]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_mroute.c
kern_sig.c: ANSIfy and remove archaic register keyword
[FreeBSD/FreeBSD.git] / sys / netinet / ip_mroute.c
1 /*-
2  * Copyright (c) 1989 Stephen Deering
3  * Copyright (c) 1992, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Stephen Deering of Stanford University.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)ip_mroute.c 8.2 (Berkeley) 11/15/93
34  */
35
36 /*
37  * IP multicast forwarding procedures
38  *
39  * Written by David Waitzman, BBN Labs, August 1988.
40  * Modified by Steve Deering, Stanford, February 1989.
41  * Modified by Mark J. Steiglitz, Stanford, May, 1991
42  * Modified by Van Jacobson, LBL, January 1993
43  * Modified by Ajit Thyagarajan, PARC, August 1993
44  * Modified by Bill Fenner, PARC, April 1995
45  * Modified by Ahmed Helmy, SGI, June 1996
46  * Modified by George Edmond Eddy (Rusty), ISI, February 1998
47  * Modified by Pavlin Radoslavov, USC/ISI, May 1998, August 1999, October 2000
48  * Modified by Hitoshi Asaeda, WIDE, August 2000
49  * Modified by Pavlin Radoslavov, ICSI, October 2002
50  *
51  * MROUTING Revision: 3.5
52  * and PIM-SMv2 and PIM-DM support, advanced API support,
53  * bandwidth metering and signaling
54  */
55
56 /*
57  * TODO: Prefix functions with ipmf_.
58  * TODO: Maintain a refcount on if_allmulti() in ifnet or in the protocol
59  * domain attachment (if_afdata) so we can track consumers of that service.
60  * TODO: Deprecate routing socket path for SIOCGETSGCNT and SIOCGETVIFCNT,
61  * move it to socket options.
62  * TODO: Cleanup LSRR removal further.
63  * TODO: Push RSVP stubs into raw_ip.c.
64  * TODO: Use bitstring.h for vif set.
65  * TODO: Fix mrt6_ioctl dangling ref when dynamically loaded.
66  * TODO: Sync ip6_mroute.c with this file.
67  */
68
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
71
72 #include "opt_inet.h"
73 #include "opt_mrouting.h"
74
75 #define _PIM_VT 1
76
77 #include <sys/param.h>
78 #include <sys/kernel.h>
79 #include <sys/stddef.h>
80 #include <sys/eventhandler.h>
81 #include <sys/lock.h>
82 #include <sys/ktr.h>
83 #include <sys/malloc.h>
84 #include <sys/mbuf.h>
85 #include <sys/module.h>
86 #include <sys/priv.h>
87 #include <sys/protosw.h>
88 #include <sys/signalvar.h>
89 #include <sys/socket.h>
90 #include <sys/socketvar.h>
91 #include <sys/sockio.h>
92 #include <sys/sx.h>
93 #include <sys/sysctl.h>
94 #include <sys/syslog.h>
95 #include <sys/systm.h>
96 #include <sys/time.h>
97 #include <sys/counter.h>
98
99 #include <net/if.h>
100 #include <net/if_var.h>
101 #include <net/netisr.h>
102 #include <net/route.h>
103 #include <net/vnet.h>
104
105 #include <netinet/in.h>
106 #include <netinet/igmp.h>
107 #include <netinet/in_systm.h>
108 #include <netinet/in_var.h>
109 #include <netinet/ip.h>
110 #include <netinet/ip_encap.h>
111 #include <netinet/ip_mroute.h>
112 #include <netinet/ip_var.h>
113 #include <netinet/ip_options.h>
114 #include <netinet/pim.h>
115 #include <netinet/pim_var.h>
116 #include <netinet/udp.h>
117
118 #include <machine/in_cksum.h>
119
120 #ifndef KTR_IPMF
121 #define KTR_IPMF KTR_INET
122 #endif
123
124 #define         VIFI_INVALID    ((vifi_t) -1)
125
126 static VNET_DEFINE(uint32_t, last_tv_sec); /* last time we processed this */
127 #define V_last_tv_sec   VNET(last_tv_sec)
128
129 static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast forwarding cache");
130
131 /*
132  * Locking.  We use two locks: one for the virtual interface table and
133  * one for the forwarding table.  These locks may be nested in which case
134  * the VIF lock must always be taken first.  Note that each lock is used
135  * to cover not only the specific data structure but also related data
136  * structures.
137  */
138
139 static struct mtx mrouter_mtx;
140 #define MROUTER_LOCK()          mtx_lock(&mrouter_mtx)
141 #define MROUTER_UNLOCK()        mtx_unlock(&mrouter_mtx)
142 #define MROUTER_LOCK_ASSERT()   mtx_assert(&mrouter_mtx, MA_OWNED)
143 #define MROUTER_LOCK_INIT()                                             \
144         mtx_init(&mrouter_mtx, "IPv4 multicast forwarding", NULL, MTX_DEF)
145 #define MROUTER_LOCK_DESTROY()  mtx_destroy(&mrouter_mtx)
146
147 static int ip_mrouter_cnt;      /* # of vnets with active mrouters */
148 static int ip_mrouter_unloading; /* Allow no more V_ip_mrouter sockets */
149
150 static VNET_PCPUSTAT_DEFINE(struct mrtstat, mrtstat);
151 VNET_PCPUSTAT_SYSINIT(mrtstat);
152 VNET_PCPUSTAT_SYSUNINIT(mrtstat);
153 SYSCTL_VNET_PCPUSTAT(_net_inet_ip, OID_AUTO, mrtstat, struct mrtstat,
154     mrtstat, "IPv4 Multicast Forwarding Statistics (struct mrtstat, "
155     "netinet/ip_mroute.h)");
156
157 static VNET_DEFINE(u_long, mfchash);
158 #define V_mfchash               VNET(mfchash)
159 #define MFCHASH(a, g)                                                   \
160         ((((a).s_addr >> 20) ^ ((a).s_addr >> 10) ^ (a).s_addr ^ \
161           ((g).s_addr >> 20) ^ ((g).s_addr >> 10) ^ (g).s_addr) & V_mfchash)
162 #define MFCHASHSIZE     256
163
164 static u_long mfchashsize;                      /* Hash size */
165 static VNET_DEFINE(u_char *, nexpire);          /* 0..mfchashsize-1 */
166 #define V_nexpire               VNET(nexpire)
167 static VNET_DEFINE(LIST_HEAD(mfchashhdr, mfc)*, mfchashtbl);
168 #define V_mfchashtbl            VNET(mfchashtbl)
169
170 static struct mtx mfc_mtx;
171 #define MFC_LOCK()              mtx_lock(&mfc_mtx)
172 #define MFC_UNLOCK()            mtx_unlock(&mfc_mtx)
173 #define MFC_LOCK_ASSERT()       mtx_assert(&mfc_mtx, MA_OWNED)
174 #define MFC_LOCK_INIT()                                                 \
175         mtx_init(&mfc_mtx, "IPv4 multicast forwarding cache", NULL, MTX_DEF)
176 #define MFC_LOCK_DESTROY()      mtx_destroy(&mfc_mtx)
177
178 static VNET_DEFINE(vifi_t, numvifs);
179 #define V_numvifs               VNET(numvifs)
180 static VNET_DEFINE(struct vif, viftable[MAXVIFS]);
181 #define V_viftable              VNET(viftable)
182 SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, viftable, CTLFLAG_VNET | CTLFLAG_RD,
183     &VNET_NAME(viftable), sizeof(V_viftable), "S,vif[MAXVIFS]",
184     "IPv4 Multicast Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
185
186 static struct mtx vif_mtx;
187 #define VIF_LOCK()              mtx_lock(&vif_mtx)
188 #define VIF_UNLOCK()            mtx_unlock(&vif_mtx)
189 #define VIF_LOCK_ASSERT()       mtx_assert(&vif_mtx, MA_OWNED)
190 #define VIF_LOCK_INIT()                                                 \
191         mtx_init(&vif_mtx, "IPv4 multicast interfaces", NULL, MTX_DEF)
192 #define VIF_LOCK_DESTROY()      mtx_destroy(&vif_mtx)
193
194 static eventhandler_tag if_detach_event_tag = NULL;
195
196 static VNET_DEFINE(struct callout, expire_upcalls_ch);
197 #define V_expire_upcalls_ch     VNET(expire_upcalls_ch)
198
199 #define         EXPIRE_TIMEOUT  (hz / 4)        /* 4x / second          */
200 #define         UPCALL_EXPIRE   6               /* number of timeouts   */
201
202 /*
203  * Bandwidth meter variables and constants
204  */
205 static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
206 /*
207  * Pending timeouts are stored in a hash table, the key being the
208  * expiration time. Periodically, the entries are analysed and processed.
209  */
210 #define BW_METER_BUCKETS        1024
211 static VNET_DEFINE(struct bw_meter*, bw_meter_timers[BW_METER_BUCKETS]);
212 #define V_bw_meter_timers       VNET(bw_meter_timers)
213 static VNET_DEFINE(struct callout, bw_meter_ch);
214 #define V_bw_meter_ch           VNET(bw_meter_ch)
215 #define BW_METER_PERIOD (hz)            /* periodical handling of bw meters */
216
217 /*
218  * Pending upcalls are stored in a vector which is flushed when
219  * full, or periodically
220  */
221 static VNET_DEFINE(struct bw_upcall, bw_upcalls[BW_UPCALLS_MAX]);
222 #define V_bw_upcalls            VNET(bw_upcalls)
223 static VNET_DEFINE(u_int, bw_upcalls_n); /* # of pending upcalls */
224 #define V_bw_upcalls_n          VNET(bw_upcalls_n)
225 static VNET_DEFINE(struct callout, bw_upcalls_ch);
226 #define V_bw_upcalls_ch         VNET(bw_upcalls_ch)
227
228 #define BW_UPCALLS_PERIOD (hz)          /* periodical flush of bw upcalls */
229
230 static VNET_PCPUSTAT_DEFINE(struct pimstat, pimstat);
231 VNET_PCPUSTAT_SYSINIT(pimstat);
232 VNET_PCPUSTAT_SYSUNINIT(pimstat);
233
234 SYSCTL_NODE(_net_inet, IPPROTO_PIM, pim, CTLFLAG_RW, 0, "PIM");
235 SYSCTL_VNET_PCPUSTAT(_net_inet_pim, PIMCTL_STATS, stats, struct pimstat,
236     pimstat, "PIM Statistics (struct pimstat, netinet/pim_var.h)");
237
238 static u_long   pim_squelch_wholepkt = 0;
239 SYSCTL_ULONG(_net_inet_pim, OID_AUTO, squelch_wholepkt, CTLFLAG_RW,
240     &pim_squelch_wholepkt, 0,
241     "Disable IGMP_WHOLEPKT notifications if rendezvous point is unspecified");
242
243 extern  struct domain inetdomain;
244 static const struct protosw in_pim_protosw = {
245         .pr_type =              SOCK_RAW,
246         .pr_domain =            &inetdomain,
247         .pr_protocol =          IPPROTO_PIM,
248         .pr_flags =             PR_ATOMIC|PR_ADDR|PR_LASTHDR,
249         .pr_input =             pim_input,
250         .pr_output =            rip_output,
251         .pr_ctloutput =         rip_ctloutput,
252         .pr_usrreqs =           &rip_usrreqs
253 };
254 static const struct encaptab *pim_encap_cookie;
255
256 static int pim_encapcheck(const struct mbuf *, int, int, void *);
257
258 /*
259  * Note: the PIM Register encapsulation adds the following in front of a
260  * data packet:
261  *
262  * struct pim_encap_hdr {
263  *    struct ip ip;
264  *    struct pim_encap_pimhdr  pim;
265  * }
266  *
267  */
268
269 struct pim_encap_pimhdr {
270         struct pim pim;
271         uint32_t   flags;
272 };
273 #define         PIM_ENCAP_TTL   64
274
275 static struct ip pim_encap_iphdr = {
276 #if BYTE_ORDER == LITTLE_ENDIAN
277         sizeof(struct ip) >> 2,
278         IPVERSION,
279 #else
280         IPVERSION,
281         sizeof(struct ip) >> 2,
282 #endif
283         0,                      /* tos */
284         sizeof(struct ip),      /* total length */
285         0,                      /* id */
286         0,                      /* frag offset */
287         PIM_ENCAP_TTL,
288         IPPROTO_PIM,
289         0,                      /* checksum */
290 };
291
292 static struct pim_encap_pimhdr pim_encap_pimhdr = {
293     {
294         PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
295         0,                      /* reserved */
296         0,                      /* checksum */
297     },
298     0                           /* flags */
299 };
300
301 static VNET_DEFINE(vifi_t, reg_vif_num) = VIFI_INVALID;
302 #define V_reg_vif_num           VNET(reg_vif_num)
303 static VNET_DEFINE(struct ifnet, multicast_register_if);
304 #define V_multicast_register_if VNET(multicast_register_if)
305
306 /*
307  * Private variables.
308  */
309
310 static u_long   X_ip_mcast_src(int);
311 static int      X_ip_mforward(struct ip *, struct ifnet *, struct mbuf *,
312                     struct ip_moptions *);
313 static int      X_ip_mrouter_done(void);
314 static int      X_ip_mrouter_get(struct socket *, struct sockopt *);
315 static int      X_ip_mrouter_set(struct socket *, struct sockopt *);
316 static int      X_legal_vif_num(int);
317 static int      X_mrt_ioctl(u_long, caddr_t, int);
318
319 static int      add_bw_upcall(struct bw_upcall *);
320 static int      add_mfc(struct mfcctl2 *);
321 static int      add_vif(struct vifctl *);
322 static void     bw_meter_prepare_upcall(struct bw_meter *, struct timeval *);
323 static void     bw_meter_process(void);
324 static void     bw_meter_receive_packet(struct bw_meter *, int,
325                     struct timeval *);
326 static void     bw_upcalls_send(void);
327 static int      del_bw_upcall(struct bw_upcall *);
328 static int      del_mfc(struct mfcctl2 *);
329 static int      del_vif(vifi_t);
330 static int      del_vif_locked(vifi_t);
331 static void     expire_bw_meter_process(void *);
332 static void     expire_bw_upcalls_send(void *);
333 static void     expire_mfc(struct mfc *);
334 static void     expire_upcalls(void *);
335 static void     free_bw_list(struct bw_meter *);
336 static int      get_sg_cnt(struct sioc_sg_req *);
337 static int      get_vif_cnt(struct sioc_vif_req *);
338 static void     if_detached_event(void *, struct ifnet *);
339 static int      ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
340 static int      ip_mrouter_init(struct socket *, int);
341 static __inline struct mfc *
342                 mfc_find(struct in_addr *, struct in_addr *);
343 static void     phyint_send(struct ip *, struct vif *, struct mbuf *);
344 static struct mbuf *
345                 pim_register_prepare(struct ip *, struct mbuf *);
346 static int      pim_register_send(struct ip *, struct vif *,
347                     struct mbuf *, struct mfc *);
348 static int      pim_register_send_rp(struct ip *, struct vif *,
349                     struct mbuf *, struct mfc *);
350 static int      pim_register_send_upcall(struct ip *, struct vif *,
351                     struct mbuf *, struct mfc *);
352 static void     schedule_bw_meter(struct bw_meter *, struct timeval *);
353 static void     send_packet(struct vif *, struct mbuf *);
354 static int      set_api_config(uint32_t *);
355 static int      set_assert(int);
356 static int      socket_send(struct socket *, struct mbuf *,
357                     struct sockaddr_in *);
358 static void     unschedule_bw_meter(struct bw_meter *);
359
360 /*
361  * Kernel multicast forwarding API capabilities and setup.
362  * If more API capabilities are added to the kernel, they should be
363  * recorded in `mrt_api_support'.
364  */
365 #define MRT_API_VERSION         0x0305
366
367 static const int mrt_api_version = MRT_API_VERSION;
368 static const uint32_t mrt_api_support = (MRT_MFC_FLAGS_DISABLE_WRONGVIF |
369                                          MRT_MFC_FLAGS_BORDER_VIF |
370                                          MRT_MFC_RP |
371                                          MRT_MFC_BW_UPCALL);
372 static VNET_DEFINE(uint32_t, mrt_api_config);
373 #define V_mrt_api_config        VNET(mrt_api_config)
374 static VNET_DEFINE(int, pim_assert_enabled);
375 #define V_pim_assert_enabled    VNET(pim_assert_enabled)
376 static struct timeval pim_assert_interval = { 3, 0 };   /* Rate limit */
377
378 /*
379  * Find a route for a given origin IP address and multicast group address.
380  * Statistics must be updated by the caller.
381  */
382 static __inline struct mfc *
383 mfc_find(struct in_addr *o, struct in_addr *g)
384 {
385         struct mfc *rt;
386
387         MFC_LOCK_ASSERT();
388
389         LIST_FOREACH(rt, &V_mfchashtbl[MFCHASH(*o, *g)], mfc_hash) {
390                 if (in_hosteq(rt->mfc_origin, *o) &&
391                     in_hosteq(rt->mfc_mcastgrp, *g) &&
392                     TAILQ_EMPTY(&rt->mfc_stall))
393                         break;
394         }
395
396         return (rt);
397 }
398
399 /*
400  * Handle MRT setsockopt commands to modify the multicast forwarding tables.
401  */
402 static int
403 X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
404 {
405     int error, optval;
406     vifi_t      vifi;
407     struct      vifctl vifc;
408     struct      mfcctl2 mfc;
409     struct      bw_upcall bw_upcall;
410     uint32_t    i;
411
412     if (so != V_ip_mrouter && sopt->sopt_name != MRT_INIT)
413         return EPERM;
414
415     error = 0;
416     switch (sopt->sopt_name) {
417     case MRT_INIT:
418         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
419         if (error)
420             break;
421         error = ip_mrouter_init(so, optval);
422         break;
423
424     case MRT_DONE:
425         error = ip_mrouter_done();
426         break;
427
428     case MRT_ADD_VIF:
429         error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
430         if (error)
431             break;
432         error = add_vif(&vifc);
433         break;
434
435     case MRT_DEL_VIF:
436         error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
437         if (error)
438             break;
439         error = del_vif(vifi);
440         break;
441
442     case MRT_ADD_MFC:
443     case MRT_DEL_MFC:
444         /*
445          * select data size depending on API version.
446          */
447         if (sopt->sopt_name == MRT_ADD_MFC &&
448                 V_mrt_api_config & MRT_API_FLAGS_ALL) {
449             error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl2),
450                                 sizeof(struct mfcctl2));
451         } else {
452             error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl),
453                                 sizeof(struct mfcctl));
454             bzero((caddr_t)&mfc + sizeof(struct mfcctl),
455                         sizeof(mfc) - sizeof(struct mfcctl));
456         }
457         if (error)
458             break;
459         if (sopt->sopt_name == MRT_ADD_MFC)
460             error = add_mfc(&mfc);
461         else
462             error = del_mfc(&mfc);
463         break;
464
465     case MRT_ASSERT:
466         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
467         if (error)
468             break;
469         set_assert(optval);
470         break;
471
472     case MRT_API_CONFIG:
473         error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
474         if (!error)
475             error = set_api_config(&i);
476         if (!error)
477             error = sooptcopyout(sopt, &i, sizeof i);
478         break;
479
480     case MRT_ADD_BW_UPCALL:
481     case MRT_DEL_BW_UPCALL:
482         error = sooptcopyin(sopt, &bw_upcall, sizeof bw_upcall,
483                                 sizeof bw_upcall);
484         if (error)
485             break;
486         if (sopt->sopt_name == MRT_ADD_BW_UPCALL)
487             error = add_bw_upcall(&bw_upcall);
488         else
489             error = del_bw_upcall(&bw_upcall);
490         break;
491
492     default:
493         error = EOPNOTSUPP;
494         break;
495     }
496     return error;
497 }
498
499 /*
500  * Handle MRT getsockopt commands
501  */
502 static int
503 X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
504 {
505     int error;
506
507     switch (sopt->sopt_name) {
508     case MRT_VERSION:
509         error = sooptcopyout(sopt, &mrt_api_version, sizeof mrt_api_version);
510         break;
511
512     case MRT_ASSERT:
513         error = sooptcopyout(sopt, &V_pim_assert_enabled,
514             sizeof V_pim_assert_enabled);
515         break;
516
517     case MRT_API_SUPPORT:
518         error = sooptcopyout(sopt, &mrt_api_support, sizeof mrt_api_support);
519         break;
520
521     case MRT_API_CONFIG:
522         error = sooptcopyout(sopt, &V_mrt_api_config, sizeof V_mrt_api_config);
523         break;
524
525     default:
526         error = EOPNOTSUPP;
527         break;
528     }
529     return error;
530 }
531
532 /*
533  * Handle ioctl commands to obtain information from the cache
534  */
535 static int
536 X_mrt_ioctl(u_long cmd, caddr_t data, int fibnum __unused)
537 {
538     int error = 0;
539
540     /*
541      * Currently the only function calling this ioctl routine is rtioctl_fib().
542      * Typically, only root can create the raw socket in order to execute
543      * this ioctl method, however the request might be coming from a prison
544      */
545     error = priv_check(curthread, PRIV_NETINET_MROUTE);
546     if (error)
547         return (error);
548     switch (cmd) {
549     case (SIOCGETVIFCNT):
550         error = get_vif_cnt((struct sioc_vif_req *)data);
551         break;
552
553     case (SIOCGETSGCNT):
554         error = get_sg_cnt((struct sioc_sg_req *)data);
555         break;
556
557     default:
558         error = EINVAL;
559         break;
560     }
561     return error;
562 }
563
564 /*
565  * returns the packet, byte, rpf-failure count for the source group provided
566  */
567 static int
568 get_sg_cnt(struct sioc_sg_req *req)
569 {
570     struct mfc *rt;
571
572     MFC_LOCK();
573     rt = mfc_find(&req->src, &req->grp);
574     if (rt == NULL) {
575         MFC_UNLOCK();
576         req->pktcnt = req->bytecnt = req->wrong_if = 0xffffffff;
577         return EADDRNOTAVAIL;
578     }
579     req->pktcnt = rt->mfc_pkt_cnt;
580     req->bytecnt = rt->mfc_byte_cnt;
581     req->wrong_if = rt->mfc_wrong_if;
582     MFC_UNLOCK();
583     return 0;
584 }
585
586 /*
587  * returns the input and output packet and byte counts on the vif provided
588  */
589 static int
590 get_vif_cnt(struct sioc_vif_req *req)
591 {
592     vifi_t vifi = req->vifi;
593
594     VIF_LOCK();
595     if (vifi >= V_numvifs) {
596         VIF_UNLOCK();
597         return EINVAL;
598     }
599
600     req->icount = V_viftable[vifi].v_pkt_in;
601     req->ocount = V_viftable[vifi].v_pkt_out;
602     req->ibytes = V_viftable[vifi].v_bytes_in;
603     req->obytes = V_viftable[vifi].v_bytes_out;
604     VIF_UNLOCK();
605
606     return 0;
607 }
608
609 static void
610 if_detached_event(void *arg __unused, struct ifnet *ifp)
611 {
612     vifi_t vifi;
613     u_long i;
614
615     MROUTER_LOCK();
616
617     if (V_ip_mrouter == NULL) {
618         MROUTER_UNLOCK();
619         return;
620     }
621
622     VIF_LOCK();
623     MFC_LOCK();
624
625     /*
626      * Tear down multicast forwarder state associated with this ifnet.
627      * 1. Walk the vif list, matching vifs against this ifnet.
628      * 2. Walk the multicast forwarding cache (mfc) looking for
629      *    inner matches with this vif's index.
630      * 3. Expire any matching multicast forwarding cache entries.
631      * 4. Free vif state. This should disable ALLMULTI on the interface.
632      */
633     for (vifi = 0; vifi < V_numvifs; vifi++) {
634         if (V_viftable[vifi].v_ifp != ifp)
635                 continue;
636         for (i = 0; i < mfchashsize; i++) {
637                 struct mfc *rt, *nrt;
638
639                 LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
640                         if (rt->mfc_parent == vifi) {
641                                 expire_mfc(rt);
642                         }
643                 }
644         }
645         del_vif_locked(vifi);
646     }
647
648     MFC_UNLOCK();
649     VIF_UNLOCK();
650
651     MROUTER_UNLOCK();
652 }
653                         
654 /*
655  * Enable multicast forwarding.
656  */
657 static int
658 ip_mrouter_init(struct socket *so, int version)
659 {
660
661     CTR3(KTR_IPMF, "%s: so_type %d, pr_protocol %d", __func__,
662         so->so_type, so->so_proto->pr_protocol);
663
664     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_IGMP)
665         return EOPNOTSUPP;
666
667     if (version != 1)
668         return ENOPROTOOPT;
669
670     MROUTER_LOCK();
671
672     if (ip_mrouter_unloading) {
673         MROUTER_UNLOCK();
674         return ENOPROTOOPT;
675     }
676
677     if (V_ip_mrouter != NULL) {
678         MROUTER_UNLOCK();
679         return EADDRINUSE;
680     }
681
682     V_mfchashtbl = hashinit_flags(mfchashsize, M_MRTABLE, &V_mfchash,
683         HASH_NOWAIT);
684
685     callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
686         curvnet);
687     callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
688         curvnet);
689     callout_reset(&V_bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process,
690         curvnet);
691
692     V_ip_mrouter = so;
693     ip_mrouter_cnt++;
694
695     MROUTER_UNLOCK();
696
697     CTR1(KTR_IPMF, "%s: done", __func__);
698
699     return 0;
700 }
701
702 /*
703  * Disable multicast forwarding.
704  */
705 static int
706 X_ip_mrouter_done(void)
707 {
708     struct ifnet *ifp;
709     u_long i;
710     vifi_t vifi;
711
712     MROUTER_LOCK();
713
714     if (V_ip_mrouter == NULL) {
715         MROUTER_UNLOCK();
716         return EINVAL;
717     }
718
719     /*
720      * Detach/disable hooks to the reset of the system.
721      */
722     V_ip_mrouter = NULL;
723     ip_mrouter_cnt--;
724     V_mrt_api_config = 0;
725
726     VIF_LOCK();
727
728     /*
729      * For each phyint in use, disable promiscuous reception of all IP
730      * multicasts.
731      */
732     for (vifi = 0; vifi < V_numvifs; vifi++) {
733         if (!in_nullhost(V_viftable[vifi].v_lcl_addr) &&
734                 !(V_viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
735             ifp = V_viftable[vifi].v_ifp;
736             if_allmulti(ifp, 0);
737         }
738     }
739     bzero((caddr_t)V_viftable, sizeof(V_viftable));
740     V_numvifs = 0;
741     V_pim_assert_enabled = 0;
742     
743     VIF_UNLOCK();
744
745     callout_stop(&V_expire_upcalls_ch);
746     callout_stop(&V_bw_upcalls_ch);
747     callout_stop(&V_bw_meter_ch);
748
749     MFC_LOCK();
750
751     /*
752      * Free all multicast forwarding cache entries.
753      * Do not use hashdestroy(), as we must perform other cleanup.
754      */
755     for (i = 0; i < mfchashsize; i++) {
756         struct mfc *rt, *nrt;
757
758         LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
759                 expire_mfc(rt);
760         }
761     }
762     free(V_mfchashtbl, M_MRTABLE);
763     V_mfchashtbl = NULL;
764
765     bzero(V_nexpire, sizeof(V_nexpire[0]) * mfchashsize);
766
767     V_bw_upcalls_n = 0;
768     bzero(V_bw_meter_timers, sizeof(V_bw_meter_timers));
769
770     MFC_UNLOCK();
771
772     V_reg_vif_num = VIFI_INVALID;
773
774     MROUTER_UNLOCK();
775
776     CTR1(KTR_IPMF, "%s: done", __func__);
777
778     return 0;
779 }
780
781 /*
782  * Set PIM assert processing global
783  */
784 static int
785 set_assert(int i)
786 {
787     if ((i != 1) && (i != 0))
788         return EINVAL;
789
790     V_pim_assert_enabled = i;
791
792     return 0;
793 }
794
795 /*
796  * Configure API capabilities
797  */
798 int
799 set_api_config(uint32_t *apival)
800 {
801     u_long i;
802
803     /*
804      * We can set the API capabilities only if it is the first operation
805      * after MRT_INIT. I.e.:
806      *  - there are no vifs installed
807      *  - pim_assert is not enabled
808      *  - the MFC table is empty
809      */
810     if (V_numvifs > 0) {
811         *apival = 0;
812         return EPERM;
813     }
814     if (V_pim_assert_enabled) {
815         *apival = 0;
816         return EPERM;
817     }
818
819     MFC_LOCK();
820
821     for (i = 0; i < mfchashsize; i++) {
822         if (LIST_FIRST(&V_mfchashtbl[i]) != NULL) {
823             MFC_UNLOCK();
824             *apival = 0;
825             return EPERM;
826         }
827     }
828
829     MFC_UNLOCK();
830
831     V_mrt_api_config = *apival & mrt_api_support;
832     *apival = V_mrt_api_config;
833
834     return 0;
835 }
836
837 /*
838  * Add a vif to the vif table
839  */
840 static int
841 add_vif(struct vifctl *vifcp)
842 {
843     struct vif *vifp = V_viftable + vifcp->vifc_vifi;
844     struct sockaddr_in sin = {sizeof sin, AF_INET};
845     struct ifaddr *ifa;
846     struct ifnet *ifp;
847     int error;
848 #ifdef KTR
849     char addrbuf[INET_ADDRSTRLEN];
850 #endif
851
852     VIF_LOCK();
853     if (vifcp->vifc_vifi >= MAXVIFS) {
854         VIF_UNLOCK();
855         return EINVAL;
856     }
857     /* rate limiting is no longer supported by this code */
858     if (vifcp->vifc_rate_limit != 0) {
859         log(LOG_ERR, "rate limiting is no longer supported\n");
860         VIF_UNLOCK();
861         return EINVAL;
862     }
863     if (!in_nullhost(vifp->v_lcl_addr)) {
864         VIF_UNLOCK();
865         return EADDRINUSE;
866     }
867     if (in_nullhost(vifcp->vifc_lcl_addr)) {
868         VIF_UNLOCK();
869         return EADDRNOTAVAIL;
870     }
871
872     /* Find the interface with an address in AF_INET family */
873     if (vifcp->vifc_flags & VIFF_REGISTER) {
874         /*
875          * XXX: Because VIFF_REGISTER does not really need a valid
876          * local interface (e.g. it could be 127.0.0.2), we don't
877          * check its address.
878          */
879         ifp = NULL;
880     } else {
881         sin.sin_addr = vifcp->vifc_lcl_addr;
882         ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
883         if (ifa == NULL) {
884             VIF_UNLOCK();
885             return EADDRNOTAVAIL;
886         }
887         ifp = ifa->ifa_ifp;
888         ifa_free(ifa);
889     }
890
891     if ((vifcp->vifc_flags & VIFF_TUNNEL) != 0) {
892         CTR1(KTR_IPMF, "%s: tunnels are no longer supported", __func__);
893         VIF_UNLOCK();
894         return EOPNOTSUPP;
895     } else if (vifcp->vifc_flags & VIFF_REGISTER) {
896         ifp = &V_multicast_register_if;
897         CTR2(KTR_IPMF, "%s: add register vif for ifp %p", __func__, ifp);
898         if (V_reg_vif_num == VIFI_INVALID) {
899             if_initname(&V_multicast_register_if, "register_vif", 0);
900             V_multicast_register_if.if_flags = IFF_LOOPBACK;
901             V_reg_vif_num = vifcp->vifc_vifi;
902         }
903     } else {            /* Make sure the interface supports multicast */
904         if ((ifp->if_flags & IFF_MULTICAST) == 0) {
905             VIF_UNLOCK();
906             return EOPNOTSUPP;
907         }
908
909         /* Enable promiscuous reception of all IP multicasts from the if */
910         error = if_allmulti(ifp, 1);
911         if (error) {
912             VIF_UNLOCK();
913             return error;
914         }
915     }
916
917     vifp->v_flags     = vifcp->vifc_flags;
918     vifp->v_threshold = vifcp->vifc_threshold;
919     vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
920     vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
921     vifp->v_ifp       = ifp;
922     /* initialize per vif pkt counters */
923     vifp->v_pkt_in    = 0;
924     vifp->v_pkt_out   = 0;
925     vifp->v_bytes_in  = 0;
926     vifp->v_bytes_out = 0;
927
928     /* Adjust numvifs up if the vifi is higher than numvifs */
929     if (V_numvifs <= vifcp->vifc_vifi)
930         V_numvifs = vifcp->vifc_vifi + 1;
931
932     VIF_UNLOCK();
933
934     CTR4(KTR_IPMF, "%s: add vif %d laddr %s thresh %x", __func__,
935         (int)vifcp->vifc_vifi, inet_ntoa_r(vifcp->vifc_lcl_addr, addrbuf),
936         (int)vifcp->vifc_threshold);
937
938     return 0;
939 }
940
941 /*
942  * Delete a vif from the vif table
943  */
944 static int
945 del_vif_locked(vifi_t vifi)
946 {
947     struct vif *vifp;
948
949     VIF_LOCK_ASSERT();
950
951     if (vifi >= V_numvifs) {
952         return EINVAL;
953     }
954     vifp = &V_viftable[vifi];
955     if (in_nullhost(vifp->v_lcl_addr)) {
956         return EADDRNOTAVAIL;
957     }
958
959     if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
960         if_allmulti(vifp->v_ifp, 0);
961
962     if (vifp->v_flags & VIFF_REGISTER)
963         V_reg_vif_num = VIFI_INVALID;
964
965     bzero((caddr_t)vifp, sizeof (*vifp));
966
967     CTR2(KTR_IPMF, "%s: delete vif %d", __func__, (int)vifi);
968
969     /* Adjust numvifs down */
970     for (vifi = V_numvifs; vifi > 0; vifi--)
971         if (!in_nullhost(V_viftable[vifi-1].v_lcl_addr))
972             break;
973     V_numvifs = vifi;
974
975     return 0;
976 }
977
978 static int
979 del_vif(vifi_t vifi)
980 {
981     int cc;
982
983     VIF_LOCK();
984     cc = del_vif_locked(vifi);
985     VIF_UNLOCK();
986
987     return cc;
988 }
989
990 /*
991  * update an mfc entry without resetting counters and S,G addresses.
992  */
993 static void
994 update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
995 {
996     int i;
997
998     rt->mfc_parent = mfccp->mfcc_parent;
999     for (i = 0; i < V_numvifs; i++) {
1000         rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1001         rt->mfc_flags[i] = mfccp->mfcc_flags[i] & V_mrt_api_config &
1002             MRT_MFC_FLAGS_ALL;
1003     }
1004     /* set the RP address */
1005     if (V_mrt_api_config & MRT_MFC_RP)
1006         rt->mfc_rp = mfccp->mfcc_rp;
1007     else
1008         rt->mfc_rp.s_addr = INADDR_ANY;
1009 }
1010
1011 /*
1012  * fully initialize an mfc entry from the parameter.
1013  */
1014 static void
1015 init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1016 {
1017     rt->mfc_origin     = mfccp->mfcc_origin;
1018     rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
1019
1020     update_mfc_params(rt, mfccp);
1021
1022     /* initialize pkt counters per src-grp */
1023     rt->mfc_pkt_cnt    = 0;
1024     rt->mfc_byte_cnt   = 0;
1025     rt->mfc_wrong_if   = 0;
1026     timevalclear(&rt->mfc_last_assert);
1027 }
1028
1029 static void
1030 expire_mfc(struct mfc *rt)
1031 {
1032         struct rtdetq *rte, *nrte;
1033
1034         MFC_LOCK_ASSERT();
1035
1036         free_bw_list(rt->mfc_bw_meter);
1037
1038         TAILQ_FOREACH_SAFE(rte, &rt->mfc_stall, rte_link, nrte) {
1039                 m_freem(rte->m);
1040                 TAILQ_REMOVE(&rt->mfc_stall, rte, rte_link);
1041                 free(rte, M_MRTABLE);
1042         }
1043
1044         LIST_REMOVE(rt, mfc_hash);
1045         free(rt, M_MRTABLE);
1046 }
1047
1048 /*
1049  * Add an mfc entry
1050  */
1051 static int
1052 add_mfc(struct mfcctl2 *mfccp)
1053 {
1054     struct mfc *rt;
1055     struct rtdetq *rte, *nrte;
1056     u_long hash = 0;
1057     u_short nstl;
1058 #ifdef KTR
1059     char addrbuf[INET_ADDRSTRLEN];
1060 #endif
1061
1062     VIF_LOCK();
1063     MFC_LOCK();
1064
1065     rt = mfc_find(&mfccp->mfcc_origin, &mfccp->mfcc_mcastgrp);
1066
1067     /* If an entry already exists, just update the fields */
1068     if (rt) {
1069         CTR4(KTR_IPMF, "%s: update mfc orig %s group %lx parent %x",
1070             __func__, inet_ntoa_r(mfccp->mfcc_origin, addrbuf),
1071             (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1072             mfccp->mfcc_parent);
1073         update_mfc_params(rt, mfccp);
1074         MFC_UNLOCK();
1075         VIF_UNLOCK();
1076         return (0);
1077     }
1078
1079     /*
1080      * Find the entry for which the upcall was made and update
1081      */
1082     nstl = 0;
1083     hash = MFCHASH(mfccp->mfcc_origin, mfccp->mfcc_mcastgrp);
1084     LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1085         if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1086             in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp) &&
1087             !TAILQ_EMPTY(&rt->mfc_stall)) {
1088                 CTR5(KTR_IPMF,
1089                     "%s: add mfc orig %s group %lx parent %x qh %p",
1090                     __func__, inet_ntoa_r(mfccp->mfcc_origin, addrbuf),
1091                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1092                     mfccp->mfcc_parent,
1093                     TAILQ_FIRST(&rt->mfc_stall));
1094                 if (nstl++)
1095                         CTR1(KTR_IPMF, "%s: multiple matches", __func__);
1096
1097                 init_mfc_params(rt, mfccp);
1098                 rt->mfc_expire = 0;     /* Don't clean this guy up */
1099                 V_nexpire[hash]--;
1100
1101                 /* Free queued packets, but attempt to forward them first. */
1102                 TAILQ_FOREACH_SAFE(rte, &rt->mfc_stall, rte_link, nrte) {
1103                         if (rte->ifp != NULL)
1104                                 ip_mdq(rte->m, rte->ifp, rt, -1);
1105                         m_freem(rte->m);
1106                         TAILQ_REMOVE(&rt->mfc_stall, rte, rte_link);
1107                         rt->mfc_nstall--;
1108                         free(rte, M_MRTABLE);
1109                 }
1110         }
1111     }
1112
1113     /*
1114      * It is possible that an entry is being inserted without an upcall
1115      */
1116     if (nstl == 0) {
1117         CTR1(KTR_IPMF, "%s: adding mfc w/o upcall", __func__);
1118         LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1119                 if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1120                     in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp)) {
1121                         init_mfc_params(rt, mfccp);
1122                         if (rt->mfc_expire)
1123                             V_nexpire[hash]--;
1124                         rt->mfc_expire = 0;
1125                         break; /* XXX */
1126                 }
1127         }
1128
1129         if (rt == NULL) {               /* no upcall, so make a new entry */
1130             rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1131             if (rt == NULL) {
1132                 MFC_UNLOCK();
1133                 VIF_UNLOCK();
1134                 return (ENOBUFS);
1135             }
1136
1137             init_mfc_params(rt, mfccp);
1138             TAILQ_INIT(&rt->mfc_stall);
1139             rt->mfc_nstall = 0;
1140
1141             rt->mfc_expire     = 0;
1142             rt->mfc_bw_meter = NULL;
1143
1144             /* insert new entry at head of hash chain */
1145             LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1146         }
1147     }
1148
1149     MFC_UNLOCK();
1150     VIF_UNLOCK();
1151
1152     return (0);
1153 }
1154
1155 /*
1156  * Delete an mfc entry
1157  */
1158 static int
1159 del_mfc(struct mfcctl2 *mfccp)
1160 {
1161     struct in_addr      origin;
1162     struct in_addr      mcastgrp;
1163     struct mfc          *rt;
1164 #ifdef KTR
1165     char                addrbuf[INET_ADDRSTRLEN];
1166 #endif
1167
1168     origin = mfccp->mfcc_origin;
1169     mcastgrp = mfccp->mfcc_mcastgrp;
1170
1171     CTR3(KTR_IPMF, "%s: delete mfc orig %s group %lx", __func__,
1172         inet_ntoa_r(origin, addrbuf), (u_long)ntohl(mcastgrp.s_addr));
1173
1174     MFC_LOCK();
1175
1176     rt = mfc_find(&origin, &mcastgrp);
1177     if (rt == NULL) {
1178         MFC_UNLOCK();
1179         return EADDRNOTAVAIL;
1180     }
1181
1182     /*
1183      * free the bw_meter entries
1184      */
1185     free_bw_list(rt->mfc_bw_meter);
1186     rt->mfc_bw_meter = NULL;
1187
1188     LIST_REMOVE(rt, mfc_hash);
1189     free(rt, M_MRTABLE);
1190
1191     MFC_UNLOCK();
1192
1193     return (0);
1194 }
1195
1196 /*
1197  * Send a message to the routing daemon on the multicast routing socket.
1198  */
1199 static int
1200 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1201 {
1202     if (s) {
1203         SOCKBUF_LOCK(&s->so_rcv);
1204         if (sbappendaddr_locked(&s->so_rcv, (struct sockaddr *)src, mm,
1205             NULL) != 0) {
1206             sorwakeup_locked(s);
1207             return 0;
1208         }
1209         SOCKBUF_UNLOCK(&s->so_rcv);
1210     }
1211     m_freem(mm);
1212     return -1;
1213 }
1214
1215 /*
1216  * IP multicast forwarding function. This function assumes that the packet
1217  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1218  * pointed to by "ifp", and the packet is to be relayed to other networks
1219  * that have members of the packet's destination IP multicast group.
1220  *
1221  * The packet is returned unscathed to the caller, unless it is
1222  * erroneous, in which case a non-zero return value tells the caller to
1223  * discard it.
1224  */
1225
1226 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1227
1228 static int
1229 X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1230     struct ip_moptions *imo)
1231 {
1232     struct mfc *rt;
1233     int error;
1234     vifi_t vifi;
1235 #ifdef KTR
1236     char addrbuf[INET_ADDRSTRLEN];
1237 #endif
1238
1239     CTR3(KTR_IPMF, "ip_mforward: delete mfc orig %s group %lx ifp %p",
1240         inet_ntoa_r(ip->ip_src, addrbuf), (u_long)ntohl(ip->ip_dst.s_addr),
1241         ifp);
1242
1243     if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1244                 ((u_char *)(ip + 1))[1] != IPOPT_LSRR ) {
1245         /*
1246          * Packet arrived via a physical interface or
1247          * an encapsulated tunnel or a register_vif.
1248          */
1249     } else {
1250         /*
1251          * Packet arrived through a source-route tunnel.
1252          * Source-route tunnels are no longer supported.
1253          */
1254         return (1);
1255     }
1256
1257     VIF_LOCK();
1258     MFC_LOCK();
1259     if (imo && ((vifi = imo->imo_multicast_vif) < V_numvifs)) {
1260         if (ip->ip_ttl < MAXTTL)
1261             ip->ip_ttl++;       /* compensate for -1 in *_send routines */
1262         error = ip_mdq(m, ifp, NULL, vifi);
1263         MFC_UNLOCK();
1264         VIF_UNLOCK();
1265         return error;
1266     }
1267
1268     /*
1269      * Don't forward a packet with time-to-live of zero or one,
1270      * or a packet destined to a local-only group.
1271      */
1272     if (ip->ip_ttl <= 1 || IN_LOCAL_GROUP(ntohl(ip->ip_dst.s_addr))) {
1273         MFC_UNLOCK();
1274         VIF_UNLOCK();
1275         return 0;
1276     }
1277
1278     /*
1279      * Determine forwarding vifs from the forwarding cache table
1280      */
1281     MRTSTAT_INC(mrts_mfc_lookups);
1282     rt = mfc_find(&ip->ip_src, &ip->ip_dst);
1283
1284     /* Entry exists, so forward if necessary */
1285     if (rt != NULL) {
1286         error = ip_mdq(m, ifp, rt, -1);
1287         MFC_UNLOCK();
1288         VIF_UNLOCK();
1289         return error;
1290     } else {
1291         /*
1292          * If we don't have a route for packet's origin,
1293          * Make a copy of the packet & send message to routing daemon
1294          */
1295
1296         struct mbuf *mb0;
1297         struct rtdetq *rte;
1298         u_long hash;
1299         int hlen = ip->ip_hl << 2;
1300
1301         MRTSTAT_INC(mrts_mfc_misses);
1302         MRTSTAT_INC(mrts_no_route);
1303         CTR2(KTR_IPMF, "ip_mforward: no mfc for (%s,%lx)",
1304             inet_ntoa_r(ip->ip_src, addrbuf), (u_long)ntohl(ip->ip_dst.s_addr));
1305
1306         /*
1307          * Allocate mbufs early so that we don't do extra work if we are
1308          * just going to fail anyway.  Make sure to pullup the header so
1309          * that other people can't step on it.
1310          */
1311         rte = (struct rtdetq *)malloc((sizeof *rte), M_MRTABLE,
1312             M_NOWAIT|M_ZERO);
1313         if (rte == NULL) {
1314             MFC_UNLOCK();
1315             VIF_UNLOCK();
1316             return ENOBUFS;
1317         }
1318
1319         mb0 = m_copypacket(m, M_NOWAIT);
1320         if (mb0 && (!M_WRITABLE(mb0) || mb0->m_len < hlen))
1321             mb0 = m_pullup(mb0, hlen);
1322         if (mb0 == NULL) {
1323             free(rte, M_MRTABLE);
1324             MFC_UNLOCK();
1325             VIF_UNLOCK();
1326             return ENOBUFS;
1327         }
1328
1329         /* is there an upcall waiting for this flow ? */
1330         hash = MFCHASH(ip->ip_src, ip->ip_dst);
1331         LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1332                 if (in_hosteq(ip->ip_src, rt->mfc_origin) &&
1333                     in_hosteq(ip->ip_dst, rt->mfc_mcastgrp) &&
1334                     !TAILQ_EMPTY(&rt->mfc_stall))
1335                         break;
1336         }
1337
1338         if (rt == NULL) {
1339             int i;
1340             struct igmpmsg *im;
1341             struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1342             struct mbuf *mm;
1343
1344             /*
1345              * Locate the vifi for the incoming interface for this packet.
1346              * If none found, drop packet.
1347              */
1348             for (vifi = 0; vifi < V_numvifs &&
1349                     V_viftable[vifi].v_ifp != ifp; vifi++)
1350                 ;
1351             if (vifi >= V_numvifs)      /* vif not found, drop packet */
1352                 goto non_fatal;
1353
1354             /* no upcall, so make a new entry */
1355             rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1356             if (rt == NULL)
1357                 goto fail;
1358
1359             /* Make a copy of the header to send to the user level process */
1360             mm = m_copym(mb0, 0, hlen, M_NOWAIT);
1361             if (mm == NULL)
1362                 goto fail1;
1363
1364             /*
1365              * Send message to routing daemon to install
1366              * a route into the kernel table
1367              */
1368
1369             im = mtod(mm, struct igmpmsg *);
1370             im->im_msgtype = IGMPMSG_NOCACHE;
1371             im->im_mbz = 0;
1372             im->im_vif = vifi;
1373
1374             MRTSTAT_INC(mrts_upcalls);
1375
1376             k_igmpsrc.sin_addr = ip->ip_src;
1377             if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1378                 CTR0(KTR_IPMF, "ip_mforward: socket queue full");
1379                 MRTSTAT_INC(mrts_upq_sockfull);
1380 fail1:
1381                 free(rt, M_MRTABLE);
1382 fail:
1383                 free(rte, M_MRTABLE);
1384                 m_freem(mb0);
1385                 MFC_UNLOCK();
1386                 VIF_UNLOCK();
1387                 return ENOBUFS;
1388             }
1389
1390             /* insert new entry at head of hash chain */
1391             rt->mfc_origin.s_addr     = ip->ip_src.s_addr;
1392             rt->mfc_mcastgrp.s_addr   = ip->ip_dst.s_addr;
1393             rt->mfc_expire            = UPCALL_EXPIRE;
1394             V_nexpire[hash]++;
1395             for (i = 0; i < V_numvifs; i++) {
1396                 rt->mfc_ttls[i] = 0;
1397                 rt->mfc_flags[i] = 0;
1398             }
1399             rt->mfc_parent = -1;
1400
1401             /* clear the RP address */
1402             rt->mfc_rp.s_addr = INADDR_ANY;
1403             rt->mfc_bw_meter = NULL;
1404
1405             /* initialize pkt counters per src-grp */
1406             rt->mfc_pkt_cnt = 0;
1407             rt->mfc_byte_cnt = 0;
1408             rt->mfc_wrong_if = 0;
1409             timevalclear(&rt->mfc_last_assert);
1410
1411             TAILQ_INIT(&rt->mfc_stall);
1412             rt->mfc_nstall = 0;
1413
1414             /* link into table */
1415             LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1416             TAILQ_INSERT_HEAD(&rt->mfc_stall, rte, rte_link);
1417             rt->mfc_nstall++;
1418
1419         } else {
1420             /* determine if queue has overflowed */
1421             if (rt->mfc_nstall > MAX_UPQ) {
1422                 MRTSTAT_INC(mrts_upq_ovflw);
1423 non_fatal:
1424                 free(rte, M_MRTABLE);
1425                 m_freem(mb0);
1426                 MFC_UNLOCK();
1427                 VIF_UNLOCK();
1428                 return (0);
1429             }
1430             TAILQ_INSERT_TAIL(&rt->mfc_stall, rte, rte_link);
1431             rt->mfc_nstall++;
1432         }
1433
1434         rte->m                  = mb0;
1435         rte->ifp                = ifp;
1436
1437         MFC_UNLOCK();
1438         VIF_UNLOCK();
1439
1440         return 0;
1441     }
1442 }
1443
1444 /*
1445  * Clean up the cache entry if upcall is not serviced
1446  */
1447 static void
1448 expire_upcalls(void *arg)
1449 {
1450     u_long i;
1451
1452     CURVNET_SET((struct vnet *) arg);
1453
1454     MFC_LOCK();
1455
1456     for (i = 0; i < mfchashsize; i++) {
1457         struct mfc *rt, *nrt;
1458
1459         if (V_nexpire[i] == 0)
1460             continue;
1461
1462         LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
1463                 if (TAILQ_EMPTY(&rt->mfc_stall))
1464                         continue;
1465
1466                 if (rt->mfc_expire == 0 || --rt->mfc_expire > 0)
1467                         continue;
1468
1469                 /*
1470                  * free the bw_meter entries
1471                  */
1472                 while (rt->mfc_bw_meter != NULL) {
1473                     struct bw_meter *x = rt->mfc_bw_meter;
1474
1475                     rt->mfc_bw_meter = x->bm_mfc_next;
1476                     free(x, M_BWMETER);
1477                 }
1478
1479                 MRTSTAT_INC(mrts_cache_cleanups);
1480                 CTR3(KTR_IPMF, "%s: expire (%lx, %lx)", __func__,
1481                     (u_long)ntohl(rt->mfc_origin.s_addr),
1482                     (u_long)ntohl(rt->mfc_mcastgrp.s_addr));
1483
1484                 expire_mfc(rt);
1485             }
1486     }
1487
1488     MFC_UNLOCK();
1489
1490     callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
1491         curvnet);
1492
1493     CURVNET_RESTORE();
1494 }
1495
1496 /*
1497  * Packet forwarding routine once entry in the cache is made
1498  */
1499 static int
1500 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1501 {
1502     struct ip  *ip = mtod(m, struct ip *);
1503     vifi_t vifi;
1504     int plen = ntohs(ip->ip_len);
1505
1506     VIF_LOCK_ASSERT();
1507
1508     /*
1509      * If xmt_vif is not -1, send on only the requested vif.
1510      *
1511      * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1512      */
1513     if (xmt_vif < V_numvifs) {
1514         if (V_viftable[xmt_vif].v_flags & VIFF_REGISTER)
1515                 pim_register_send(ip, V_viftable + xmt_vif, m, rt);
1516         else
1517                 phyint_send(ip, V_viftable + xmt_vif, m);
1518         return 1;
1519     }
1520
1521     /*
1522      * Don't forward if it didn't arrive from the parent vif for its origin.
1523      */
1524     vifi = rt->mfc_parent;
1525     if ((vifi >= V_numvifs) || (V_viftable[vifi].v_ifp != ifp)) {
1526         CTR4(KTR_IPMF, "%s: rx on wrong ifp %p (vifi %d, v_ifp %p)",
1527             __func__, ifp, (int)vifi, V_viftable[vifi].v_ifp);
1528         MRTSTAT_INC(mrts_wrong_if);
1529         ++rt->mfc_wrong_if;
1530         /*
1531          * If we are doing PIM assert processing, send a message
1532          * to the routing daemon.
1533          *
1534          * XXX: A PIM-SM router needs the WRONGVIF detection so it
1535          * can complete the SPT switch, regardless of the type
1536          * of the iif (broadcast media, GRE tunnel, etc).
1537          */
1538         if (V_pim_assert_enabled && (vifi < V_numvifs) &&
1539             V_viftable[vifi].v_ifp) {
1540
1541             if (ifp == &V_multicast_register_if)
1542                 PIMSTAT_INC(pims_rcv_registers_wrongiif);
1543
1544             /* Get vifi for the incoming packet */
1545             for (vifi = 0; vifi < V_numvifs && V_viftable[vifi].v_ifp != ifp;
1546                 vifi++)
1547                 ;
1548             if (vifi >= V_numvifs)
1549                 return 0;       /* The iif is not found: ignore the packet. */
1550
1551             if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1552                 return 0;       /* WRONGVIF disabled: ignore the packet */
1553
1554             if (ratecheck(&rt->mfc_last_assert, &pim_assert_interval)) {
1555                 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1556                 struct igmpmsg *im;
1557                 int hlen = ip->ip_hl << 2;
1558                 struct mbuf *mm = m_copym(m, 0, hlen, M_NOWAIT);
1559
1560                 if (mm && (!M_WRITABLE(mm) || mm->m_len < hlen))
1561                     mm = m_pullup(mm, hlen);
1562                 if (mm == NULL)
1563                     return ENOBUFS;
1564
1565                 im = mtod(mm, struct igmpmsg *);
1566                 im->im_msgtype  = IGMPMSG_WRONGVIF;
1567                 im->im_mbz              = 0;
1568                 im->im_vif              = vifi;
1569
1570                 MRTSTAT_INC(mrts_upcalls);
1571
1572                 k_igmpsrc.sin_addr = im->im_src;
1573                 if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1574                     CTR1(KTR_IPMF, "%s: socket queue full", __func__);
1575                     MRTSTAT_INC(mrts_upq_sockfull);
1576                     return ENOBUFS;
1577                 }
1578             }
1579         }
1580         return 0;
1581     }
1582
1583
1584     /* If I sourced this packet, it counts as output, else it was input. */
1585     if (in_hosteq(ip->ip_src, V_viftable[vifi].v_lcl_addr)) {
1586         V_viftable[vifi].v_pkt_out++;
1587         V_viftable[vifi].v_bytes_out += plen;
1588     } else {
1589         V_viftable[vifi].v_pkt_in++;
1590         V_viftable[vifi].v_bytes_in += plen;
1591     }
1592     rt->mfc_pkt_cnt++;
1593     rt->mfc_byte_cnt += plen;
1594
1595     /*
1596      * For each vif, decide if a copy of the packet should be forwarded.
1597      * Forward if:
1598      *          - the ttl exceeds the vif's threshold
1599      *          - there are group members downstream on interface
1600      */
1601     for (vifi = 0; vifi < V_numvifs; vifi++)
1602         if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1603             V_viftable[vifi].v_pkt_out++;
1604             V_viftable[vifi].v_bytes_out += plen;
1605             if (V_viftable[vifi].v_flags & VIFF_REGISTER)
1606                 pim_register_send(ip, V_viftable + vifi, m, rt);
1607             else
1608                 phyint_send(ip, V_viftable + vifi, m);
1609         }
1610
1611     /*
1612      * Perform upcall-related bw measuring.
1613      */
1614     if (rt->mfc_bw_meter != NULL) {
1615         struct bw_meter *x;
1616         struct timeval now;
1617
1618         microtime(&now);
1619         MFC_LOCK_ASSERT();
1620         for (x = rt->mfc_bw_meter; x != NULL; x = x->bm_mfc_next)
1621             bw_meter_receive_packet(x, plen, &now);
1622     }
1623
1624     return 0;
1625 }
1626
1627 /*
1628  * Check if a vif number is legal/ok. This is used by in_mcast.c.
1629  */
1630 static int
1631 X_legal_vif_num(int vif)
1632 {
1633         int ret;
1634
1635         ret = 0;
1636         if (vif < 0)
1637                 return (ret);
1638
1639         VIF_LOCK();
1640         if (vif < V_numvifs)
1641                 ret = 1;
1642         VIF_UNLOCK();
1643
1644         return (ret);
1645 }
1646
1647 /*
1648  * Return the local address used by this vif
1649  */
1650 static u_long
1651 X_ip_mcast_src(int vifi)
1652 {
1653         in_addr_t addr;
1654
1655         addr = INADDR_ANY;
1656         if (vifi < 0)
1657                 return (addr);
1658
1659         VIF_LOCK();
1660         if (vifi < V_numvifs)
1661                 addr = V_viftable[vifi].v_lcl_addr.s_addr;
1662         VIF_UNLOCK();
1663
1664         return (addr);
1665 }
1666
1667 static void
1668 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1669 {
1670     struct mbuf *mb_copy;
1671     int hlen = ip->ip_hl << 2;
1672
1673     VIF_LOCK_ASSERT();
1674
1675     /*
1676      * Make a new reference to the packet; make sure that
1677      * the IP header is actually copied, not just referenced,
1678      * so that ip_output() only scribbles on the copy.
1679      */
1680     mb_copy = m_copypacket(m, M_NOWAIT);
1681     if (mb_copy && (!M_WRITABLE(mb_copy) || mb_copy->m_len < hlen))
1682         mb_copy = m_pullup(mb_copy, hlen);
1683     if (mb_copy == NULL)
1684         return;
1685
1686     send_packet(vifp, mb_copy);
1687 }
1688
1689 static void
1690 send_packet(struct vif *vifp, struct mbuf *m)
1691 {
1692         struct ip_moptions imo;
1693         struct in_multi *imm[2];
1694         int error;
1695
1696         VIF_LOCK_ASSERT();
1697
1698         imo.imo_multicast_ifp  = vifp->v_ifp;
1699         imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1700         imo.imo_multicast_loop = 1;
1701         imo.imo_multicast_vif  = -1;
1702         imo.imo_num_memberships = 0;
1703         imo.imo_max_memberships = 2;
1704         imo.imo_membership  = &imm[0];
1705
1706         /*
1707          * Re-entrancy should not be a problem here, because
1708          * the packets that we send out and are looped back at us
1709          * should get rejected because they appear to come from
1710          * the loopback interface, thus preventing looping.
1711          */
1712         error = ip_output(m, NULL, NULL, IP_FORWARDING, &imo, NULL);
1713         CTR3(KTR_IPMF, "%s: vif %td err %d", __func__,
1714             (ptrdiff_t)(vifp - V_viftable), error);
1715 }
1716
1717 /*
1718  * Stubs for old RSVP socket shim implementation.
1719  */
1720
1721 static int
1722 X_ip_rsvp_vif(struct socket *so __unused, struct sockopt *sopt __unused)
1723 {
1724
1725         return (EOPNOTSUPP);
1726 }
1727
1728 static void
1729 X_ip_rsvp_force_done(struct socket *so __unused)
1730 {
1731
1732 }
1733
1734 static int
1735 X_rsvp_input(struct mbuf **mp, int *offp, int proto)
1736 {
1737         struct mbuf *m;
1738
1739         m = *mp;
1740         *mp = NULL;
1741         if (!V_rsvp_on)
1742                 m_freem(m);
1743         return (IPPROTO_DONE);
1744 }
1745
1746 /*
1747  * Code for bandwidth monitors
1748  */
1749
1750 /*
1751  * Define common interface for timeval-related methods
1752  */
1753 #define BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
1754 #define BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
1755 #define BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
1756
1757 static uint32_t
1758 compute_bw_meter_flags(struct bw_upcall *req)
1759 {
1760     uint32_t flags = 0;
1761
1762     if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
1763         flags |= BW_METER_UNIT_PACKETS;
1764     if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
1765         flags |= BW_METER_UNIT_BYTES;
1766     if (req->bu_flags & BW_UPCALL_GEQ)
1767         flags |= BW_METER_GEQ;
1768     if (req->bu_flags & BW_UPCALL_LEQ)
1769         flags |= BW_METER_LEQ;
1770
1771     return flags;
1772 }
1773
1774 /*
1775  * Add a bw_meter entry
1776  */
1777 static int
1778 add_bw_upcall(struct bw_upcall *req)
1779 {
1780     struct mfc *mfc;
1781     struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
1782                 BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
1783     struct timeval now;
1784     struct bw_meter *x;
1785     uint32_t flags;
1786
1787     if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
1788         return EOPNOTSUPP;
1789
1790     /* Test if the flags are valid */
1791     if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
1792         return EINVAL;
1793     if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
1794         return EINVAL;
1795     if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
1796             == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
1797         return EINVAL;
1798
1799     /* Test if the threshold time interval is valid */
1800     if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
1801         return EINVAL;
1802
1803     flags = compute_bw_meter_flags(req);
1804
1805     /*
1806      * Find if we have already same bw_meter entry
1807      */
1808     MFC_LOCK();
1809     mfc = mfc_find(&req->bu_src, &req->bu_dst);
1810     if (mfc == NULL) {
1811         MFC_UNLOCK();
1812         return EADDRNOTAVAIL;
1813     }
1814     for (x = mfc->mfc_bw_meter; x != NULL; x = x->bm_mfc_next) {
1815         if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
1816                            &req->bu_threshold.b_time, ==)) &&
1817             (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
1818             (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
1819             (x->bm_flags & BW_METER_USER_FLAGS) == flags)  {
1820             MFC_UNLOCK();
1821             return 0;           /* XXX Already installed */
1822         }
1823     }
1824
1825     /* Allocate the new bw_meter entry */
1826     x = (struct bw_meter *)malloc(sizeof(*x), M_BWMETER, M_NOWAIT);
1827     if (x == NULL) {
1828         MFC_UNLOCK();
1829         return ENOBUFS;
1830     }
1831
1832     /* Set the new bw_meter entry */
1833     x->bm_threshold.b_time = req->bu_threshold.b_time;
1834     microtime(&now);
1835     x->bm_start_time = now;
1836     x->bm_threshold.b_packets = req->bu_threshold.b_packets;
1837     x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
1838     x->bm_measured.b_packets = 0;
1839     x->bm_measured.b_bytes = 0;
1840     x->bm_flags = flags;
1841     x->bm_time_next = NULL;
1842     x->bm_time_hash = BW_METER_BUCKETS;
1843
1844     /* Add the new bw_meter entry to the front of entries for this MFC */
1845     x->bm_mfc = mfc;
1846     x->bm_mfc_next = mfc->mfc_bw_meter;
1847     mfc->mfc_bw_meter = x;
1848     schedule_bw_meter(x, &now);
1849     MFC_UNLOCK();
1850
1851     return 0;
1852 }
1853
1854 static void
1855 free_bw_list(struct bw_meter *list)
1856 {
1857     while (list != NULL) {
1858         struct bw_meter *x = list;
1859
1860         list = list->bm_mfc_next;
1861         unschedule_bw_meter(x);
1862         free(x, M_BWMETER);
1863     }
1864 }
1865
1866 /*
1867  * Delete one or multiple bw_meter entries
1868  */
1869 static int
1870 del_bw_upcall(struct bw_upcall *req)
1871 {
1872     struct mfc *mfc;
1873     struct bw_meter *x;
1874
1875     if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
1876         return EOPNOTSUPP;
1877
1878     MFC_LOCK();
1879
1880     /* Find the corresponding MFC entry */
1881     mfc = mfc_find(&req->bu_src, &req->bu_dst);
1882     if (mfc == NULL) {
1883         MFC_UNLOCK();
1884         return EADDRNOTAVAIL;
1885     } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
1886         /*
1887          * Delete all bw_meter entries for this mfc
1888          */
1889         struct bw_meter *list;
1890
1891         list = mfc->mfc_bw_meter;
1892         mfc->mfc_bw_meter = NULL;
1893         free_bw_list(list);
1894         MFC_UNLOCK();
1895         return 0;
1896     } else {                    /* Delete a single bw_meter entry */
1897         struct bw_meter *prev;
1898         uint32_t flags = 0;
1899
1900         flags = compute_bw_meter_flags(req);
1901
1902         /* Find the bw_meter entry to delete */
1903         for (prev = NULL, x = mfc->mfc_bw_meter; x != NULL;
1904              prev = x, x = x->bm_mfc_next) {
1905             if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
1906                                &req->bu_threshold.b_time, ==)) &&
1907                 (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
1908                 (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
1909                 (x->bm_flags & BW_METER_USER_FLAGS) == flags)
1910                 break;
1911         }
1912         if (x != NULL) { /* Delete entry from the list for this MFC */
1913             if (prev != NULL)
1914                 prev->bm_mfc_next = x->bm_mfc_next;     /* remove from middle*/
1915             else
1916                 x->bm_mfc->mfc_bw_meter = x->bm_mfc_next;/* new head of list */
1917
1918             unschedule_bw_meter(x);
1919             MFC_UNLOCK();
1920             /* Free the bw_meter entry */
1921             free(x, M_BWMETER);
1922             return 0;
1923         } else {
1924             MFC_UNLOCK();
1925             return EINVAL;
1926         }
1927     }
1928     /* NOTREACHED */
1929 }
1930
1931 /*
1932  * Perform bandwidth measurement processing that may result in an upcall
1933  */
1934 static void
1935 bw_meter_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
1936 {
1937     struct timeval delta;
1938
1939     MFC_LOCK_ASSERT();
1940
1941     delta = *nowp;
1942     BW_TIMEVALDECR(&delta, &x->bm_start_time);
1943
1944     if (x->bm_flags & BW_METER_GEQ) {
1945         /*
1946          * Processing for ">=" type of bw_meter entry
1947          */
1948         if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
1949             /* Reset the bw_meter entry */
1950             x->bm_start_time = *nowp;
1951             x->bm_measured.b_packets = 0;
1952             x->bm_measured.b_bytes = 0;
1953             x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
1954         }
1955
1956         /* Record that a packet is received */
1957         x->bm_measured.b_packets++;
1958         x->bm_measured.b_bytes += plen;
1959
1960         /*
1961          * Test if we should deliver an upcall
1962          */
1963         if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
1964             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
1965                  (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
1966                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
1967                  (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
1968                 /* Prepare an upcall for delivery */
1969                 bw_meter_prepare_upcall(x, nowp);
1970                 x->bm_flags |= BW_METER_UPCALL_DELIVERED;
1971             }
1972         }
1973     } else if (x->bm_flags & BW_METER_LEQ) {
1974         /*
1975          * Processing for "<=" type of bw_meter entry
1976          */
1977         if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
1978             /*
1979              * We are behind time with the multicast forwarding table
1980              * scanning for "<=" type of bw_meter entries, so test now
1981              * if we should deliver an upcall.
1982              */
1983             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
1984                  (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
1985                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
1986                  (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
1987                 /* Prepare an upcall for delivery */
1988                 bw_meter_prepare_upcall(x, nowp);
1989             }
1990             /* Reschedule the bw_meter entry */
1991             unschedule_bw_meter(x);
1992             schedule_bw_meter(x, nowp);
1993         }
1994
1995         /* Record that a packet is received */
1996         x->bm_measured.b_packets++;
1997         x->bm_measured.b_bytes += plen;
1998
1999         /*
2000          * Test if we should restart the measuring interval
2001          */
2002         if ((x->bm_flags & BW_METER_UNIT_PACKETS &&
2003              x->bm_measured.b_packets <= x->bm_threshold.b_packets) ||
2004             (x->bm_flags & BW_METER_UNIT_BYTES &&
2005              x->bm_measured.b_bytes <= x->bm_threshold.b_bytes)) {
2006             /* Don't restart the measuring interval */
2007         } else {
2008             /* Do restart the measuring interval */
2009             /*
2010              * XXX: note that we don't unschedule and schedule, because this
2011              * might be too much overhead per packet. Instead, when we process
2012              * all entries for a given timer hash bin, we check whether it is
2013              * really a timeout. If not, we reschedule at that time.
2014              */
2015             x->bm_start_time = *nowp;
2016             x->bm_measured.b_packets = 0;
2017             x->bm_measured.b_bytes = 0;
2018             x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2019         }
2020     }
2021 }
2022
2023 /*
2024  * Prepare a bandwidth-related upcall
2025  */
2026 static void
2027 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2028 {
2029     struct timeval delta;
2030     struct bw_upcall *u;
2031
2032     MFC_LOCK_ASSERT();
2033
2034     /*
2035      * Compute the measured time interval
2036      */
2037     delta = *nowp;
2038     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2039
2040     /*
2041      * If there are too many pending upcalls, deliver them now
2042      */
2043     if (V_bw_upcalls_n >= BW_UPCALLS_MAX)
2044         bw_upcalls_send();
2045
2046     /*
2047      * Set the bw_upcall entry
2048      */
2049     u = &V_bw_upcalls[V_bw_upcalls_n++];
2050     u->bu_src = x->bm_mfc->mfc_origin;
2051     u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2052     u->bu_threshold.b_time = x->bm_threshold.b_time;
2053     u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2054     u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2055     u->bu_measured.b_time = delta;
2056     u->bu_measured.b_packets = x->bm_measured.b_packets;
2057     u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2058     u->bu_flags = 0;
2059     if (x->bm_flags & BW_METER_UNIT_PACKETS)
2060         u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2061     if (x->bm_flags & BW_METER_UNIT_BYTES)
2062         u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2063     if (x->bm_flags & BW_METER_GEQ)
2064         u->bu_flags |= BW_UPCALL_GEQ;
2065     if (x->bm_flags & BW_METER_LEQ)
2066         u->bu_flags |= BW_UPCALL_LEQ;
2067 }
2068
2069 /*
2070  * Send the pending bandwidth-related upcalls
2071  */
2072 static void
2073 bw_upcalls_send(void)
2074 {
2075     struct mbuf *m;
2076     int len = V_bw_upcalls_n * sizeof(V_bw_upcalls[0]);
2077     struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2078     static struct igmpmsg igmpmsg = { 0,                /* unused1 */
2079                                       0,                /* unused2 */
2080                                       IGMPMSG_BW_UPCALL,/* im_msgtype */
2081                                       0,                /* im_mbz  */
2082                                       0,                /* im_vif  */
2083                                       0,                /* unused3 */
2084                                       { 0 },            /* im_src  */
2085                                       { 0 } };          /* im_dst  */
2086
2087     MFC_LOCK_ASSERT();
2088
2089     if (V_bw_upcalls_n == 0)
2090         return;                 /* No pending upcalls */
2091
2092     V_bw_upcalls_n = 0;
2093
2094     /*
2095      * Allocate a new mbuf, initialize it with the header and
2096      * the payload for the pending calls.
2097      */
2098     m = m_gethdr(M_NOWAIT, MT_DATA);
2099     if (m == NULL) {
2100         log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2101         return;
2102     }
2103
2104     m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2105     m_copyback(m, sizeof(struct igmpmsg), len, (caddr_t)&V_bw_upcalls[0]);
2106
2107     /*
2108      * Send the upcalls
2109      * XXX do we need to set the address in k_igmpsrc ?
2110      */
2111     MRTSTAT_INC(mrts_upcalls);
2112     if (socket_send(V_ip_mrouter, m, &k_igmpsrc) < 0) {
2113         log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2114         MRTSTAT_INC(mrts_upq_sockfull);
2115     }
2116 }
2117
2118 /*
2119  * Compute the timeout hash value for the bw_meter entries
2120  */
2121 #define BW_METER_TIMEHASH(bw_meter, hash)                               \
2122     do {                                                                \
2123         struct timeval next_timeval = (bw_meter)->bm_start_time;        \
2124                                                                         \
2125         BW_TIMEVALADD(&next_timeval, &(bw_meter)->bm_threshold.b_time); \
2126         (hash) = next_timeval.tv_sec;                                   \
2127         if (next_timeval.tv_usec)                                       \
2128             (hash)++; /* XXX: make sure we don't timeout early */       \
2129         (hash) %= BW_METER_BUCKETS;                                     \
2130     } while (0)
2131
2132 /*
2133  * Schedule a timer to process periodically bw_meter entry of type "<="
2134  * by linking the entry in the proper hash bucket.
2135  */
2136 static void
2137 schedule_bw_meter(struct bw_meter *x, struct timeval *nowp)
2138 {
2139     int time_hash;
2140
2141     MFC_LOCK_ASSERT();
2142
2143     if (!(x->bm_flags & BW_METER_LEQ))
2144         return;         /* XXX: we schedule timers only for "<=" entries */
2145
2146     /*
2147      * Reset the bw_meter entry
2148      */
2149     x->bm_start_time = *nowp;
2150     x->bm_measured.b_packets = 0;
2151     x->bm_measured.b_bytes = 0;
2152     x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2153
2154     /*
2155      * Compute the timeout hash value and insert the entry
2156      */
2157     BW_METER_TIMEHASH(x, time_hash);
2158     x->bm_time_next = V_bw_meter_timers[time_hash];
2159     V_bw_meter_timers[time_hash] = x;
2160     x->bm_time_hash = time_hash;
2161 }
2162
2163 /*
2164  * Unschedule the periodic timer that processes bw_meter entry of type "<="
2165  * by removing the entry from the proper hash bucket.
2166  */
2167 static void
2168 unschedule_bw_meter(struct bw_meter *x)
2169 {
2170     int time_hash;
2171     struct bw_meter *prev, *tmp;
2172
2173     MFC_LOCK_ASSERT();
2174
2175     if (!(x->bm_flags & BW_METER_LEQ))
2176         return;         /* XXX: we schedule timers only for "<=" entries */
2177
2178     /*
2179      * Compute the timeout hash value and delete the entry
2180      */
2181     time_hash = x->bm_time_hash;
2182     if (time_hash >= BW_METER_BUCKETS)
2183         return;         /* Entry was not scheduled */
2184
2185     for (prev = NULL, tmp = V_bw_meter_timers[time_hash];
2186              tmp != NULL; prev = tmp, tmp = tmp->bm_time_next)
2187         if (tmp == x)
2188             break;
2189
2190     if (tmp == NULL)
2191         panic("unschedule_bw_meter: bw_meter entry not found");
2192
2193     if (prev != NULL)
2194         prev->bm_time_next = x->bm_time_next;
2195     else
2196         V_bw_meter_timers[time_hash] = x->bm_time_next;
2197
2198     x->bm_time_next = NULL;
2199     x->bm_time_hash = BW_METER_BUCKETS;
2200 }
2201
2202
2203 /*
2204  * Process all "<=" type of bw_meter that should be processed now,
2205  * and for each entry prepare an upcall if necessary. Each processed
2206  * entry is rescheduled again for the (periodic) processing.
2207  *
2208  * This is run periodically (once per second normally). On each round,
2209  * all the potentially matching entries are in the hash slot that we are
2210  * looking at.
2211  */
2212 static void
2213 bw_meter_process()
2214 {
2215     uint32_t loops;
2216     int i;
2217     struct timeval now, process_endtime;
2218
2219     microtime(&now);
2220     if (V_last_tv_sec == now.tv_sec)
2221         return;         /* nothing to do */
2222
2223     loops = now.tv_sec - V_last_tv_sec;
2224     V_last_tv_sec = now.tv_sec;
2225     if (loops > BW_METER_BUCKETS)
2226         loops = BW_METER_BUCKETS;
2227
2228     MFC_LOCK();
2229     /*
2230      * Process all bins of bw_meter entries from the one after the last
2231      * processed to the current one. On entry, i points to the last bucket
2232      * visited, so we need to increment i at the beginning of the loop.
2233      */
2234     for (i = (now.tv_sec - loops) % BW_METER_BUCKETS; loops > 0; loops--) {
2235         struct bw_meter *x, *tmp_list;
2236
2237         if (++i >= BW_METER_BUCKETS)
2238             i = 0;
2239
2240         /* Disconnect the list of bw_meter entries from the bin */
2241         tmp_list = V_bw_meter_timers[i];
2242         V_bw_meter_timers[i] = NULL;
2243
2244         /* Process the list of bw_meter entries */
2245         while (tmp_list != NULL) {
2246             x = tmp_list;
2247             tmp_list = tmp_list->bm_time_next;
2248
2249             /* Test if the time interval is over */
2250             process_endtime = x->bm_start_time;
2251             BW_TIMEVALADD(&process_endtime, &x->bm_threshold.b_time);
2252             if (BW_TIMEVALCMP(&process_endtime, &now, >)) {
2253                 /* Not yet: reschedule, but don't reset */
2254                 int time_hash;
2255
2256                 BW_METER_TIMEHASH(x, time_hash);
2257                 if (time_hash == i && process_endtime.tv_sec == now.tv_sec) {
2258                     /*
2259                      * XXX: somehow the bin processing is a bit ahead of time.
2260                      * Put the entry in the next bin.
2261                      */
2262                     if (++time_hash >= BW_METER_BUCKETS)
2263                         time_hash = 0;
2264                 }
2265                 x->bm_time_next = V_bw_meter_timers[time_hash];
2266                 V_bw_meter_timers[time_hash] = x;
2267                 x->bm_time_hash = time_hash;
2268
2269                 continue;
2270             }
2271
2272             /*
2273              * Test if we should deliver an upcall
2274              */
2275             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2276                  (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2277                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2278                  (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2279                 /* Prepare an upcall for delivery */
2280                 bw_meter_prepare_upcall(x, &now);
2281             }
2282
2283             /*
2284              * Reschedule for next processing
2285              */
2286             schedule_bw_meter(x, &now);
2287         }
2288     }
2289
2290     /* Send all upcalls that are pending delivery */
2291     bw_upcalls_send();
2292
2293     MFC_UNLOCK();
2294 }
2295
2296 /*
2297  * A periodic function for sending all upcalls that are pending delivery
2298  */
2299 static void
2300 expire_bw_upcalls_send(void *arg)
2301 {
2302     CURVNET_SET((struct vnet *) arg);
2303
2304     MFC_LOCK();
2305     bw_upcalls_send();
2306     MFC_UNLOCK();
2307
2308     callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
2309         curvnet);
2310     CURVNET_RESTORE();
2311 }
2312
2313 /*
2314  * A periodic function for periodic scanning of the multicast forwarding
2315  * table for processing all "<=" bw_meter entries.
2316  */
2317 static void
2318 expire_bw_meter_process(void *arg)
2319 {
2320     CURVNET_SET((struct vnet *) arg);
2321
2322     if (V_mrt_api_config & MRT_MFC_BW_UPCALL)
2323         bw_meter_process();
2324
2325     callout_reset(&V_bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process,
2326         curvnet);
2327     CURVNET_RESTORE();
2328 }
2329
2330 /*
2331  * End of bandwidth monitoring code
2332  */
2333
2334 /*
2335  * Send the packet up to the user daemon, or eventually do kernel encapsulation
2336  *
2337  */
2338 static int
2339 pim_register_send(struct ip *ip, struct vif *vifp, struct mbuf *m,
2340     struct mfc *rt)
2341 {
2342     struct mbuf *mb_copy, *mm;
2343
2344     /*
2345      * Do not send IGMP_WHOLEPKT notifications to userland, if the
2346      * rendezvous point was unspecified, and we were told not to.
2347      */
2348     if (pim_squelch_wholepkt != 0 && (V_mrt_api_config & MRT_MFC_RP) &&
2349         in_nullhost(rt->mfc_rp))
2350         return 0;
2351
2352     mb_copy = pim_register_prepare(ip, m);
2353     if (mb_copy == NULL)
2354         return ENOBUFS;
2355
2356     /*
2357      * Send all the fragments. Note that the mbuf for each fragment
2358      * is freed by the sending machinery.
2359      */
2360     for (mm = mb_copy; mm; mm = mb_copy) {
2361         mb_copy = mm->m_nextpkt;
2362         mm->m_nextpkt = 0;
2363         mm = m_pullup(mm, sizeof(struct ip));
2364         if (mm != NULL) {
2365             ip = mtod(mm, struct ip *);
2366             if ((V_mrt_api_config & MRT_MFC_RP) && !in_nullhost(rt->mfc_rp)) {
2367                 pim_register_send_rp(ip, vifp, mm, rt);
2368             } else {
2369                 pim_register_send_upcall(ip, vifp, mm, rt);
2370             }
2371         }
2372     }
2373
2374     return 0;
2375 }
2376
2377 /*
2378  * Return a copy of the data packet that is ready for PIM Register
2379  * encapsulation.
2380  * XXX: Note that in the returned copy the IP header is a valid one.
2381  */
2382 static struct mbuf *
2383 pim_register_prepare(struct ip *ip, struct mbuf *m)
2384 {
2385     struct mbuf *mb_copy = NULL;
2386     int mtu;
2387
2388     /* Take care of delayed checksums */
2389     if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2390         in_delayed_cksum(m);
2391         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2392     }
2393
2394     /*
2395      * Copy the old packet & pullup its IP header into the
2396      * new mbuf so we can modify it.
2397      */
2398     mb_copy = m_copypacket(m, M_NOWAIT);
2399     if (mb_copy == NULL)
2400         return NULL;
2401     mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2402     if (mb_copy == NULL)
2403         return NULL;
2404
2405     /* take care of the TTL */
2406     ip = mtod(mb_copy, struct ip *);
2407     --ip->ip_ttl;
2408
2409     /* Compute the MTU after the PIM Register encapsulation */
2410     mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2411
2412     if (ntohs(ip->ip_len) <= mtu) {
2413         /* Turn the IP header into a valid one */
2414         ip->ip_sum = 0;
2415         ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2416     } else {
2417         /* Fragment the packet */
2418         mb_copy->m_pkthdr.csum_flags |= CSUM_IP;
2419         if (ip_fragment(ip, &mb_copy, mtu, 0) != 0) {
2420             m_freem(mb_copy);
2421             return NULL;
2422         }
2423     }
2424     return mb_copy;
2425 }
2426
2427 /*
2428  * Send an upcall with the data packet to the user-level process.
2429  */
2430 static int
2431 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2432     struct mbuf *mb_copy, struct mfc *rt)
2433 {
2434     struct mbuf *mb_first;
2435     int len = ntohs(ip->ip_len);
2436     struct igmpmsg *im;
2437     struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2438
2439     VIF_LOCK_ASSERT();
2440
2441     /*
2442      * Add a new mbuf with an upcall header
2443      */
2444     mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2445     if (mb_first == NULL) {
2446         m_freem(mb_copy);
2447         return ENOBUFS;
2448     }
2449     mb_first->m_data += max_linkhdr;
2450     mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2451     mb_first->m_len = sizeof(struct igmpmsg);
2452     mb_first->m_next = mb_copy;
2453
2454     /* Send message to routing daemon */
2455     im = mtod(mb_first, struct igmpmsg *);
2456     im->im_msgtype      = IGMPMSG_WHOLEPKT;
2457     im->im_mbz          = 0;
2458     im->im_vif          = vifp - V_viftable;
2459     im->im_src          = ip->ip_src;
2460     im->im_dst          = ip->ip_dst;
2461
2462     k_igmpsrc.sin_addr  = ip->ip_src;
2463
2464     MRTSTAT_INC(mrts_upcalls);
2465
2466     if (socket_send(V_ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2467         CTR1(KTR_IPMF, "%s: socket queue full", __func__);
2468         MRTSTAT_INC(mrts_upq_sockfull);
2469         return ENOBUFS;
2470     }
2471
2472     /* Keep statistics */
2473     PIMSTAT_INC(pims_snd_registers_msgs);
2474     PIMSTAT_ADD(pims_snd_registers_bytes, len);
2475
2476     return 0;
2477 }
2478
2479 /*
2480  * Encapsulate the data packet in PIM Register message and send it to the RP.
2481  */
2482 static int
2483 pim_register_send_rp(struct ip *ip, struct vif *vifp, struct mbuf *mb_copy,
2484     struct mfc *rt)
2485 {
2486     struct mbuf *mb_first;
2487     struct ip *ip_outer;
2488     struct pim_encap_pimhdr *pimhdr;
2489     int len = ntohs(ip->ip_len);
2490     vifi_t vifi = rt->mfc_parent;
2491
2492     VIF_LOCK_ASSERT();
2493
2494     if ((vifi >= V_numvifs) || in_nullhost(V_viftable[vifi].v_lcl_addr)) {
2495         m_freem(mb_copy);
2496         return EADDRNOTAVAIL;           /* The iif vif is invalid */
2497     }
2498
2499     /*
2500      * Add a new mbuf with the encapsulating header
2501      */
2502     mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2503     if (mb_first == NULL) {
2504         m_freem(mb_copy);
2505         return ENOBUFS;
2506     }
2507     mb_first->m_data += max_linkhdr;
2508     mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2509     mb_first->m_next = mb_copy;
2510
2511     mb_first->m_pkthdr.len = len + mb_first->m_len;
2512
2513     /*
2514      * Fill in the encapsulating IP and PIM header
2515      */
2516     ip_outer = mtod(mb_first, struct ip *);
2517     *ip_outer = pim_encap_iphdr;
2518     ip_outer->ip_len = htons(len + sizeof(pim_encap_iphdr) +
2519         sizeof(pim_encap_pimhdr));
2520     ip_outer->ip_src = V_viftable[vifi].v_lcl_addr;
2521     ip_outer->ip_dst = rt->mfc_rp;
2522     /*
2523      * Copy the inner header TOS to the outer header, and take care of the
2524      * IP_DF bit.
2525      */
2526     ip_outer->ip_tos = ip->ip_tos;
2527     if (ip->ip_off & htons(IP_DF))
2528         ip_outer->ip_off |= htons(IP_DF);
2529     ip_fillid(ip_outer);
2530     pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2531                                          + sizeof(pim_encap_iphdr));
2532     *pimhdr = pim_encap_pimhdr;
2533     /* If the iif crosses a border, set the Border-bit */
2534     if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & V_mrt_api_config)
2535         pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
2536
2537     mb_first->m_data += sizeof(pim_encap_iphdr);
2538     pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
2539     mb_first->m_data -= sizeof(pim_encap_iphdr);
2540
2541     send_packet(vifp, mb_first);
2542
2543     /* Keep statistics */
2544     PIMSTAT_INC(pims_snd_registers_msgs);
2545     PIMSTAT_ADD(pims_snd_registers_bytes, len);
2546
2547     return 0;
2548 }
2549
2550 /*
2551  * pim_encapcheck() is called by the encap4_input() path at runtime to
2552  * determine if a packet is for PIM; allowing PIM to be dynamically loaded
2553  * into the kernel.
2554  */
2555 static int
2556 pim_encapcheck(const struct mbuf *m, int off, int proto, void *arg)
2557 {
2558
2559 #ifdef DIAGNOSTIC
2560     KASSERT(proto == IPPROTO_PIM, ("not for IPPROTO_PIM"));
2561 #endif
2562     if (proto != IPPROTO_PIM)
2563         return 0;       /* not for us; reject the datagram. */
2564
2565     return 64;          /* claim the datagram. */
2566 }
2567
2568 /*
2569  * PIM-SMv2 and PIM-DM messages processing.
2570  * Receives and verifies the PIM control messages, and passes them
2571  * up to the listening socket, using rip_input().
2572  * The only message with special processing is the PIM_REGISTER message
2573  * (used by PIM-SM): the PIM header is stripped off, and the inner packet
2574  * is passed to if_simloop().
2575  */
2576 int
2577 pim_input(struct mbuf **mp, int *offp, int proto)
2578 {
2579     struct mbuf *m = *mp;
2580     struct ip *ip = mtod(m, struct ip *);
2581     struct pim *pim;
2582     int iphlen = *offp;
2583     int minlen;
2584     int datalen = ntohs(ip->ip_len) - iphlen;
2585     int ip_tos;
2586 #ifdef KTR
2587     char addrbuf[INET_ADDRSTRLEN];
2588 #endif
2589  
2590     *mp = NULL;
2591
2592     /* Keep statistics */
2593     PIMSTAT_INC(pims_rcv_total_msgs);
2594     PIMSTAT_ADD(pims_rcv_total_bytes, datalen);
2595
2596     /*
2597      * Validate lengths
2598      */
2599     if (datalen < PIM_MINLEN) {
2600         PIMSTAT_INC(pims_rcv_tooshort);
2601         CTR3(KTR_IPMF, "%s: short packet (%d) from %s",
2602             __func__, datalen, inet_ntoa_r(ip->ip_src, addrbuf));
2603         m_freem(m);
2604         return (IPPROTO_DONE);
2605     }
2606
2607     /*
2608      * If the packet is at least as big as a REGISTER, go agead
2609      * and grab the PIM REGISTER header size, to avoid another
2610      * possible m_pullup() later.
2611      *
2612      * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
2613      * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
2614      */
2615     minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
2616     /*
2617      * Get the IP and PIM headers in contiguous memory, and
2618      * possibly the PIM REGISTER header.
2619      */
2620     if (m->m_len < minlen && (m = m_pullup(m, minlen)) == NULL) {
2621         CTR1(KTR_IPMF, "%s: m_pullup() failed", __func__);
2622         return (IPPROTO_DONE);
2623     }
2624
2625     /* m_pullup() may have given us a new mbuf so reset ip. */
2626     ip = mtod(m, struct ip *);
2627     ip_tos = ip->ip_tos;
2628
2629     /* adjust mbuf to point to the PIM header */
2630     m->m_data += iphlen;
2631     m->m_len  -= iphlen;
2632     pim = mtod(m, struct pim *);
2633
2634     /*
2635      * Validate checksum. If PIM REGISTER, exclude the data packet.
2636      *
2637      * XXX: some older PIMv2 implementations don't make this distinction,
2638      * so for compatibility reason perform the checksum over part of the
2639      * message, and if error, then over the whole message.
2640      */
2641     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
2642         /* do nothing, checksum okay */
2643     } else if (in_cksum(m, datalen)) {
2644         PIMSTAT_INC(pims_rcv_badsum);
2645         CTR1(KTR_IPMF, "%s: invalid checksum", __func__);
2646         m_freem(m);
2647         return (IPPROTO_DONE);
2648     }
2649
2650     /* PIM version check */
2651     if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
2652         PIMSTAT_INC(pims_rcv_badversion);
2653         CTR3(KTR_IPMF, "%s: bad version %d expect %d", __func__,
2654             (int)PIM_VT_V(pim->pim_vt), PIM_VERSION);
2655         m_freem(m);
2656         return (IPPROTO_DONE);
2657     }
2658
2659     /* restore mbuf back to the outer IP */
2660     m->m_data -= iphlen;
2661     m->m_len  += iphlen;
2662
2663     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
2664         /*
2665          * Since this is a REGISTER, we'll make a copy of the register
2666          * headers ip + pim + u_int32 + encap_ip, to be passed up to the
2667          * routing daemon.
2668          */
2669         struct sockaddr_in dst = { sizeof(dst), AF_INET };
2670         struct mbuf *mcp;
2671         struct ip *encap_ip;
2672         u_int32_t *reghdr;
2673         struct ifnet *vifp;
2674
2675         VIF_LOCK();
2676         if ((V_reg_vif_num >= V_numvifs) || (V_reg_vif_num == VIFI_INVALID)) {
2677             VIF_UNLOCK();
2678             CTR2(KTR_IPMF, "%s: register vif not set: %d", __func__,
2679                 (int)V_reg_vif_num);
2680             m_freem(m);
2681             return (IPPROTO_DONE);
2682         }
2683         /* XXX need refcnt? */
2684         vifp = V_viftable[V_reg_vif_num].v_ifp;
2685         VIF_UNLOCK();
2686
2687         /*
2688          * Validate length
2689          */
2690         if (datalen < PIM_REG_MINLEN) {
2691             PIMSTAT_INC(pims_rcv_tooshort);
2692             PIMSTAT_INC(pims_rcv_badregisters);
2693             CTR1(KTR_IPMF, "%s: register packet size too small", __func__);
2694             m_freem(m);
2695             return (IPPROTO_DONE);
2696         }
2697
2698         reghdr = (u_int32_t *)(pim + 1);
2699         encap_ip = (struct ip *)(reghdr + 1);
2700
2701         CTR3(KTR_IPMF, "%s: register: encap ip src %s len %d",
2702             __func__, inet_ntoa_r(encap_ip->ip_src, addrbuf),
2703             ntohs(encap_ip->ip_len));
2704
2705         /* verify the version number of the inner packet */
2706         if (encap_ip->ip_v != IPVERSION) {
2707             PIMSTAT_INC(pims_rcv_badregisters);
2708             CTR1(KTR_IPMF, "%s: bad encap ip version", __func__);
2709             m_freem(m);
2710             return (IPPROTO_DONE);
2711         }
2712
2713         /* verify the inner packet is destined to a mcast group */
2714         if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
2715             PIMSTAT_INC(pims_rcv_badregisters);
2716             CTR2(KTR_IPMF, "%s: bad encap ip dest %s", __func__,
2717                 inet_ntoa_r(encap_ip->ip_dst, addrbuf));
2718             m_freem(m);
2719             return (IPPROTO_DONE);
2720         }
2721
2722         /* If a NULL_REGISTER, pass it to the daemon */
2723         if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
2724             goto pim_input_to_daemon;
2725
2726         /*
2727          * Copy the TOS from the outer IP header to the inner IP header.
2728          */
2729         if (encap_ip->ip_tos != ip_tos) {
2730             /* Outer TOS -> inner TOS */
2731             encap_ip->ip_tos = ip_tos;
2732             /* Recompute the inner header checksum. Sigh... */
2733
2734             /* adjust mbuf to point to the inner IP header */
2735             m->m_data += (iphlen + PIM_MINLEN);
2736             m->m_len  -= (iphlen + PIM_MINLEN);
2737
2738             encap_ip->ip_sum = 0;
2739             encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
2740
2741             /* restore mbuf to point back to the outer IP header */
2742             m->m_data -= (iphlen + PIM_MINLEN);
2743             m->m_len  += (iphlen + PIM_MINLEN);
2744         }
2745
2746         /*
2747          * Decapsulate the inner IP packet and loopback to forward it
2748          * as a normal multicast packet. Also, make a copy of the
2749          *     outer_iphdr + pimhdr + reghdr + encap_iphdr
2750          * to pass to the daemon later, so it can take the appropriate
2751          * actions (e.g., send back PIM_REGISTER_STOP).
2752          * XXX: here m->m_data points to the outer IP header.
2753          */
2754         mcp = m_copym(m, 0, iphlen + PIM_REG_MINLEN, M_NOWAIT);
2755         if (mcp == NULL) {
2756             CTR1(KTR_IPMF, "%s: m_copym() failed", __func__);
2757             m_freem(m);
2758             return (IPPROTO_DONE);
2759         }
2760
2761         /* Keep statistics */
2762         /* XXX: registers_bytes include only the encap. mcast pkt */
2763         PIMSTAT_INC(pims_rcv_registers_msgs);
2764         PIMSTAT_ADD(pims_rcv_registers_bytes, ntohs(encap_ip->ip_len));
2765
2766         /*
2767          * forward the inner ip packet; point m_data at the inner ip.
2768          */
2769         m_adj(m, iphlen + PIM_MINLEN);
2770
2771         CTR4(KTR_IPMF,
2772             "%s: forward decap'd REGISTER: src %lx dst %lx vif %d",
2773             __func__,
2774             (u_long)ntohl(encap_ip->ip_src.s_addr),
2775             (u_long)ntohl(encap_ip->ip_dst.s_addr),
2776             (int)V_reg_vif_num);
2777
2778         /* NB: vifp was collected above; can it change on us? */
2779         if_simloop(vifp, m, dst.sin_family, 0);
2780
2781         /* prepare the register head to send to the mrouting daemon */
2782         m = mcp;
2783     }
2784
2785 pim_input_to_daemon:
2786     /*
2787      * Pass the PIM message up to the daemon; if it is a Register message,
2788      * pass the 'head' only up to the daemon. This includes the
2789      * outer IP header, PIM header, PIM-Register header and the
2790      * inner IP header.
2791      * XXX: the outer IP header pkt size of a Register is not adjust to
2792      * reflect the fact that the inner multicast data is truncated.
2793      */
2794     *mp = m;
2795     rip_input(mp, offp, proto);
2796
2797     return (IPPROTO_DONE);
2798 }
2799
2800 static int
2801 sysctl_mfctable(SYSCTL_HANDLER_ARGS)
2802 {
2803         struct mfc      *rt;
2804         int              error, i;
2805
2806         if (req->newptr)
2807                 return (EPERM);
2808         if (V_mfchashtbl == NULL)       /* XXX unlocked */
2809                 return (0);
2810         error = sysctl_wire_old_buffer(req, 0);
2811         if (error)
2812                 return (error);
2813
2814         MFC_LOCK();
2815         for (i = 0; i < mfchashsize; i++) {
2816                 LIST_FOREACH(rt, &V_mfchashtbl[i], mfc_hash) {
2817                         error = SYSCTL_OUT(req, rt, sizeof(struct mfc));
2818                         if (error)
2819                                 goto out_locked;
2820                 }
2821         }
2822 out_locked:
2823         MFC_UNLOCK();
2824         return (error);
2825 }
2826
2827 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, mfctable, CTLFLAG_RD,
2828     sysctl_mfctable, "IPv4 Multicast Forwarding Table "
2829     "(struct *mfc[mfchashsize], netinet/ip_mroute.h)");
2830
2831 static void
2832 vnet_mroute_init(const void *unused __unused)
2833 {
2834
2835         MALLOC(V_nexpire, u_char *, mfchashsize, M_MRTABLE, M_WAITOK|M_ZERO);
2836         bzero(V_bw_meter_timers, sizeof(V_bw_meter_timers));
2837         callout_init(&V_expire_upcalls_ch, 1);
2838         callout_init(&V_bw_upcalls_ch, 1);
2839         callout_init(&V_bw_meter_ch, 1);
2840 }
2841
2842 VNET_SYSINIT(vnet_mroute_init, SI_SUB_PROTO_MC, SI_ORDER_ANY, vnet_mroute_init,
2843         NULL);
2844
2845 static void
2846 vnet_mroute_uninit(const void *unused __unused)
2847 {
2848
2849         FREE(V_nexpire, M_MRTABLE);
2850         V_nexpire = NULL;
2851 }
2852
2853 VNET_SYSUNINIT(vnet_mroute_uninit, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE, 
2854         vnet_mroute_uninit, NULL);
2855
2856 static int
2857 ip_mroute_modevent(module_t mod, int type, void *unused)
2858 {
2859
2860     switch (type) {
2861     case MOD_LOAD:
2862         MROUTER_LOCK_INIT();
2863
2864         if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event, 
2865             if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
2866         if (if_detach_event_tag == NULL) {
2867                 printf("ip_mroute: unable to register "
2868                     "ifnet_departure_event handler\n");
2869                 MROUTER_LOCK_DESTROY();
2870                 return (EINVAL);
2871         }
2872
2873         MFC_LOCK_INIT();
2874         VIF_LOCK_INIT();
2875
2876         mfchashsize = MFCHASHSIZE;
2877         if (TUNABLE_ULONG_FETCH("net.inet.ip.mfchashsize", &mfchashsize) &&
2878             !powerof2(mfchashsize)) {
2879                 printf("WARNING: %s not a power of 2; using default\n",
2880                     "net.inet.ip.mfchashsize");
2881                 mfchashsize = MFCHASHSIZE;
2882         }
2883
2884         pim_squelch_wholepkt = 0;
2885         TUNABLE_ULONG_FETCH("net.inet.pim.squelch_wholepkt",
2886             &pim_squelch_wholepkt);
2887
2888         pim_encap_cookie = encap_attach_func(AF_INET, IPPROTO_PIM,
2889             pim_encapcheck, &in_pim_protosw, NULL);
2890         if (pim_encap_cookie == NULL) {
2891                 printf("ip_mroute: unable to attach pim encap\n");
2892                 VIF_LOCK_DESTROY();
2893                 MFC_LOCK_DESTROY();
2894                 MROUTER_LOCK_DESTROY();
2895                 return (EINVAL);
2896         }
2897
2898         ip_mcast_src = X_ip_mcast_src;
2899         ip_mforward = X_ip_mforward;
2900         ip_mrouter_done = X_ip_mrouter_done;
2901         ip_mrouter_get = X_ip_mrouter_get;
2902         ip_mrouter_set = X_ip_mrouter_set;
2903
2904         ip_rsvp_force_done = X_ip_rsvp_force_done;
2905         ip_rsvp_vif = X_ip_rsvp_vif;
2906
2907         legal_vif_num = X_legal_vif_num;
2908         mrt_ioctl = X_mrt_ioctl;
2909         rsvp_input_p = X_rsvp_input;
2910         break;
2911
2912     case MOD_UNLOAD:
2913         /*
2914          * Typically module unload happens after the user-level
2915          * process has shutdown the kernel services (the check
2916          * below insures someone can't just yank the module out
2917          * from under a running process).  But if the module is
2918          * just loaded and then unloaded w/o starting up a user
2919          * process we still need to cleanup.
2920          */
2921         MROUTER_LOCK();
2922         if (ip_mrouter_cnt != 0) {
2923             MROUTER_UNLOCK();
2924             return (EINVAL);
2925         }
2926         ip_mrouter_unloading = 1;
2927         MROUTER_UNLOCK();
2928
2929         EVENTHANDLER_DEREGISTER(ifnet_departure_event, if_detach_event_tag);
2930
2931         if (pim_encap_cookie) {
2932             encap_detach(pim_encap_cookie);
2933             pim_encap_cookie = NULL;
2934         }
2935
2936         ip_mcast_src = NULL;
2937         ip_mforward = NULL;
2938         ip_mrouter_done = NULL;
2939         ip_mrouter_get = NULL;
2940         ip_mrouter_set = NULL;
2941
2942         ip_rsvp_force_done = NULL;
2943         ip_rsvp_vif = NULL;
2944
2945         legal_vif_num = NULL;
2946         mrt_ioctl = NULL;
2947         rsvp_input_p = NULL;
2948
2949         VIF_LOCK_DESTROY();
2950         MFC_LOCK_DESTROY();
2951         MROUTER_LOCK_DESTROY();
2952         break;
2953
2954     default:
2955         return EOPNOTSUPP;
2956     }
2957     return 0;
2958 }
2959
2960 static moduledata_t ip_mroutemod = {
2961     "ip_mroute",
2962     ip_mroute_modevent,
2963     0
2964 };
2965
2966 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);