Merge from vendor branch OPENPAM:
[dragonfly.git] / sys / net / ip_mroute / ip_mroute.c
1 /*
2  * IP multicast forwarding procedures
3  *
4  * Written by David Waitzman, BBN Labs, August 1988.
5  * Modified by Steve Deering, Stanford, February 1989.
6  * Modified by Mark J. Steiglitz, Stanford, May, 1991
7  * Modified by Van Jacobson, LBL, January 1993
8  * Modified by Ajit Thyagarajan, PARC, August 1993
9  * Modified by Bill Fenner, PARC, April 1995
10  * Modified by Ahmed Helmy, SGI, June 1996
11  * Modified by George Edmond Eddy (Rusty), ISI, February 1998
12  * Modified by Pavlin Radoslavov, USC/ISI, May 1998, August 1999, October 2000
13  * Modified by Hitoshi Asaeda, WIDE, August 2000
14  * Modified by Pavlin Radoslavov, ICSI, October 2002
15  *
16  * MROUTING Revision: 3.5
17  * and PIM-SMv2 and PIM-DM support, advanced API support,
18  * bandwidth metering and signaling
19  *
20  * $FreeBSD: src/sys/netinet/ip_mroute.c,v 1.56.2.10 2003/08/24 21:37:34 hsu Exp $
21  * $DragonFly: src/sys/net/ip_mroute/ip_mroute.c,v 1.17 2005/06/15 18:29:30 joerg Exp $
22  */
23
24 #include "opt_mrouting.h"
25 #include "opt_random_ip_id.h"
26
27 #ifdef PIM
28 #define _PIM_VT 1
29 #endif
30
31 #include <sys/param.h>
32 #include <sys/kernel.h>
33 #include <sys/malloc.h>
34 #include <sys/mbuf.h>
35 #include <sys/protosw.h>
36 #include <sys/socket.h>
37 #include <sys/socketvar.h>
38 #include <sys/sockio.h>
39 #include <sys/sysctl.h>
40 #include <sys/syslog.h>
41 #include <sys/systm.h>
42 #include <sys/thread2.h>
43 #include <sys/time.h>
44 #include <sys/in_cksum.h>
45
46 #include <machine/stdarg.h>
47
48 #include <net/if.h>
49 #include <net/netisr.h>
50 #include <net/route.h>
51 #include <netinet/in.h>
52 #include <netinet/igmp.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/in_var.h>
55 #include <netinet/ip.h>
56 #include "ip_mroute.h"
57 #include <netinet/ip_var.h>
58 #ifdef PIM
59 #include <netinet/pim.h>
60 #include <netinet/pim_var.h>
61 #endif
62 #ifdef ALTQ
63 #include <netinet/in_pcb.h>
64 #endif
65 #include <netinet/udp.h>
66
67 /*
68  * Control debugging code for rsvp and multicast routing code.
69  * Can only set them with the debugger.
70  */
71 static  u_int   rsvpdebug;              /* non-zero enables debugging   */
72
73 static  u_int   mrtdebug;               /* any set of the flags below   */
74  
75 #define         DEBUG_MFC       0x02
76 #define         DEBUG_FORWARD   0x04
77 #define         DEBUG_EXPIRE    0x08
78 #define         DEBUG_XMIT      0x10
79 #define         DEBUG_PIM       0x20
80
81 #define         VIFI_INVALID    ((vifi_t) -1)
82
83 #define M_HASCL(m)      ((m)->m_flags & M_EXT)
84
85 static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast routing tables");
86
87 static struct mrtstat   mrtstat;
88 SYSCTL_STRUCT(_net_inet_ip, OID_AUTO, mrtstat, CTLFLAG_RW,
89     &mrtstat, mrtstat,
90     "Multicast Routing Statistics (struct mrtstat, netinet/ip_mroute.h)");
91
92 static struct mfc       *mfctable[MFCTBLSIZ];
93 SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, mfctable, CTLFLAG_RD,
94     &mfctable, sizeof(mfctable), "S,*mfc[MFCTBLSIZ]",
95     "Multicast Forwarding Table (struct *mfc[MFCTBLSIZ], netinet/ip_mroute.h)");
96
97 static struct vif       viftable[MAXVIFS];
98 SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, viftable, CTLFLAG_RD,
99     &viftable, sizeof(viftable), "S,vif[MAXVIFS]",
100     "Multicast Virtual Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
101
102 static u_char           nexpire[MFCTBLSIZ];
103
104 static struct callout expire_upcalls_ch;
105 static struct callout tbf_reprocess_q_ch;
106 #define         EXPIRE_TIMEOUT  (hz / 4)        /* 4x / second          */
107 #define         UPCALL_EXPIRE   6               /* number of timeouts   */
108
109 /*
110  * Define the token bucket filter structures
111  * tbftable -> each vif has one of these for storing info
112  */
113
114 static struct tbf tbftable[MAXVIFS];
115 #define         TBF_REPROCESS   (hz / 100)      /* 100x / second */
116
117 /*
118  * 'Interfaces' associated with decapsulator (so we can tell
119  * packets that went through it from ones that get reflected
120  * by a broken gateway).  These interfaces are never linked into
121  * the system ifnet list & no routes point to them.  I.e., packets
122  * can't be sent this way.  They only exist as a placeholder for
123  * multicast source verification.
124  */
125 static struct ifnet multicast_decap_if[MAXVIFS];
126
127 #define ENCAP_TTL 64
128 #define ENCAP_PROTO IPPROTO_IPIP        /* 4 */
129
130 /* prototype IP hdr for encapsulated packets */
131 static struct ip multicast_encap_iphdr = {
132 #if BYTE_ORDER == LITTLE_ENDIAN
133         sizeof(struct ip) >> 2, IPVERSION,
134 #else
135         IPVERSION, sizeof(struct ip) >> 2,
136 #endif
137         0,                              /* tos */
138         sizeof(struct ip),              /* total length */
139         0,                              /* id */
140         0,                              /* frag offset */
141         ENCAP_TTL, ENCAP_PROTO,
142         0,                              /* checksum */
143 };
144
145 /*
146  * Bandwidth meter variables and constants
147  */
148 static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
149 /*
150  * Pending timeouts are stored in a hash table, the key being the
151  * expiration time. Periodically, the entries are analysed and processed.
152  */
153 #define BW_METER_BUCKETS        1024
154 static struct bw_meter *bw_meter_timers[BW_METER_BUCKETS];
155 static struct callout bw_meter_ch;
156 #define BW_METER_PERIOD (hz)            /* periodical handling of bw meters */
157
158 /*
159  * Pending upcalls are stored in a vector which is flushed when
160  * full, or periodically
161  */
162 static struct bw_upcall bw_upcalls[BW_UPCALLS_MAX];
163 static u_int    bw_upcalls_n; /* # of pending upcalls */
164 static struct callout bw_upcalls_ch;
165 #define BW_UPCALLS_PERIOD (hz)          /* periodical flush of bw upcalls */
166
167 #ifdef PIM
168 static struct pimstat pimstat;
169 SYSCTL_STRUCT(_net_inet_pim, PIMCTL_STATS, stats, CTLFLAG_RD,
170     &pimstat, pimstat,
171     "PIM Statistics (struct pimstat, netinet/pim_var.h)");
172
173 /*
174  * Note: the PIM Register encapsulation adds the following in front of a
175  * data packet:
176  *
177  * struct pim_encap_hdr {
178  *    struct ip ip;
179  *    struct pim_encap_pimhdr  pim;
180  * }
181  *
182  */
183
184 struct pim_encap_pimhdr {
185         struct pim pim;
186         uint32_t   flags;
187 };
188
189 static struct ip pim_encap_iphdr = {
190 #if BYTE_ORDER == LITTLE_ENDIAN
191         sizeof(struct ip) >> 2,
192         IPVERSION,
193 #else
194         IPVERSION,
195         sizeof(struct ip) >> 2,
196 #endif
197         0,                      /* tos */
198         sizeof(struct ip),      /* total length */
199         0,                      /* id */
200         0,                      /* frag offset */ 
201         ENCAP_TTL,
202         IPPROTO_PIM,
203         0,                      /* checksum */
204 };
205
206 static struct pim_encap_pimhdr pim_encap_pimhdr = {
207     {
208         PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
209         0,                      /* reserved */
210         0,                      /* checksum */
211     },
212     0                           /* flags */
213 };
214
215 static struct ifnet multicast_register_if;
216 static vifi_t reg_vif_num = VIFI_INVALID;
217 #endif /* PIM */
218
219 /*
220  * Private variables.
221  */
222 static vifi_t      numvifs;
223 static int have_encap_tunnel;
224
225 /*
226  * one-back cache used by ipip_input to locate a tunnel's vif
227  * given a datagram's src ip address.
228  */
229 static u_long last_encap_src;
230 static struct vif *last_encap_vif;
231
232 static u_long   X_ip_mcast_src(int vifi);
233 static int      X_ip_mforward(struct ip *ip, struct ifnet *ifp,
234                         struct mbuf *m, struct ip_moptions *imo);
235 static int      X_ip_mrouter_done(void);
236 static int      X_ip_mrouter_get(struct socket *so, struct sockopt *m);
237 static int      X_ip_mrouter_set(struct socket *so, struct sockopt *m);
238 static int      X_legal_vif_num(int vif);
239 static int      X_mrt_ioctl(int cmd, caddr_t data);
240
241 static int get_sg_cnt(struct sioc_sg_req *);
242 static int get_vif_cnt(struct sioc_vif_req *);
243 static int ip_mrouter_init(struct socket *, int);
244 static int add_vif(struct vifctl *);
245 static int del_vif(vifi_t);
246 static int add_mfc(struct mfcctl2 *);
247 static int del_mfc(struct mfcctl2 *);
248 static int set_api_config(uint32_t *); /* chose API capabilities */
249 static int socket_send(struct socket *, struct mbuf *, struct sockaddr_in *);
250 static int set_assert(int);
251 static void expire_upcalls(void *);
252 static int ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
253 static void phyint_send(struct ip *, struct vif *, struct mbuf *);
254 static void encap_send(struct ip *, struct vif *, struct mbuf *);
255 static void tbf_control(struct vif *, struct mbuf *, struct ip *, u_long);
256 static void tbf_queue(struct vif *, struct mbuf *);
257 static void tbf_process_q(struct vif *);
258 static void tbf_reprocess_q(void *);
259 static int tbf_dq_sel(struct vif *, struct ip *);
260 static void tbf_send_packet(struct vif *, struct mbuf *);
261 static void tbf_update_tokens(struct vif *);
262 static int priority(struct vif *, struct ip *);
263
264 /*
265  * Bandwidth monitoring
266  */
267 static void free_bw_list(struct bw_meter *list);
268 static int add_bw_upcall(struct bw_upcall *);
269 static int del_bw_upcall(struct bw_upcall *);
270 static void bw_meter_receive_packet(struct bw_meter *x, int plen,
271                 struct timeval *nowp);
272 static void bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp);
273 static void bw_upcalls_send(void);
274 static void schedule_bw_meter(struct bw_meter *x, struct timeval *nowp);
275 static void unschedule_bw_meter(struct bw_meter *x);
276 static void bw_meter_process(void);
277 static void expire_bw_upcalls_send(void *);
278 static void expire_bw_meter_process(void *);
279
280 #ifdef PIM
281 static int pim_register_send(struct ip *, struct vif *,
282                 struct mbuf *, struct mfc *);
283 static int pim_register_send_rp(struct ip *, struct vif *,
284                 struct mbuf *, struct mfc *);
285 static int pim_register_send_upcall(struct ip *, struct vif *,
286                 struct mbuf *, struct mfc *);
287 static struct mbuf *pim_register_prepare(struct ip *, struct mbuf *);
288 #endif
289
290 /*
291  * whether or not special PIM assert processing is enabled.
292  */
293 static int pim_assert;
294 /*
295  * Rate limit for assert notification messages, in usec
296  */
297 #define ASSERT_MSG_TIME         3000000
298
299 /*
300  * Kernel multicast routing API capabilities and setup.
301  * If more API capabilities are added to the kernel, they should be
302  * recorded in `mrt_api_support'.
303  */
304 static const uint32_t mrt_api_support = (MRT_MFC_FLAGS_DISABLE_WRONGVIF |
305                                          MRT_MFC_FLAGS_BORDER_VIF |
306                                          MRT_MFC_RP |
307                                          MRT_MFC_BW_UPCALL);
308 static uint32_t mrt_api_config = 0;
309
310 /*
311  * Hash function for a source, group entry
312  */
313 #define MFCHASH(a, g) MFCHASHMOD(((a) >> 20) ^ ((a) >> 10) ^ (a) ^ \
314                         ((g) >> 20) ^ ((g) >> 10) ^ (g))
315
316 /*
317  * Find a route for a given origin IP address and Multicast group address
318  * Type of service parameter to be added in the future!!!
319  * Statistics are updated by the caller if needed
320  * (mrtstat.mrts_mfc_lookups and mrtstat.mrts_mfc_misses)
321  */
322 static struct mfc *
323 mfc_find(in_addr_t o, in_addr_t g)
324 {
325     struct mfc *rt;
326
327     for (rt = mfctable[MFCHASH(o,g)]; rt; rt = rt->mfc_next)
328         if ((rt->mfc_origin.s_addr == o) &&
329                 (rt->mfc_mcastgrp.s_addr == g) && (rt->mfc_stall == NULL))
330             break;
331     return rt;
332 }
333
334 /*
335  * Macros to compute elapsed time efficiently
336  * Borrowed from Van Jacobson's scheduling code
337  */
338 #define TV_DELTA(a, b, delta) {                                 \
339         int xxs;                                                \
340         delta = (a).tv_usec - (b).tv_usec;                      \
341         if ((xxs = (a).tv_sec - (b).tv_sec)) {                  \
342                 switch (xxs) {                                  \
343                 case 2:                                         \
344                         delta += 1000000;                       \
345                         /* FALLTHROUGH */                       \
346                 case 1:                                         \
347                         delta += 1000000;                       \
348                         break;                                  \
349                 default:                                        \
350                         delta += (1000000 * xxs);               \
351                 }                                               \
352         }                                                       \
353 }
354
355 #define TV_LT(a, b) (((a).tv_usec < (b).tv_usec && \
356               (a).tv_sec <= (b).tv_sec) || (a).tv_sec < (b).tv_sec)
357
358 /*
359  * Handle MRT setsockopt commands to modify the multicast routing tables.
360  */
361 static int
362 X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
363 {
364     int error, optval;
365     vifi_t      vifi;
366     struct      vifctl vifc;
367     struct      mfcctl2 mfc;
368     struct      bw_upcall bw_upcall;
369     uint32_t    i;
370
371     if (so != ip_mrouter && sopt->sopt_name != MRT_INIT)
372         return EPERM;
373
374     error = 0;
375     switch (sopt->sopt_name) {
376     case MRT_INIT:
377         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
378         if (error)
379             break;
380         error = ip_mrouter_init(so, optval);
381         break;
382
383     case MRT_DONE:
384         error = ip_mrouter_done();
385         break;
386
387     case MRT_ADD_VIF:
388         error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
389         if (error)
390             break;
391         error = add_vif(&vifc);
392         break;
393
394     case MRT_DEL_VIF:
395         error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
396         if (error)
397             break;
398         error = del_vif(vifi);
399         break;
400
401     case MRT_ADD_MFC:
402     case MRT_DEL_MFC:
403         /*
404          * select data size depending on API version.
405          */
406         if (sopt->sopt_name == MRT_ADD_MFC &&
407                 mrt_api_config & MRT_API_FLAGS_ALL) {
408             error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl2),
409                                 sizeof(struct mfcctl2));
410         } else {
411             error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl),
412                                 sizeof(struct mfcctl));
413             bzero((caddr_t)&mfc + sizeof(struct mfcctl),
414                         sizeof(mfc) - sizeof(struct mfcctl));
415         }
416         if (error)
417             break;
418         if (sopt->sopt_name == MRT_ADD_MFC)
419             error = add_mfc(&mfc);
420         else
421             error = del_mfc(&mfc);
422         break;
423
424     case MRT_ASSERT:
425         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
426         if (error)
427             break;
428         set_assert(optval);
429         break;
430
431     case MRT_API_CONFIG:
432         error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
433         if (!error)
434             error = set_api_config(&i);
435         if (!error)
436             error = sooptcopyout(sopt, &i, sizeof i);
437         break;
438
439     case MRT_ADD_BW_UPCALL:
440     case MRT_DEL_BW_UPCALL:
441         error = sooptcopyin(sopt, &bw_upcall, sizeof bw_upcall,
442                                 sizeof bw_upcall);
443         if (error)
444             break;
445         if (sopt->sopt_name == MRT_ADD_BW_UPCALL)
446             error = add_bw_upcall(&bw_upcall);
447         else
448             error = del_bw_upcall(&bw_upcall);
449         break;
450
451     default:
452         error = EOPNOTSUPP;
453         break;
454     }
455     return error;
456 }
457
458 /*
459  * Handle MRT getsockopt commands
460  */
461 static int
462 X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
463 {
464     int error;
465     static int version = 0x0305; /* !!! why is this here? XXX */
466
467     switch (sopt->sopt_name) {
468     case MRT_VERSION:
469         error = sooptcopyout(sopt, &version, sizeof version);
470         break;
471
472     case MRT_ASSERT:
473         error = sooptcopyout(sopt, &pim_assert, sizeof pim_assert);
474         break;
475
476     case MRT_API_SUPPORT:
477         error = sooptcopyout(sopt, &mrt_api_support, sizeof mrt_api_support);
478         break;
479
480     case MRT_API_CONFIG:
481         error = sooptcopyout(sopt, &mrt_api_config, sizeof mrt_api_config);
482         break;
483
484     default:
485         error = EOPNOTSUPP;
486         break;
487     }
488     return error;
489 }
490
491 /*
492  * Handle ioctl commands to obtain information from the cache
493  */
494 static int
495 X_mrt_ioctl(int cmd, caddr_t data)
496 {
497     int error = 0;
498
499     switch (cmd) {
500     case SIOCGETVIFCNT:
501         error = get_vif_cnt((struct sioc_vif_req *)data);
502         break;
503
504     case SIOCGETSGCNT:
505         error = get_sg_cnt((struct sioc_sg_req *)data);
506         break;
507
508     default:
509         error = EINVAL;
510         break;
511     }
512     return error;
513 }
514
515 /*
516  * returns the packet, byte, rpf-failure count for the source group provided
517  */
518 static int
519 get_sg_cnt(struct sioc_sg_req *req)
520 {
521     struct mfc *rt;
522
523     crit_enter();
524     rt = mfc_find(req->src.s_addr, req->grp.s_addr);
525     crit_exit();
526     if (rt == NULL) {
527         req->pktcnt = req->bytecnt = req->wrong_if = 0xffffffff;
528         return EADDRNOTAVAIL;
529     }
530     req->pktcnt = rt->mfc_pkt_cnt;
531     req->bytecnt = rt->mfc_byte_cnt;
532     req->wrong_if = rt->mfc_wrong_if;
533     return 0;
534 }
535
536 /*
537  * returns the input and output packet and byte counts on the vif provided
538  */
539 static int
540 get_vif_cnt(struct sioc_vif_req *req)
541 {
542     vifi_t vifi = req->vifi;
543
544     if (vifi >= numvifs)
545         return EINVAL;
546
547     req->icount = viftable[vifi].v_pkt_in;
548     req->ocount = viftable[vifi].v_pkt_out;
549     req->ibytes = viftable[vifi].v_bytes_in;
550     req->obytes = viftable[vifi].v_bytes_out;
551
552     return 0;
553 }
554
555 /*
556  * Enable multicast routing
557  */
558 static int
559 ip_mrouter_init(struct socket *so, int version)
560 {
561     if (mrtdebug)
562         log(LOG_DEBUG, "ip_mrouter_init: so_type = %d, pr_protocol = %d\n",
563             so->so_type, so->so_proto->pr_protocol);
564
565     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_IGMP)
566         return EOPNOTSUPP;
567
568     if (version != 1)
569         return ENOPROTOOPT;
570
571     if (ip_mrouter != NULL)
572         return EADDRINUSE;
573
574     ip_mrouter = so;
575
576     bzero((caddr_t)mfctable, sizeof(mfctable));
577     bzero((caddr_t)nexpire, sizeof(nexpire));
578
579     pim_assert = 0;
580     bw_upcalls_n = 0;
581     bzero((caddr_t)bw_meter_timers, sizeof(bw_meter_timers));
582
583     callout_init(&expire_upcalls_ch);
584     callout_init(&bw_upcalls_ch);
585     callout_init(&bw_meter_ch);
586     callout_init(&tbf_reprocess_q_ch);
587
588     callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
589     callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
590                   expire_bw_upcalls_send, NULL);
591     callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
592
593     mrt_api_config = 0;
594
595     if (mrtdebug)
596         log(LOG_DEBUG, "ip_mrouter_init\n");
597
598     return 0;
599 }
600
601 /*
602  * Disable multicast routing
603  */
604 static int
605 X_ip_mrouter_done(void)
606 {
607     vifi_t vifi;
608     int i;
609     struct ifnet *ifp;
610     struct ifreq ifr;
611     struct mfc *rt;
612     struct rtdetq *rte;
613
614     crit_enter();
615
616     /*
617      * For each phyint in use, disable promiscuous reception of all IP
618      * multicasts.
619      */
620     for (vifi = 0; vifi < numvifs; vifi++) {
621         if (viftable[vifi].v_lcl_addr.s_addr != 0 &&
622                 !(viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
623             struct sockaddr_in *so = (struct sockaddr_in *)&(ifr.ifr_addr);
624
625             so->sin_len = sizeof(struct sockaddr_in);
626             so->sin_family = AF_INET;
627             so->sin_addr.s_addr = INADDR_ANY;
628             ifp = viftable[vifi].v_ifp;
629             if_allmulti(ifp, 0);
630         }
631     }
632     bzero((caddr_t)tbftable, sizeof(tbftable));
633     bzero((caddr_t)viftable, sizeof(viftable));
634     numvifs = 0;
635     pim_assert = 0;
636
637     callout_stop(&expire_upcalls_ch);
638
639     mrt_api_config = 0;
640     bw_upcalls_n = 0;
641     callout_stop(&bw_upcalls_ch);
642     callout_stop(&bw_meter_ch);
643     callout_stop(&tbf_reprocess_q_ch);
644
645     /*
646      * Free all multicast forwarding cache entries.
647      */
648     for (i = 0; i < MFCTBLSIZ; i++) {
649         for (rt = mfctable[i]; rt != NULL; ) {
650             struct mfc *nr = rt->mfc_next;
651
652             for (rte = rt->mfc_stall; rte != NULL; ) {
653                 struct rtdetq *n = rte->next;
654
655                 m_freem(rte->m);
656                 free(rte, M_MRTABLE);
657                 rte = n;
658             }
659             free_bw_list(rt->mfc_bw_meter);
660             free(rt, M_MRTABLE);
661             rt = nr;
662         }
663     }
664
665     bzero((caddr_t)mfctable, sizeof(mfctable));
666
667     bzero(bw_meter_timers, sizeof(bw_meter_timers));
668
669     /*
670      * Reset de-encapsulation cache
671      */
672     last_encap_src = INADDR_ANY;
673     last_encap_vif = NULL;
674 #ifdef PIM
675     reg_vif_num = VIFI_INVALID;
676 #endif
677     have_encap_tunnel = 0;
678
679     ip_mrouter = NULL;
680
681     crit_exit();
682
683     if (mrtdebug)
684         log(LOG_DEBUG, "ip_mrouter_done\n");
685
686     return 0;
687 }
688
689 /*
690  * Set PIM assert processing global
691  */
692 static int
693 set_assert(int i)
694 {
695     if ((i != 1) && (i != 0))
696         return EINVAL;
697
698     pim_assert = i;
699
700     return 0;
701 }
702
703 /*
704  * Configure API capabilities
705  */
706 int
707 set_api_config(uint32_t *apival)
708 {
709     int i;
710
711     /*
712      * We can set the API capabilities only if it is the first operation
713      * after MRT_INIT. I.e.:
714      *  - there are no vifs installed
715      *  - pim_assert is not enabled
716      *  - the MFC table is empty
717      */
718     if (numvifs > 0) {
719         *apival = 0;
720         return EPERM;
721     }
722     if (pim_assert) {
723         *apival = 0;
724         return EPERM;
725     }
726     for (i = 0; i < MFCTBLSIZ; i++) {
727         if (mfctable[i] != NULL) {
728             *apival = 0;
729             return EPERM;
730         }
731     }
732
733     mrt_api_config = *apival & mrt_api_support;
734     *apival = mrt_api_config;
735
736     return 0;
737 }
738
739 /*
740  * Add a vif to the vif table
741  */
742 static int
743 add_vif(struct vifctl *vifcp)
744 {
745     struct vif *vifp = viftable + vifcp->vifc_vifi;
746     struct sockaddr_in sin = {sizeof sin, AF_INET};
747     struct ifaddr *ifa;
748     struct ifnet *ifp;
749     int error, i;
750     struct tbf *v_tbf = tbftable + vifcp->vifc_vifi;
751
752     if (vifcp->vifc_vifi >= MAXVIFS)
753         return EINVAL;
754     if (vifp->v_lcl_addr.s_addr != INADDR_ANY)
755         return EADDRINUSE;
756     if (vifcp->vifc_lcl_addr.s_addr == INADDR_ANY)
757         return EADDRNOTAVAIL;
758
759     /* Find the interface with an address in AF_INET family */
760 #ifdef PIM
761     if (vifcp->vifc_flags & VIFF_REGISTER) {
762         /*
763          * XXX: Because VIFF_REGISTER does not really need a valid
764          * local interface (e.g. it could be 127.0.0.2), we don't
765          * check its address.
766          */
767         ifp = NULL;
768     } else
769 #endif
770     {
771         sin.sin_addr = vifcp->vifc_lcl_addr;
772         ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
773         if (ifa == NULL)
774             return EADDRNOTAVAIL;
775         ifp = ifa->ifa_ifp;
776     }
777
778     if (vifcp->vifc_flags & VIFF_TUNNEL) {
779         if ((vifcp->vifc_flags & VIFF_SRCRT) == 0) {
780             /*
781              * An encapsulating tunnel is wanted.  Tell ipip_input() to
782              * start paying attention to encapsulated packets.
783              */
784             if (have_encap_tunnel == 0) {
785                 have_encap_tunnel = 1;
786                 for (i = 0; i < MAXVIFS; i++) {
787                     if_initname(&multicast_decap_if[i], "mdecap", i);
788                 }
789             }
790             /*
791              * Set interface to fake encapsulator interface
792              */
793             ifp = &multicast_decap_if[vifcp->vifc_vifi];
794             /*
795              * Prepare cached route entry
796              */
797             bzero(&vifp->v_route, sizeof(vifp->v_route));
798         } else {
799             log(LOG_ERR, "source routed tunnels not supported\n");
800             return EOPNOTSUPP;
801         }
802 #ifdef PIM
803     } else if (vifcp->vifc_flags & VIFF_REGISTER) {
804         ifp = &multicast_register_if;
805         if (mrtdebug)
806             log(LOG_DEBUG, "Adding a register vif, ifp: %p\n",
807                     (void *)&multicast_register_if);
808         if (reg_vif_num == VIFI_INVALID) {
809             if_initname(&multicast_register_if, "register_vif", 0);
810             multicast_register_if.if_flags = IFF_LOOPBACK;
811             bzero(&vifp->v_route, sizeof(vifp->v_route));
812             reg_vif_num = vifcp->vifc_vifi;
813         }
814 #endif
815     } else {            /* Make sure the interface supports multicast */
816         if ((ifp->if_flags & IFF_MULTICAST) == 0)
817             return EOPNOTSUPP;
818
819         /* Enable promiscuous reception of all IP multicasts from the if */
820         crit_enter();
821         error = if_allmulti(ifp, 1);
822         crit_exit();
823         if (error)
824             return error;
825     }
826
827     crit_enter();
828     /* define parameters for the tbf structure */
829     vifp->v_tbf = v_tbf;
830     GET_TIME(vifp->v_tbf->tbf_last_pkt_t);
831     vifp->v_tbf->tbf_n_tok = 0;
832     vifp->v_tbf->tbf_q_len = 0;
833     vifp->v_tbf->tbf_max_q_len = MAXQSIZE;
834     vifp->v_tbf->tbf_q = vifp->v_tbf->tbf_t = NULL;
835
836     vifp->v_flags     = vifcp->vifc_flags;
837     vifp->v_threshold = vifcp->vifc_threshold;
838     vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
839     vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
840     vifp->v_ifp       = ifp;
841     /* scaling up here allows division by 1024 in critical code */
842     vifp->v_rate_limit= vifcp->vifc_rate_limit * 1024 / 1000;
843     vifp->v_rsvp_on   = 0;
844     vifp->v_rsvpd     = NULL;
845     /* initialize per vif pkt counters */
846     vifp->v_pkt_in    = 0;
847     vifp->v_pkt_out   = 0;
848     vifp->v_bytes_in  = 0;
849     vifp->v_bytes_out = 0;
850     crit_exit();
851
852     /* Adjust numvifs up if the vifi is higher than numvifs */
853     if (numvifs <= vifcp->vifc_vifi) numvifs = vifcp->vifc_vifi + 1;
854
855     if (mrtdebug)
856         log(LOG_DEBUG, "add_vif #%d, lcladdr %lx, %s %lx, thresh %x, rate %d\n",
857             vifcp->vifc_vifi,
858             (u_long)ntohl(vifcp->vifc_lcl_addr.s_addr),
859             (vifcp->vifc_flags & VIFF_TUNNEL) ? "rmtaddr" : "mask",
860             (u_long)ntohl(vifcp->vifc_rmt_addr.s_addr),
861             vifcp->vifc_threshold,
862             vifcp->vifc_rate_limit);
863
864     return 0;
865 }
866
867 /*
868  * Delete a vif from the vif table
869  */
870 static int
871 del_vif(vifi_t vifi)
872 {
873     struct vif *vifp;
874
875     if (vifi >= numvifs)
876         return EINVAL;
877     vifp = &viftable[vifi];
878     if (vifp->v_lcl_addr.s_addr == INADDR_ANY)
879         return EADDRNOTAVAIL;
880
881     crit_enter();
882
883     if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
884         if_allmulti(vifp->v_ifp, 0);
885
886     if (vifp == last_encap_vif) {
887         last_encap_vif = NULL;
888         last_encap_src = INADDR_ANY;
889     }
890
891     /*
892      * Free packets queued at the interface
893      */
894     while (vifp->v_tbf->tbf_q) {
895         struct mbuf *m = vifp->v_tbf->tbf_q;
896
897         vifp->v_tbf->tbf_q = m->m_nextpkt;
898         m_freem(m);
899     }
900
901 #ifdef PIM
902     if (vifp->v_flags & VIFF_REGISTER)
903         reg_vif_num = VIFI_INVALID;
904 #endif
905
906     bzero((caddr_t)vifp->v_tbf, sizeof(*(vifp->v_tbf)));
907     bzero((caddr_t)vifp, sizeof (*vifp));
908
909     if (mrtdebug)
910         log(LOG_DEBUG, "del_vif %d, numvifs %d\n", vifi, numvifs);
911
912     /* Adjust numvifs down */
913     for (vifi = numvifs; vifi > 0; vifi--)
914         if (viftable[vifi-1].v_lcl_addr.s_addr != INADDR_ANY)
915             break;
916     numvifs = vifi;
917
918     crit_exit();
919
920     return 0;
921 }
922
923 /*
924  * update an mfc entry without resetting counters and S,G addresses.
925  */
926 static void
927 update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
928 {
929     int i;
930
931     rt->mfc_parent = mfccp->mfcc_parent;
932     for (i = 0; i < numvifs; i++) {
933         rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
934         rt->mfc_flags[i] = mfccp->mfcc_flags[i] & mrt_api_config &
935             MRT_MFC_FLAGS_ALL;
936     }
937     /* set the RP address */
938     if (mrt_api_config & MRT_MFC_RP)
939         rt->mfc_rp = mfccp->mfcc_rp;
940     else
941         rt->mfc_rp.s_addr = INADDR_ANY;
942 }
943
944 /*
945  * fully initialize an mfc entry from the parameter.
946  */
947 static void
948 init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
949 {
950     rt->mfc_origin     = mfccp->mfcc_origin;
951     rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
952
953     update_mfc_params(rt, mfccp);
954
955     /* initialize pkt counters per src-grp */
956     rt->mfc_pkt_cnt    = 0;
957     rt->mfc_byte_cnt   = 0;
958     rt->mfc_wrong_if   = 0;
959     rt->mfc_last_assert.tv_sec = rt->mfc_last_assert.tv_usec = 0;
960 }
961
962
963 /*
964  * Add an mfc entry
965  */
966 static int
967 add_mfc(struct mfcctl2 *mfccp)
968 {
969     struct mfc *rt;
970     u_long hash;
971     struct rtdetq *rte;
972     u_short nstl;
973
974     rt = mfc_find(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
975
976     /* If an entry already exists, just update the fields */
977     if (rt) {
978         if (mrtdebug & DEBUG_MFC)
979             log(LOG_DEBUG,"add_mfc update o %lx g %lx p %x\n",
980                 (u_long)ntohl(mfccp->mfcc_origin.s_addr),
981                 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
982                 mfccp->mfcc_parent);
983
984         crit_enter();
985         update_mfc_params(rt, mfccp);
986         crit_exit();
987         return 0;
988     }
989
990     /*
991      * Find the entry for which the upcall was made and update
992      */
993     crit_enter();
994     hash = MFCHASH(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
995     for (rt = mfctable[hash], nstl = 0; rt; rt = rt->mfc_next) {
996
997         if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
998                 (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr) &&
999                 (rt->mfc_stall != NULL)) {
1000
1001             if (nstl++)
1002                 log(LOG_ERR, "add_mfc %s o %lx g %lx p %x dbx %p\n",
1003                     "multiple kernel entries",
1004                     (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1005                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1006                     mfccp->mfcc_parent, (void *)rt->mfc_stall);
1007
1008             if (mrtdebug & DEBUG_MFC)
1009                 log(LOG_DEBUG,"add_mfc o %lx g %lx p %x dbg %p\n",
1010                     (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1011                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1012                     mfccp->mfcc_parent, (void *)rt->mfc_stall);
1013
1014             init_mfc_params(rt, mfccp);
1015
1016             rt->mfc_expire = 0; /* Don't clean this guy up */
1017             nexpire[hash]--;
1018
1019             /* free packets Qed at the end of this entry */
1020             for (rte = rt->mfc_stall; rte != NULL; ) {
1021                 struct rtdetq *n = rte->next;
1022
1023                 ip_mdq(rte->m, rte->ifp, rt, -1);
1024                 m_freem(rte->m);
1025                 free(rte, M_MRTABLE);
1026                 rte = n;
1027             }
1028             rt->mfc_stall = NULL;
1029         }
1030     }
1031
1032     /*
1033      * It is possible that an entry is being inserted without an upcall
1034      */
1035     if (nstl == 0) {
1036         if (mrtdebug & DEBUG_MFC)
1037             log(LOG_DEBUG,"add_mfc no upcall h %lu o %lx g %lx p %x\n",
1038                 hash, (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1039                 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1040                 mfccp->mfcc_parent);
1041
1042         for (rt = mfctable[hash]; rt != NULL; rt = rt->mfc_next) {
1043             if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1044                     (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr)) {
1045                 init_mfc_params(rt, mfccp);
1046                 if (rt->mfc_expire)
1047                     nexpire[hash]--;
1048                 rt->mfc_expire = 0;
1049                 break; /* XXX */
1050             }
1051         }
1052         if (rt == NULL) {               /* no upcall, so make a new entry */
1053             rt = malloc(sizeof(*rt), M_MRTABLE, M_INTWAIT | M_NULLOK);
1054             if (rt == NULL) {
1055                     crit_exit();
1056                     return ENOBUFS;
1057             }
1058
1059             init_mfc_params(rt, mfccp);
1060             rt->mfc_expire     = 0;
1061             rt->mfc_stall      = NULL;
1062
1063             rt->mfc_bw_meter = NULL;
1064             /* insert new entry at head of hash chain */
1065             rt->mfc_next = mfctable[hash];
1066             mfctable[hash] = rt;
1067         }
1068     }
1069     crit_exit();
1070     return 0;
1071 }
1072
1073 /*
1074  * Delete an mfc entry
1075  */
1076 static int
1077 del_mfc(struct mfcctl2 *mfccp)
1078 {
1079     struct in_addr      origin;
1080     struct in_addr      mcastgrp;
1081     struct mfc          *rt;
1082     struct mfc          **nptr;
1083     u_long              hash;
1084     struct bw_meter     *list;
1085
1086     origin = mfccp->mfcc_origin;
1087     mcastgrp = mfccp->mfcc_mcastgrp;
1088
1089     if (mrtdebug & DEBUG_MFC)
1090         log(LOG_DEBUG,"del_mfc orig %lx mcastgrp %lx\n",
1091             (u_long)ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
1092
1093     crit_enter();
1094
1095     hash = MFCHASH(origin.s_addr, mcastgrp.s_addr);
1096     for (nptr = &mfctable[hash]; (rt = *nptr) != NULL; nptr = &rt->mfc_next)
1097         if (origin.s_addr == rt->mfc_origin.s_addr &&
1098                 mcastgrp.s_addr == rt->mfc_mcastgrp.s_addr &&
1099                 rt->mfc_stall == NULL)
1100             break;
1101     if (rt == NULL) {
1102         crit_exit();
1103         return EADDRNOTAVAIL;
1104     }
1105
1106     *nptr = rt->mfc_next;
1107
1108     /*
1109      * free the bw_meter entries
1110      */
1111     list = rt->mfc_bw_meter;
1112     rt->mfc_bw_meter = NULL;
1113
1114     free(rt, M_MRTABLE);
1115
1116     crit_exit();
1117
1118     free_bw_list(list);
1119
1120     return 0;
1121 }
1122
1123 /*
1124  * Send a message to mrouted on the multicast routing socket
1125  */
1126 static int
1127 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1128 {
1129     if (s) {
1130         if (sbappendaddr(&s->so_rcv, (struct sockaddr *)src, mm, NULL) != 0) {
1131             sorwakeup(s);
1132             return 0;
1133         }
1134     }
1135     m_freem(mm);
1136     return -1;
1137 }
1138
1139 /*
1140  * IP multicast forwarding function. This function assumes that the packet
1141  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1142  * pointed to by "ifp", and the packet is to be relayed to other networks
1143  * that have members of the packet's destination IP multicast group.
1144  *
1145  * The packet is returned unscathed to the caller, unless it is
1146  * erroneous, in which case a non-zero return value tells the caller to
1147  * discard it.
1148  */
1149
1150 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1151
1152 static int
1153 X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1154     struct ip_moptions *imo)
1155 {
1156     struct mfc *rt;
1157     vifi_t vifi;
1158
1159     if (mrtdebug & DEBUG_FORWARD)
1160         log(LOG_DEBUG, "ip_mforward: src %lx, dst %lx, ifp %p\n",
1161             (u_long)ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr),
1162             (void *)ifp);
1163
1164     if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1165                 ((u_char *)(ip + 1))[1] != IPOPT_LSRR ) {
1166         /*
1167          * Packet arrived via a physical interface or
1168          * an encapsulated tunnel or a register_vif.
1169          */
1170     } else {
1171         /*
1172          * Packet arrived through a source-route tunnel.
1173          * Source-route tunnels are no longer supported.
1174          */
1175         static int last_log;
1176         if (last_log != time_second) {
1177             last_log = time_second;
1178             log(LOG_ERR,
1179                 "ip_mforward: received source-routed packet from %lx\n",
1180                 (u_long)ntohl(ip->ip_src.s_addr));
1181         }
1182         return 1;
1183     }
1184
1185     if (imo && ((vifi = imo->imo_multicast_vif) < numvifs)) {
1186         if (ip->ip_ttl < 255)
1187             ip->ip_ttl++;       /* compensate for -1 in *_send routines */
1188         if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1189             struct vif *vifp = viftable + vifi;
1190
1191             printf("Sending IPPROTO_RSVP from %lx to %lx on vif %d (%s%s)\n",
1192                 (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr),
1193                 vifi,
1194                 (vifp->v_flags & VIFF_TUNNEL) ? "tunnel on " : "",
1195                 vifp->v_ifp->if_xname);
1196         }
1197         return ip_mdq(m, ifp, NULL, vifi);
1198     }
1199     if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1200         printf("Warning: IPPROTO_RSVP from %lx to %lx without vif option\n",
1201             (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr));
1202         if (!imo)
1203             printf("In fact, no options were specified at all\n");
1204     }
1205
1206     /*
1207      * Don't forward a packet with time-to-live of zero or one,
1208      * or a packet destined to a local-only group.
1209      */
1210     if (ip->ip_ttl <= 1 || ntohl(ip->ip_dst.s_addr) <= INADDR_MAX_LOCAL_GROUP)
1211         return 0;
1212
1213     /*
1214      * Determine forwarding vifs from the forwarding cache table
1215      */
1216     crit_enter();
1217     ++mrtstat.mrts_mfc_lookups;
1218     rt = mfc_find(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1219
1220     /* Entry exists, so forward if necessary */
1221     if (rt != NULL) {
1222         crit_exit();
1223         return ip_mdq(m, ifp, rt, -1);
1224     } else {
1225         /*
1226          * If we don't have a route for packet's origin,
1227          * Make a copy of the packet & send message to routing daemon
1228          */
1229
1230         struct mbuf *mb0;
1231         struct rtdetq *rte;
1232         u_long hash;
1233         int hlen = ip->ip_hl << 2;
1234
1235         ++mrtstat.mrts_mfc_misses;
1236
1237         mrtstat.mrts_no_route++;
1238         if (mrtdebug & (DEBUG_FORWARD | DEBUG_MFC))
1239             log(LOG_DEBUG, "ip_mforward: no rte s %lx g %lx\n",
1240                 (u_long)ntohl(ip->ip_src.s_addr),
1241                 (u_long)ntohl(ip->ip_dst.s_addr));
1242
1243         /*
1244          * Allocate mbufs early so that we don't do extra work if we are
1245          * just going to fail anyway.  Make sure to pullup the header so
1246          * that other people can't step on it.
1247          */
1248         rte = malloc((sizeof *rte), M_MRTABLE, M_INTWAIT | M_NULLOK);
1249         if (rte == NULL) {
1250                 crit_exit();
1251                 return ENOBUFS;
1252         }
1253
1254         mb0 = m_copypacket(m, MB_DONTWAIT);
1255         if (mb0 && (M_HASCL(mb0) || mb0->m_len < hlen))
1256             mb0 = m_pullup(mb0, hlen);
1257         if (mb0 == NULL) {
1258             free(rte, M_MRTABLE);
1259             crit_exit();
1260             return ENOBUFS;
1261         }
1262
1263         /* is there an upcall waiting for this flow ? */
1264         hash = MFCHASH(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1265         for (rt = mfctable[hash]; rt; rt = rt->mfc_next) {
1266             if ((ip->ip_src.s_addr == rt->mfc_origin.s_addr) &&
1267                     (ip->ip_dst.s_addr == rt->mfc_mcastgrp.s_addr) &&
1268                     (rt->mfc_stall != NULL))
1269                 break;
1270         }
1271
1272         if (rt == NULL) {
1273             int i;
1274             struct igmpmsg *im;
1275             struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1276             struct mbuf *mm;
1277
1278             /*
1279              * Locate the vifi for the incoming interface for this packet.
1280              * If none found, drop packet.
1281              */
1282             for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1283                 ;
1284             if (vifi >= numvifs)        /* vif not found, drop packet */
1285                 goto non_fatal;
1286
1287             /* no upcall, so make a new entry */
1288             rt = malloc(sizeof(*rt), M_MRTABLE, M_INTWAIT | M_NULLOK);
1289             if (rt == NULL)
1290                     goto fail;
1291
1292             /* Make a copy of the header to send to the user level process */
1293             mm = m_copy(mb0, 0, hlen);
1294             if (mm == NULL)
1295                 goto fail1;
1296
1297             /*
1298              * Send message to routing daemon to install
1299              * a route into the kernel table
1300              */
1301
1302             im = mtod(mm, struct igmpmsg *);
1303             im->im_msgtype = IGMPMSG_NOCACHE;
1304             im->im_mbz = 0;
1305             im->im_vif = vifi;
1306
1307             mrtstat.mrts_upcalls++;
1308
1309             k_igmpsrc.sin_addr = ip->ip_src;
1310             if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1311                 log(LOG_WARNING, "ip_mforward: ip_mrouter socket queue full\n");
1312                 ++mrtstat.mrts_upq_sockfull;
1313 fail1:
1314                 free(rt, M_MRTABLE);
1315 fail:
1316                 free(rte, M_MRTABLE);
1317                 m_freem(mb0);
1318                 crit_exit();
1319                 return ENOBUFS;
1320             }
1321
1322             /* insert new entry at head of hash chain */
1323             rt->mfc_origin.s_addr     = ip->ip_src.s_addr;
1324             rt->mfc_mcastgrp.s_addr   = ip->ip_dst.s_addr;
1325             rt->mfc_expire            = UPCALL_EXPIRE;
1326             nexpire[hash]++;
1327             for (i = 0; i < numvifs; i++) {
1328                 rt->mfc_ttls[i] = 0;
1329                 rt->mfc_flags[i] = 0;
1330             }
1331             rt->mfc_parent = -1;
1332
1333             rt->mfc_rp.s_addr = INADDR_ANY; /* clear the RP address */
1334
1335             rt->mfc_bw_meter = NULL;
1336
1337             /* link into table */
1338             rt->mfc_next   = mfctable[hash];
1339             mfctable[hash] = rt;
1340             rt->mfc_stall = rte;
1341
1342         } else {
1343             /* determine if q has overflowed */
1344             int npkts = 0;
1345             struct rtdetq **p;
1346
1347             /*
1348              * XXX ouch! we need to append to the list, but we
1349              * only have a pointer to the front, so we have to
1350              * scan the entire list every time.
1351              */
1352             for (p = &rt->mfc_stall; *p != NULL; p = &(*p)->next)
1353                 npkts++;
1354
1355             if (npkts > MAX_UPQ) {
1356                 mrtstat.mrts_upq_ovflw++;
1357 non_fatal:
1358                 free(rte, M_MRTABLE);
1359                 m_freem(mb0);
1360                 crit_exit();
1361                 return 0;
1362             }
1363
1364             /* Add this entry to the end of the queue */
1365             *p = rte;
1366         }
1367
1368         rte->m                  = mb0;
1369         rte->ifp                = ifp;
1370         rte->next               = NULL;
1371
1372         crit_exit();
1373         return 0;
1374     }
1375 }
1376
1377 /*
1378  * Clean up the cache entry if upcall is not serviced
1379  */
1380 static void
1381 expire_upcalls(void *unused)
1382 {
1383     struct rtdetq *rte;
1384     struct mfc *mfc, **nptr;
1385     int i;
1386
1387     crit_enter();
1388     for (i = 0; i < MFCTBLSIZ; i++) {
1389         if (nexpire[i] == 0)
1390             continue;
1391         nptr = &mfctable[i];
1392         for (mfc = *nptr; mfc != NULL; mfc = *nptr) {
1393             /*
1394              * Skip real cache entries
1395              * Make sure it wasn't marked to not expire (shouldn't happen)
1396              * If it expires now
1397              */
1398             if (mfc->mfc_stall != NULL && mfc->mfc_expire != 0 &&
1399                     --mfc->mfc_expire == 0) {
1400                 if (mrtdebug & DEBUG_EXPIRE)
1401                     log(LOG_DEBUG, "expire_upcalls: expiring (%lx %lx)\n",
1402                         (u_long)ntohl(mfc->mfc_origin.s_addr),
1403                         (u_long)ntohl(mfc->mfc_mcastgrp.s_addr));
1404                 /*
1405                  * drop all the packets
1406                  * free the mbuf with the pkt, if, timing info
1407                  */
1408                 for (rte = mfc->mfc_stall; rte; ) {
1409                     struct rtdetq *n = rte->next;
1410
1411                     m_freem(rte->m);
1412                     free(rte, M_MRTABLE);
1413                     rte = n;
1414                 }
1415                 ++mrtstat.mrts_cache_cleanups;
1416                 nexpire[i]--;
1417
1418                 /*
1419                  * free the bw_meter entries
1420                  */
1421                 while (mfc->mfc_bw_meter != NULL) {
1422                     struct bw_meter *x = mfc->mfc_bw_meter;
1423
1424                     mfc->mfc_bw_meter = x->bm_mfc_next;
1425                     free(x, M_BWMETER);
1426                 }
1427
1428                 *nptr = mfc->mfc_next;
1429                 free(mfc, M_MRTABLE);
1430             } else {
1431                 nptr = &mfc->mfc_next;
1432             }
1433         }
1434     }
1435     callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
1436     crit_exit();
1437 }
1438
1439 /*
1440  * Packet forwarding routine once entry in the cache is made
1441  */
1442 static int
1443 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1444 {
1445     struct ip  *ip = mtod(m, struct ip *);
1446     vifi_t vifi;
1447     int plen = ip->ip_len;
1448
1449 /*
1450  * Macro to send packet on vif.  Since RSVP packets don't get counted on
1451  * input, they shouldn't get counted on output, so statistics keeping is
1452  * separate.
1453  */
1454 #define MC_SEND(ip,vifp,m) {                            \
1455                 if ((vifp)->v_flags & VIFF_TUNNEL)      \
1456                     encap_send((ip), (vifp), (m));      \
1457                 else                                    \
1458                     phyint_send((ip), (vifp), (m));     \
1459 }
1460
1461     /*
1462      * If xmt_vif is not -1, send on only the requested vif.
1463      *
1464      * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1465      */
1466     if (xmt_vif < numvifs) {
1467 #ifdef PIM
1468         if (viftable[xmt_vif].v_flags & VIFF_REGISTER)
1469             pim_register_send(ip, viftable + xmt_vif, m, rt);
1470         else
1471 #endif
1472         MC_SEND(ip, viftable + xmt_vif, m);
1473         return 1;
1474     }
1475
1476     /*
1477      * Don't forward if it didn't arrive from the parent vif for its origin.
1478      */
1479     vifi = rt->mfc_parent;
1480     if ((vifi >= numvifs) || (viftable[vifi].v_ifp != ifp)) {
1481         /* came in the wrong interface */
1482         if (mrtdebug & DEBUG_FORWARD)
1483             log(LOG_DEBUG, "wrong if: ifp %p vifi %d vififp %p\n",
1484                 (void *)ifp, vifi, (void *)viftable[vifi].v_ifp);
1485         ++mrtstat.mrts_wrong_if;
1486         ++rt->mfc_wrong_if;
1487         /*
1488          * If we are doing PIM assert processing, send a message
1489          * to the routing daemon.
1490          *
1491          * XXX: A PIM-SM router needs the WRONGVIF detection so it
1492          * can complete the SPT switch, regardless of the type
1493          * of the iif (broadcast media, GRE tunnel, etc).
1494          */
1495         if (pim_assert && (vifi < numvifs) && viftable[vifi].v_ifp) {
1496             struct timeval now;
1497             u_long delta;
1498
1499 #ifdef PIM
1500             if (ifp == &multicast_register_if)
1501                 pimstat.pims_rcv_registers_wrongiif++;
1502 #endif
1503
1504             /* Get vifi for the incoming packet */
1505             for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1506                 ;
1507             if (vifi >= numvifs)
1508                 return 0;       /* The iif is not found: ignore the packet. */
1509
1510             if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1511                 return 0;       /* WRONGVIF disabled: ignore the packet */
1512
1513             GET_TIME(now);
1514
1515             TV_DELTA(rt->mfc_last_assert, now, delta);
1516
1517             if (delta > ASSERT_MSG_TIME) {
1518                 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1519                 struct igmpmsg *im;
1520                 int hlen = ip->ip_hl << 2;
1521                 struct mbuf *mm = m_copy(m, 0, hlen);
1522
1523                 if (mm && (M_HASCL(mm) || mm->m_len < hlen))
1524                     mm = m_pullup(mm, hlen);
1525                 if (mm == NULL)
1526                     return ENOBUFS;
1527
1528                 rt->mfc_last_assert = now;
1529
1530                 im = mtod(mm, struct igmpmsg *);
1531                 im->im_msgtype  = IGMPMSG_WRONGVIF;
1532                 im->im_mbz              = 0;
1533                 im->im_vif              = vifi;
1534
1535                 mrtstat.mrts_upcalls++;
1536
1537                 k_igmpsrc.sin_addr = im->im_src;
1538                 if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1539                     log(LOG_WARNING,
1540                         "ip_mforward: ip_mrouter socket queue full\n");
1541                     ++mrtstat.mrts_upq_sockfull;
1542                     return ENOBUFS;
1543                 }
1544             }
1545         }
1546         return 0;
1547     }
1548
1549     /* If I sourced this packet, it counts as output, else it was input. */
1550     if (ip->ip_src.s_addr == viftable[vifi].v_lcl_addr.s_addr) {
1551         viftable[vifi].v_pkt_out++;
1552         viftable[vifi].v_bytes_out += plen;
1553     } else {
1554         viftable[vifi].v_pkt_in++;
1555         viftable[vifi].v_bytes_in += plen;
1556     }
1557     rt->mfc_pkt_cnt++;
1558     rt->mfc_byte_cnt += plen;
1559
1560     /*
1561      * For each vif, decide if a copy of the packet should be forwarded.
1562      * Forward if:
1563      *          - the ttl exceeds the vif's threshold
1564      *          - there are group members downstream on interface
1565      */
1566     for (vifi = 0; vifi < numvifs; vifi++)
1567         if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1568             viftable[vifi].v_pkt_out++;
1569             viftable[vifi].v_bytes_out += plen;
1570 #ifdef PIM
1571             if (viftable[vifi].v_flags & VIFF_REGISTER)
1572                 pim_register_send(ip, viftable + vifi, m, rt);
1573             else
1574 #endif
1575             MC_SEND(ip, viftable+vifi, m);
1576         }
1577
1578     /*
1579      * Perform upcall-related bw measuring.
1580      */
1581     if (rt->mfc_bw_meter != NULL) {
1582         struct bw_meter *x;
1583         struct timeval now;
1584
1585         GET_TIME(now);
1586         for (x = rt->mfc_bw_meter; x != NULL; x = x->bm_mfc_next)
1587             bw_meter_receive_packet(x, plen, &now);
1588     }
1589
1590     return 0;
1591 }
1592
1593 /*
1594  * check if a vif number is legal/ok. This is used by ip_output.
1595  */
1596 static int
1597 X_legal_vif_num(int vif)
1598 {
1599     return (vif >= 0 && vif < numvifs);
1600 }
1601
1602 /*
1603  * Return the local address used by this vif
1604  */
1605 static u_long
1606 X_ip_mcast_src(int vifi)
1607 {
1608     if (vifi >= 0 && vifi < numvifs)
1609         return viftable[vifi].v_lcl_addr.s_addr;
1610     else
1611         return INADDR_ANY;
1612 }
1613
1614 static void
1615 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1616 {
1617     struct mbuf *mb_copy;
1618     int hlen = ip->ip_hl << 2;
1619
1620     /*
1621      * Make a new reference to the packet; make sure that
1622      * the IP header is actually copied, not just referenced,
1623      * so that ip_output() only scribbles on the copy.
1624      */
1625     mb_copy = m_copypacket(m, MB_DONTWAIT);
1626     if (mb_copy && (M_HASCL(mb_copy) || mb_copy->m_len < hlen))
1627         mb_copy = m_pullup(mb_copy, hlen);
1628     if (mb_copy == NULL)
1629         return;
1630
1631     if (vifp->v_rate_limit == 0)
1632         tbf_send_packet(vifp, mb_copy);
1633     else
1634         tbf_control(vifp, mb_copy, mtod(mb_copy, struct ip *), ip->ip_len);
1635 }
1636
1637 static void
1638 encap_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1639 {
1640     struct mbuf *mb_copy;
1641     struct ip *ip_copy;
1642     int i, len = ip->ip_len;
1643
1644     /* Take care of delayed checksums */
1645     if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1646         in_delayed_cksum(m);
1647         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1648     }
1649
1650     /*
1651      * copy the old packet & pullup its IP header into the
1652      * new mbuf so we can modify it.  Try to fill the new
1653      * mbuf since if we don't the ethernet driver will.
1654      */
1655     MGETHDR(mb_copy, MB_DONTWAIT, MT_HEADER);
1656     if (mb_copy == NULL)
1657         return;
1658     mb_copy->m_data += max_linkhdr;
1659     mb_copy->m_len = sizeof(multicast_encap_iphdr);
1660
1661     if ((mb_copy->m_next = m_copypacket(m, MB_DONTWAIT)) == NULL) {
1662         m_freem(mb_copy);
1663         return;
1664     }
1665     i = MHLEN - M_LEADINGSPACE(mb_copy);
1666     if (i > len)
1667         i = len;
1668     mb_copy = m_pullup(mb_copy, i);
1669     if (mb_copy == NULL)
1670         return;
1671     mb_copy->m_pkthdr.len = len + sizeof(multicast_encap_iphdr);
1672
1673     /*
1674      * fill in the encapsulating IP header.
1675      */
1676     ip_copy = mtod(mb_copy, struct ip *);
1677     *ip_copy = multicast_encap_iphdr;
1678 #ifdef RANDOM_IP_ID
1679     ip_copy->ip_id = ip_randomid();
1680 #else
1681     ip_copy->ip_id = htons(ip_id++);
1682 #endif
1683     ip_copy->ip_len += len;
1684     ip_copy->ip_src = vifp->v_lcl_addr;
1685     ip_copy->ip_dst = vifp->v_rmt_addr;
1686
1687     /*
1688      * turn the encapsulated IP header back into a valid one.
1689      */
1690     ip = (struct ip *)((caddr_t)ip_copy + sizeof(multicast_encap_iphdr));
1691     --ip->ip_ttl;
1692     ip->ip_len = htons(ip->ip_len);
1693     ip->ip_off = htons(ip->ip_off);
1694     ip->ip_sum = 0;
1695     mb_copy->m_data += sizeof(multicast_encap_iphdr);
1696     ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
1697     mb_copy->m_data -= sizeof(multicast_encap_iphdr);
1698
1699     if (vifp->v_rate_limit == 0)
1700         tbf_send_packet(vifp, mb_copy);
1701     else
1702         tbf_control(vifp, mb_copy, ip, ip_copy->ip_len);
1703 }
1704
1705 /*
1706  * De-encapsulate a packet and feed it back through ip input (this
1707  * routine is called whenever IP gets a packet with proto type
1708  * ENCAP_PROTO and a local destination address).
1709  *
1710  * This is similar to mroute_encapcheck() + mroute_encap_input() in -current.
1711  */
1712 static void
1713 X_ipip_input(struct mbuf *m, int off, int proto)
1714 {
1715     struct ip *ip = mtod(m, struct ip *);
1716     int hlen = ip->ip_hl << 2;
1717
1718     if (!have_encap_tunnel) {
1719         rip_input(m, off, proto);
1720         return;
1721     }
1722     /*
1723      * dump the packet if it's not to a multicast destination or if
1724      * we don't have an encapsulating tunnel with the source.
1725      * Note:  This code assumes that the remote site IP address
1726      * uniquely identifies the tunnel (i.e., that this site has
1727      * at most one tunnel with the remote site).
1728      */
1729     if (!IN_MULTICAST(ntohl(((struct ip *)((char *)ip+hlen))->ip_dst.s_addr))) {
1730         ++mrtstat.mrts_bad_tunnel;
1731         m_freem(m);
1732         return;
1733     }
1734     if (ip->ip_src.s_addr != last_encap_src) {
1735         struct vif *vifp = viftable;
1736         struct vif *vife = vifp + numvifs;
1737
1738         last_encap_src = ip->ip_src.s_addr;
1739         last_encap_vif = NULL;
1740         for ( ; vifp < vife; ++vifp)
1741             if (vifp->v_rmt_addr.s_addr == ip->ip_src.s_addr) {
1742                 if ((vifp->v_flags & (VIFF_TUNNEL|VIFF_SRCRT))
1743                     == VIFF_TUNNEL)
1744                     last_encap_vif = vifp;
1745                 break;
1746             }
1747     }
1748     if (last_encap_vif == NULL) {
1749         last_encap_src = INADDR_ANY;
1750         mrtstat.mrts_cant_tunnel++; /*XXX*/
1751         m_freem(m);
1752         if (mrtdebug)
1753             log(LOG_DEBUG, "ip_mforward: no tunnel with %lx\n",
1754                 (u_long)ntohl(ip->ip_src.s_addr));
1755         return;
1756     }
1757
1758     if (hlen > sizeof(struct ip))
1759         ip_stripoptions(m);
1760     m->m_data += sizeof(struct ip);
1761     m->m_len -= sizeof(struct ip);
1762     m->m_pkthdr.len -= sizeof(struct ip);
1763     m->m_pkthdr.rcvif = last_encap_vif->v_ifp;
1764
1765     netisr_queue(NETISR_IP, m);
1766 }
1767
1768 /*
1769  * Token bucket filter module
1770  */
1771
1772 static void
1773 tbf_control(struct vif *vifp, struct mbuf *m, struct ip *ip, u_long p_len)
1774 {
1775     struct tbf *t = vifp->v_tbf;
1776
1777     if (p_len > MAX_BKT_SIZE) {         /* drop if packet is too large */
1778         mrtstat.mrts_pkt2large++;
1779         m_freem(m);
1780         return;
1781     }
1782
1783     tbf_update_tokens(vifp);
1784
1785     if (t->tbf_q_len == 0) {            /* queue empty...               */
1786         if (p_len <= t->tbf_n_tok) {    /* send packet if enough tokens */
1787             t->tbf_n_tok -= p_len;
1788             tbf_send_packet(vifp, m);
1789         } else {                        /* no, queue packet and try later */
1790             tbf_queue(vifp, m);
1791             callout_reset(&tbf_reprocess_q_ch, TBF_REPROCESS,
1792                           tbf_reprocess_q, vifp);
1793         }
1794     } else if (t->tbf_q_len < t->tbf_max_q_len) {
1795         /* finite queue length, so queue pkts and process queue */
1796         tbf_queue(vifp, m);
1797         tbf_process_q(vifp);
1798     } else {
1799         /* queue full, try to dq and queue and process */
1800         if (!tbf_dq_sel(vifp, ip)) {
1801             mrtstat.mrts_q_overflow++;
1802             m_freem(m);
1803         } else {
1804             tbf_queue(vifp, m);
1805             tbf_process_q(vifp);
1806         }
1807     }
1808 }
1809
1810 /*
1811  * adds a packet to the queue at the interface
1812  */
1813 static void
1814 tbf_queue(struct vif *vifp, struct mbuf *m)
1815 {
1816     struct tbf *t = vifp->v_tbf;
1817
1818     crit_enter();
1819
1820     if (t->tbf_t == NULL)       /* Queue was empty */
1821         t->tbf_q = m;
1822     else                        /* Insert at tail */
1823         t->tbf_t->m_nextpkt = m;
1824
1825     t->tbf_t = m;               /* Set new tail pointer */
1826
1827 #ifdef DIAGNOSTIC
1828     /* Make sure we didn't get fed a bogus mbuf */
1829     if (m->m_nextpkt)
1830         panic("tbf_queue: m_nextpkt");
1831 #endif
1832     m->m_nextpkt = NULL;
1833
1834     t->tbf_q_len++;
1835
1836     crit_exit();
1837 }
1838
1839 /*
1840  * processes the queue at the interface
1841  */
1842 static void
1843 tbf_process_q(struct vif *vifp)
1844 {
1845     struct tbf *t = vifp->v_tbf;
1846
1847     crit_enter();
1848
1849     /* loop through the queue at the interface and send as many packets
1850      * as possible
1851      */
1852     while (t->tbf_q_len > 0) {
1853         struct mbuf *m = t->tbf_q;
1854         int len = mtod(m, struct ip *)->ip_len;
1855
1856         /* determine if the packet can be sent */
1857         if (len > t->tbf_n_tok) /* not enough tokens, we are done */
1858             break;
1859         /* ok, reduce no of tokens, dequeue and send the packet. */
1860         t->tbf_n_tok -= len;
1861
1862         t->tbf_q = m->m_nextpkt;
1863         if (--t->tbf_q_len == 0)
1864             t->tbf_t = NULL;
1865
1866         m->m_nextpkt = NULL;
1867         tbf_send_packet(vifp, m);
1868     }
1869     crit_exit();
1870 }
1871
1872 static void
1873 tbf_reprocess_q(void *xvifp)
1874 {
1875     struct vif *vifp = xvifp;
1876
1877     if (ip_mrouter == NULL)
1878         return;
1879     tbf_update_tokens(vifp);
1880     tbf_process_q(vifp);
1881     if (vifp->v_tbf->tbf_q_len)
1882         callout_reset(&tbf_reprocess_q_ch, TBF_REPROCESS,
1883                       tbf_reprocess_q, vifp);
1884 }
1885
1886 /* function that will selectively discard a member of the queue
1887  * based on the precedence value and the priority
1888  */
1889 static int
1890 tbf_dq_sel(struct vif *vifp, struct ip *ip)
1891 {
1892     u_int p;
1893     struct mbuf *m, *last;
1894     struct mbuf **np;
1895     struct tbf *t = vifp->v_tbf;
1896
1897     crit_enter();
1898
1899     p = priority(vifp, ip);
1900
1901     np = &t->tbf_q;
1902     last = NULL;
1903     while ((m = *np) != NULL) {
1904         if (p > priority(vifp, mtod(m, struct ip *))) {
1905             *np = m->m_nextpkt;
1906             /* If we're removing the last packet, fix the tail pointer */
1907             if (m == t->tbf_t)
1908                 t->tbf_t = last;
1909             m_freem(m);
1910             /* It's impossible for the queue to be empty, but check anyways. */
1911             if (--t->tbf_q_len == 0)
1912                 t->tbf_t = NULL;
1913             crit_exit();
1914             mrtstat.mrts_drop_sel++;
1915             return 1;
1916         }
1917         np = &m->m_nextpkt;
1918         last = m;
1919     }
1920     crit_exit();
1921     return 0;
1922 }
1923
1924 static void
1925 tbf_send_packet(struct vif *vifp, struct mbuf *m)
1926 {
1927     crit_enter();
1928
1929     if (vifp->v_flags & VIFF_TUNNEL)    /* If tunnel options */
1930         ip_output(m, NULL, &vifp->v_route, IP_FORWARDING, NULL, NULL);
1931     else {
1932         struct ip_moptions imo;
1933         int error;
1934         static struct route ro; /* XXX check this */
1935
1936         imo.imo_multicast_ifp  = vifp->v_ifp;
1937         imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1938         imo.imo_multicast_loop = 1;
1939         imo.imo_multicast_vif  = -1;
1940
1941         /*
1942          * Re-entrancy should not be a problem here, because
1943          * the packets that we send out and are looped back at us
1944          * should get rejected because they appear to come from
1945          * the loopback interface, thus preventing looping.
1946          */
1947         error = ip_output(m, NULL, &ro, IP_FORWARDING, &imo, NULL);
1948
1949         if (mrtdebug & DEBUG_XMIT)
1950             log(LOG_DEBUG, "phyint_send on vif %d err %d\n",
1951                 (int)(vifp - viftable), error);
1952     }
1953     crit_exit();
1954 }
1955
1956 /* determine the current time and then
1957  * the elapsed time (between the last time and time now)
1958  * in milliseconds & update the no. of tokens in the bucket
1959  */
1960 static void
1961 tbf_update_tokens(struct vif *vifp)
1962 {
1963     struct timeval tp;
1964     u_long tm;
1965     struct tbf *t = vifp->v_tbf;
1966
1967     crit_enter();
1968
1969     GET_TIME(tp);
1970
1971     TV_DELTA(tp, t->tbf_last_pkt_t, tm);
1972
1973     /*
1974      * This formula is actually
1975      * "time in seconds" * "bytes/second".
1976      *
1977      * (tm / 1000000) * (v_rate_limit * 1000 * (1000/1024) / 8)
1978      *
1979      * The (1000/1024) was introduced in add_vif to optimize
1980      * this divide into a shift.
1981      */
1982     t->tbf_n_tok += tm * vifp->v_rate_limit / 1024 / 8;
1983     t->tbf_last_pkt_t = tp;
1984
1985     if (t->tbf_n_tok > MAX_BKT_SIZE)
1986         t->tbf_n_tok = MAX_BKT_SIZE;
1987
1988     crit_exit();
1989 }
1990
1991 static int
1992 priority(struct vif *vifp, struct ip *ip)
1993 {
1994     int prio = 50; /* the lowest priority -- default case */
1995
1996     /* temporary hack; may add general packet classifier some day */
1997
1998     /*
1999      * The UDP port space is divided up into four priority ranges:
2000      * [0, 16384)     : unclassified - lowest priority
2001      * [16384, 32768) : audio - highest priority
2002      * [32768, 49152) : whiteboard - medium priority
2003      * [49152, 65536) : video - low priority
2004      *
2005      * Everything else gets lowest priority.
2006      */
2007     if (ip->ip_p == IPPROTO_UDP) {
2008         struct udphdr *udp = (struct udphdr *)(((char *)ip) + (ip->ip_hl << 2));
2009         switch (ntohs(udp->uh_dport) & 0xc000) {
2010         case 0x4000:
2011             prio = 70;
2012             break;
2013         case 0x8000:
2014             prio = 60;
2015             break;
2016         case 0xc000:
2017             prio = 55;
2018             break;
2019         }
2020     }
2021     return prio;
2022 }
2023
2024 /*
2025  * End of token bucket filter modifications
2026  */
2027
2028 static int
2029 X_ip_rsvp_vif(struct socket *so, struct sockopt *sopt)
2030 {
2031     int error, vifi;
2032
2033     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
2034         return EOPNOTSUPP;
2035
2036     error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
2037     if (error)
2038         return error;
2039
2040     crit_enter();
2041
2042     if (vifi < 0 || vifi >= numvifs) { /* Error if vif is invalid */
2043         crit_exit();
2044         return EADDRNOTAVAIL;
2045     }
2046
2047     if (sopt->sopt_name == IP_RSVP_VIF_ON) {
2048         /* Check if socket is available. */
2049         if (viftable[vifi].v_rsvpd != NULL) {
2050             crit_exit();
2051             return EADDRINUSE;
2052         }
2053
2054         viftable[vifi].v_rsvpd = so;
2055         /* This may seem silly, but we need to be sure we don't over-increment
2056          * the RSVP counter, in case something slips up.
2057          */
2058         if (!viftable[vifi].v_rsvp_on) {
2059             viftable[vifi].v_rsvp_on = 1;
2060             rsvp_on++;
2061         }
2062     } else { /* must be VIF_OFF */
2063         /*
2064          * XXX as an additional consistency check, one could make sure
2065          * that viftable[vifi].v_rsvpd == so, otherwise passing so as
2066          * first parameter is pretty useless.
2067          */
2068         viftable[vifi].v_rsvpd = NULL;
2069         /*
2070          * This may seem silly, but we need to be sure we don't over-decrement
2071          * the RSVP counter, in case something slips up.
2072          */
2073         if (viftable[vifi].v_rsvp_on) {
2074             viftable[vifi].v_rsvp_on = 0;
2075             rsvp_on--;
2076         }
2077     }
2078     crit_exit();
2079     return 0;
2080 }
2081
2082 static void
2083 X_ip_rsvp_force_done(struct socket *so)
2084 {
2085     int vifi;
2086
2087     /* Don't bother if it is not the right type of socket. */
2088     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
2089         return;
2090
2091     crit_enter();
2092
2093     /* The socket may be attached to more than one vif...this
2094      * is perfectly legal.
2095      */
2096     for (vifi = 0; vifi < numvifs; vifi++) {
2097         if (viftable[vifi].v_rsvpd == so) {
2098             viftable[vifi].v_rsvpd = NULL;
2099             /* This may seem silly, but we need to be sure we don't
2100              * over-decrement the RSVP counter, in case something slips up.
2101              */
2102             if (viftable[vifi].v_rsvp_on) {
2103                 viftable[vifi].v_rsvp_on = 0;
2104                 rsvp_on--;
2105             }
2106         }
2107     }
2108
2109     crit_exit();
2110 }
2111
2112 static void
2113 X_rsvp_input(struct mbuf *m, ...)
2114 {
2115     int vifi;
2116     struct ip *ip = mtod(m, struct ip *);
2117     struct sockaddr_in rsvp_src = { sizeof rsvp_src, AF_INET };
2118     struct ifnet *ifp;
2119     int off, proto;
2120 #ifdef ALTQ
2121     /* support IP_RECVIF used by rsvpd rel4.2a1 */
2122     struct inpcb *inp;
2123     struct socket *so;
2124     struct mbuf *opts;
2125 #endif
2126     __va_list ap;
2127
2128     __va_start(ap, m);
2129     off = __va_arg(ap, int);
2130     proto = __va_arg(ap, int);
2131     __va_end(ap);
2132
2133     if (rsvpdebug)
2134         printf("rsvp_input: rsvp_on %d\n",rsvp_on);
2135
2136     /* Can still get packets with rsvp_on = 0 if there is a local member
2137      * of the group to which the RSVP packet is addressed.  But in this
2138      * case we want to throw the packet away.
2139      */
2140     if (!rsvp_on) {
2141         m_freem(m);
2142         return;
2143     }
2144
2145     crit_enter();
2146
2147     if (rsvpdebug)
2148         printf("rsvp_input: check vifs\n");
2149
2150 #ifdef DIAGNOSTIC
2151     if (!(m->m_flags & M_PKTHDR))
2152         panic("rsvp_input no hdr");
2153 #endif
2154
2155     ifp = m->m_pkthdr.rcvif;
2156     /* Find which vif the packet arrived on. */
2157     for (vifi = 0; vifi < numvifs; vifi++)
2158         if (viftable[vifi].v_ifp == ifp)
2159             break;
2160
2161 #ifdef ALTQ
2162     if (vifi == numvifs || (so = viftable[vifi].v_rsvpd) == NULL) {
2163 #else
2164     if (vifi == numvifs || viftable[vifi].v_rsvpd == NULL) {
2165 #endif
2166         /*
2167          * If the old-style non-vif-associated socket is set,
2168          * then use it.  Otherwise, drop packet since there
2169          * is no specific socket for this vif.
2170          */
2171         if (ip_rsvpd != NULL) {
2172             if (rsvpdebug)
2173                 printf("rsvp_input: Sending packet up old-style socket\n");
2174             rip_input(m, off, proto);  /* xxx */
2175         } else {
2176             if (rsvpdebug && vifi == numvifs)
2177                 printf("rsvp_input: Can't find vif for packet.\n");
2178             else if (rsvpdebug && viftable[vifi].v_rsvpd == NULL)
2179                 printf("rsvp_input: No socket defined for vif %d\n",vifi);
2180             m_freem(m);
2181         }
2182         crit_exit();
2183         return;
2184     }
2185     rsvp_src.sin_addr = ip->ip_src;
2186
2187     if (rsvpdebug && m)
2188         printf("rsvp_input: m->m_len = %d, sbspace() = %ld\n",
2189                m->m_len,sbspace(&(viftable[vifi].v_rsvpd->so_rcv)));
2190
2191 #ifdef ALTQ
2192     opts = NULL;
2193     inp = (struct inpcb *)so->so_pcb;
2194     if (inp->inp_flags & INP_CONTROLOPTS ||
2195         inp->inp_socket->so_options & SO_TIMESTAMP)
2196         ip_savecontrol(inp, &opts, ip, m);
2197     if (sbappendaddr(&so->so_rcv,
2198                      (struct sockaddr *)&rsvp_src,m, opts) == 0) {
2199         m_freem(m);
2200         if (opts)
2201             m_freem(opts);
2202         if (rsvpdebug)
2203             printf("rsvp_input: Failed to append to socket\n");
2204     }
2205     else {
2206         sorwakeup(so);
2207         if (rsvpdebug)
2208             printf("rsvp_input: send packet up\n");
2209     }
2210 #else /* !ALTQ */
2211     if (socket_send(viftable[vifi].v_rsvpd, m, &rsvp_src) < 0) {
2212         if (rsvpdebug)
2213             printf("rsvp_input: Failed to append to socket\n");
2214     } else {
2215         if (rsvpdebug)
2216             printf("rsvp_input: send packet up\n");
2217     }
2218 #endif /* !ALTQ */
2219
2220     crit_exit();
2221 }
2222
2223 /*
2224  * Code for bandwidth monitors
2225  */
2226
2227 /*
2228  * Define common interface for timeval-related methods
2229  */
2230 #define BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
2231 #define BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
2232 #define BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
2233
2234 static uint32_t
2235 compute_bw_meter_flags(struct bw_upcall *req)
2236 {
2237     uint32_t flags = 0;
2238
2239     if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
2240         flags |= BW_METER_UNIT_PACKETS;
2241     if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
2242         flags |= BW_METER_UNIT_BYTES;
2243     if (req->bu_flags & BW_UPCALL_GEQ)
2244         flags |= BW_METER_GEQ;
2245     if (req->bu_flags & BW_UPCALL_LEQ)
2246         flags |= BW_METER_LEQ;
2247     
2248     return flags;
2249 }
2250  
2251 /*
2252  * Add a bw_meter entry
2253  */
2254 static int
2255 add_bw_upcall(struct bw_upcall *req)
2256 {
2257     struct mfc *mfc;
2258     struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
2259                 BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
2260     struct timeval now;
2261     struct bw_meter *x;
2262     uint32_t flags;
2263     
2264     if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2265         return EOPNOTSUPP;
2266     
2267     /* Test if the flags are valid */
2268     if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
2269         return EINVAL;
2270     if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
2271         return EINVAL;
2272     if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2273             == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2274         return EINVAL;
2275     
2276     /* Test if the threshold time interval is valid */
2277     if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
2278         return EINVAL;
2279     
2280     flags = compute_bw_meter_flags(req);
2281
2282     /*
2283      * Find if we have already same bw_meter entry
2284      */
2285     crit_enter();
2286     mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2287     if (mfc == NULL) {
2288         crit_exit();
2289         return EADDRNOTAVAIL;
2290     }
2291     for (x = mfc->mfc_bw_meter; x != NULL; x = x->bm_mfc_next) {
2292         if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2293                            &req->bu_threshold.b_time, ==)) &&
2294             (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2295             (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2296             (x->bm_flags & BW_METER_USER_FLAGS) == flags)  {
2297             crit_exit();
2298             return 0;           /* XXX Already installed */
2299         }
2300     }
2301     crit_exit();
2302     
2303     /* Allocate the new bw_meter entry */
2304     x = malloc(sizeof(*x), M_BWMETER, M_INTWAIT);
2305     
2306     /* Set the new bw_meter entry */
2307     x->bm_threshold.b_time = req->bu_threshold.b_time;
2308     GET_TIME(now);
2309     x->bm_start_time = now;
2310     x->bm_threshold.b_packets = req->bu_threshold.b_packets;
2311     x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
2312     x->bm_measured.b_packets = 0;
2313     x->bm_measured.b_bytes = 0;
2314     x->bm_flags = flags;
2315     x->bm_time_next = NULL;
2316     x->bm_time_hash = BW_METER_BUCKETS;
2317     
2318     /* Add the new bw_meter entry to the front of entries for this MFC */
2319     crit_enter();
2320     x->bm_mfc = mfc;
2321     x->bm_mfc_next = mfc->mfc_bw_meter;
2322     mfc->mfc_bw_meter = x;
2323     schedule_bw_meter(x, &now);
2324     crit_exit();
2325     
2326     return 0;
2327 }
2328
2329 static void
2330 free_bw_list(struct bw_meter *list)
2331 {
2332     while (list != NULL) {
2333         struct bw_meter *x = list;
2334
2335         list = list->bm_mfc_next;
2336         unschedule_bw_meter(x);
2337         free(x, M_BWMETER);
2338     }
2339 }
2340
2341 /*
2342  * Delete one or multiple bw_meter entries
2343  */
2344 static int
2345 del_bw_upcall(struct bw_upcall *req)
2346 {
2347     struct mfc *mfc;
2348     struct bw_meter *x;
2349     
2350     if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2351         return EOPNOTSUPP;
2352     
2353     crit_enter();
2354     /* Find the corresponding MFC entry */
2355     mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2356     if (mfc == NULL) {
2357         crit_exit();
2358         return EADDRNOTAVAIL;
2359     } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2360         /*
2361          * Delete all bw_meter entries for this mfc
2362          */
2363         struct bw_meter *list;
2364         
2365         list = mfc->mfc_bw_meter;
2366         mfc->mfc_bw_meter = NULL;
2367         crit_exit();
2368         free_bw_list(list);
2369         return 0;
2370     } else {                    /* Delete a single bw_meter entry */
2371         struct bw_meter *prev;
2372         uint32_t flags = 0;
2373
2374         flags = compute_bw_meter_flags(req);
2375
2376         /* Find the bw_meter entry to delete */
2377         for (prev = NULL, x = mfc->mfc_bw_meter; x != NULL;
2378              prev = x, x = x->bm_mfc_next) {
2379             if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2380                                &req->bu_threshold.b_time, ==)) &&
2381                 (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2382                 (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2383                 (x->bm_flags & BW_METER_USER_FLAGS) == flags)
2384                 break;
2385         }
2386         if (x != NULL) { /* Delete entry from the list for this MFC */
2387             if (prev != NULL)
2388                 prev->bm_mfc_next = x->bm_mfc_next;     /* remove from middle*/
2389             else
2390                 x->bm_mfc->mfc_bw_meter = x->bm_mfc_next;/* new head of list */
2391             crit_exit();
2392
2393             unschedule_bw_meter(x);
2394             /* Free the bw_meter entry */
2395             free(x, M_BWMETER);
2396             return 0;
2397         } else {
2398             crit_exit();
2399             return EINVAL;
2400         }
2401     }
2402     /* NOTREACHED */
2403 }
2404
2405 /*
2406  * Perform bandwidth measurement processing that may result in an upcall
2407  */
2408 static void
2409 bw_meter_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2410 {
2411     struct timeval delta;
2412     
2413     crit_enter();
2414     delta = *nowp;
2415     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2416     
2417     if (x->bm_flags & BW_METER_GEQ) {
2418         /*
2419          * Processing for ">=" type of bw_meter entry
2420          */
2421         if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2422             /* Reset the bw_meter entry */
2423             x->bm_start_time = *nowp;
2424             x->bm_measured.b_packets = 0;
2425             x->bm_measured.b_bytes = 0;
2426             x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2427         }
2428         
2429         /* Record that a packet is received */
2430         x->bm_measured.b_packets++;
2431         x->bm_measured.b_bytes += plen;
2432         
2433         /*
2434          * Test if we should deliver an upcall
2435          */
2436         if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {       
2437             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2438                  (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2439                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2440                  (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2441                 /* Prepare an upcall for delivery */
2442                 bw_meter_prepare_upcall(x, nowp);
2443                 x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2444             }
2445         }
2446     } else if (x->bm_flags & BW_METER_LEQ) {
2447         /*
2448          * Processing for "<=" type of bw_meter entry
2449          */
2450         if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2451             /*
2452              * We are behind time with the multicast forwarding table
2453              * scanning for "<=" type of bw_meter entries, so test now
2454              * if we should deliver an upcall.
2455              */
2456             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2457                  (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2458                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2459                  (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2460                 /* Prepare an upcall for delivery */
2461                 bw_meter_prepare_upcall(x, nowp);
2462             }
2463             /* Reschedule the bw_meter entry */
2464             unschedule_bw_meter(x);
2465             schedule_bw_meter(x, nowp);
2466         }
2467         
2468         /* Record that a packet is received */
2469         x->bm_measured.b_packets++;
2470         x->bm_measured.b_bytes += plen;
2471         
2472         /*
2473          * Test if we should restart the measuring interval
2474          */
2475         if ((x->bm_flags & BW_METER_UNIT_PACKETS &&
2476              x->bm_measured.b_packets <= x->bm_threshold.b_packets) ||
2477             (x->bm_flags & BW_METER_UNIT_BYTES &&
2478              x->bm_measured.b_bytes <= x->bm_threshold.b_bytes)) {
2479             /* Don't restart the measuring interval */
2480         } else {
2481             /* Do restart the measuring interval */
2482             /*
2483              * XXX: note that we don't unschedule and schedule, because this
2484              * might be too much overhead per packet. Instead, when we process
2485              * all entries for a given timer hash bin, we check whether it is
2486              * really a timeout. If not, we reschedule at that time.
2487              */
2488             x->bm_start_time = *nowp;
2489             x->bm_measured.b_packets = 0;
2490             x->bm_measured.b_bytes = 0;
2491             x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2492         }
2493     }
2494     crit_exit();
2495 }
2496
2497 /*
2498  * Prepare a bandwidth-related upcall
2499  */
2500 static void
2501 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2502 {
2503     struct timeval delta;
2504     struct bw_upcall *u;
2505     
2506     crit_enter();
2507     
2508     /*
2509      * Compute the measured time interval 
2510      */
2511     delta = *nowp;
2512     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2513     
2514     /*
2515      * If there are too many pending upcalls, deliver them now
2516      */
2517     if (bw_upcalls_n >= BW_UPCALLS_MAX)
2518         bw_upcalls_send();
2519     
2520     /*
2521      * Set the bw_upcall entry
2522      */
2523     u = &bw_upcalls[bw_upcalls_n++];
2524     u->bu_src = x->bm_mfc->mfc_origin;
2525     u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2526     u->bu_threshold.b_time = x->bm_threshold.b_time;
2527     u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2528     u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2529     u->bu_measured.b_time = delta;
2530     u->bu_measured.b_packets = x->bm_measured.b_packets;
2531     u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2532     u->bu_flags = 0;
2533     if (x->bm_flags & BW_METER_UNIT_PACKETS)
2534         u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2535     if (x->bm_flags & BW_METER_UNIT_BYTES)
2536         u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2537     if (x->bm_flags & BW_METER_GEQ)
2538         u->bu_flags |= BW_UPCALL_GEQ;
2539     if (x->bm_flags & BW_METER_LEQ)
2540         u->bu_flags |= BW_UPCALL_LEQ;
2541     
2542     crit_exit();
2543 }
2544
2545 /*
2546  * Send the pending bandwidth-related upcalls
2547  */
2548 static void
2549 bw_upcalls_send(void)
2550 {
2551     struct mbuf *m;
2552     int len = bw_upcalls_n * sizeof(bw_upcalls[0]);
2553     struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2554     static struct igmpmsg igmpmsg = { 0,                /* unused1 */
2555                                       0,                /* unused2 */
2556                                       IGMPMSG_BW_UPCALL,/* im_msgtype */
2557                                       0,                /* im_mbz  */
2558                                       0,                /* im_vif  */
2559                                       0,                /* unused3 */
2560                                       { 0 },            /* im_src  */
2561                                       { 0 } };          /* im_dst  */
2562     
2563     if (bw_upcalls_n == 0)
2564         return;                 /* No pending upcalls */
2565
2566     bw_upcalls_n = 0;
2567     
2568     /*
2569      * Allocate a new mbuf, initialize it with the header and
2570      * the payload for the pending calls.
2571      */
2572     MGETHDR(m, MB_DONTWAIT, MT_HEADER);
2573     if (m == NULL) {
2574         log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2575         return;
2576     }
2577     
2578     m->m_len = m->m_pkthdr.len = 0;
2579     m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2580     m_copyback(m, sizeof(struct igmpmsg), len, (caddr_t)&bw_upcalls[0]);
2581     
2582     /*
2583      * Send the upcalls
2584      * XXX do we need to set the address in k_igmpsrc ?
2585      */
2586     mrtstat.mrts_upcalls++;
2587     if (socket_send(ip_mrouter, m, &k_igmpsrc) < 0) {
2588         log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2589         ++mrtstat.mrts_upq_sockfull;
2590     }
2591 }
2592
2593 /*
2594  * Compute the timeout hash value for the bw_meter entries
2595  */
2596 #define BW_METER_TIMEHASH(bw_meter, hash)                               \
2597     do {                                                                \
2598         struct timeval next_timeval = (bw_meter)->bm_start_time;        \
2599                                                                         \
2600         BW_TIMEVALADD(&next_timeval, &(bw_meter)->bm_threshold.b_time); \
2601         (hash) = next_timeval.tv_sec;                                   \
2602         if (next_timeval.tv_usec)                                       \
2603             (hash)++; /* XXX: make sure we don't timeout early */       \
2604         (hash) %= BW_METER_BUCKETS;                                     \
2605     } while (0)
2606
2607 /*
2608  * Schedule a timer to process periodically bw_meter entry of type "<="
2609  * by linking the entry in the proper hash bucket.
2610  */
2611 static void
2612 schedule_bw_meter(struct bw_meter *x, struct timeval *nowp)
2613 {
2614     int time_hash;
2615     
2616     if (!(x->bm_flags & BW_METER_LEQ))
2617         return;         /* XXX: we schedule timers only for "<=" entries */
2618     
2619     /*
2620      * Reset the bw_meter entry
2621      */
2622     crit_enter();
2623     x->bm_start_time = *nowp;
2624     x->bm_measured.b_packets = 0;
2625     x->bm_measured.b_bytes = 0;
2626     x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2627     crit_exit();
2628     
2629     /*
2630      * Compute the timeout hash value and insert the entry
2631      */
2632     BW_METER_TIMEHASH(x, time_hash);
2633     x->bm_time_next = bw_meter_timers[time_hash];
2634     bw_meter_timers[time_hash] = x;
2635     x->bm_time_hash = time_hash;
2636 }
2637
2638 /*
2639  * Unschedule the periodic timer that processes bw_meter entry of type "<="
2640  * by removing the entry from the proper hash bucket.
2641  */
2642 static void
2643 unschedule_bw_meter(struct bw_meter *x)
2644 {
2645     int time_hash;
2646     struct bw_meter *prev, *tmp;
2647     
2648     if (!(x->bm_flags & BW_METER_LEQ))
2649         return;         /* XXX: we schedule timers only for "<=" entries */
2650     
2651     /*
2652      * Compute the timeout hash value and delete the entry
2653      */
2654     time_hash = x->bm_time_hash;
2655     if (time_hash >= BW_METER_BUCKETS)
2656         return;         /* Entry was not scheduled */
2657     
2658     for (prev = NULL, tmp = bw_meter_timers[time_hash];
2659              tmp != NULL; prev = tmp, tmp = tmp->bm_time_next)
2660         if (tmp == x)
2661             break;
2662     
2663     if (tmp == NULL)
2664         panic("unschedule_bw_meter: bw_meter entry not found");
2665     
2666     if (prev != NULL)
2667         prev->bm_time_next = x->bm_time_next;
2668     else
2669         bw_meter_timers[time_hash] = x->bm_time_next;
2670     
2671     x->bm_time_next = NULL;
2672     x->bm_time_hash = BW_METER_BUCKETS;
2673 }
2674
2675
2676 /*
2677  * Process all "<=" type of bw_meter that should be processed now,
2678  * and for each entry prepare an upcall if necessary. Each processed
2679  * entry is rescheduled again for the (periodic) processing.
2680  *
2681  * This is run periodically (once per second normally). On each round,
2682  * all the potentially matching entries are in the hash slot that we are
2683  * looking at.
2684  */
2685 static void
2686 bw_meter_process()
2687 {
2688     static uint32_t last_tv_sec;        /* last time we processed this */
2689
2690     uint32_t loops;
2691     int i;
2692     struct timeval now, process_endtime;
2693     
2694     GET_TIME(now);
2695     if (last_tv_sec == now.tv_sec)
2696         return;         /* nothing to do */
2697
2698     crit_enter();
2699     loops = now.tv_sec - last_tv_sec;
2700     last_tv_sec = now.tv_sec;
2701     if (loops > BW_METER_BUCKETS)
2702         loops = BW_METER_BUCKETS;
2703
2704     /*
2705      * Process all bins of bw_meter entries from the one after the last
2706      * processed to the current one. On entry, i points to the last bucket
2707      * visited, so we need to increment i at the beginning of the loop.
2708      */
2709     for (i = (now.tv_sec - loops) % BW_METER_BUCKETS; loops > 0; loops--) {
2710         struct bw_meter *x, *tmp_list;
2711         
2712         if (++i >= BW_METER_BUCKETS)
2713             i = 0;
2714         
2715         /* Disconnect the list of bw_meter entries from the bin */
2716         tmp_list = bw_meter_timers[i];
2717         bw_meter_timers[i] = NULL;
2718         
2719         /* Process the list of bw_meter entries */
2720         while (tmp_list != NULL) {
2721             x = tmp_list;
2722             tmp_list = tmp_list->bm_time_next;
2723             
2724             /* Test if the time interval is over */
2725             process_endtime = x->bm_start_time;
2726             BW_TIMEVALADD(&process_endtime, &x->bm_threshold.b_time);
2727             if (BW_TIMEVALCMP(&process_endtime, &now, >)) {
2728                 /* Not yet: reschedule, but don't reset */
2729                 int time_hash;
2730                 
2731                 BW_METER_TIMEHASH(x, time_hash);
2732                 if (time_hash == i && process_endtime.tv_sec == now.tv_sec) {
2733                     /*
2734                      * XXX: somehow the bin processing is a bit ahead of time.
2735                      * Put the entry in the next bin.
2736                      */
2737                     if (++time_hash >= BW_METER_BUCKETS)
2738                         time_hash = 0;
2739                 }
2740                 x->bm_time_next = bw_meter_timers[time_hash];
2741                 bw_meter_timers[time_hash] = x;
2742                 x->bm_time_hash = time_hash;
2743                 
2744                 continue;
2745             }
2746             
2747             /*
2748              * Test if we should deliver an upcall
2749              */
2750             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2751                  (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2752                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2753                  (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2754                 /* Prepare an upcall for delivery */
2755                 bw_meter_prepare_upcall(x, &now);
2756             }
2757             
2758             /*
2759              * Reschedule for next processing
2760              */
2761             schedule_bw_meter(x, &now);
2762         }
2763     }
2764     crit_exit();
2765     
2766     /* Send all upcalls that are pending delivery */
2767     bw_upcalls_send();
2768 }
2769
2770 /*
2771  * A periodic function for sending all upcalls that are pending delivery
2772  */
2773 static void
2774 expire_bw_upcalls_send(void *unused)
2775 {
2776     bw_upcalls_send();
2777     
2778     callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
2779                   expire_bw_upcalls_send, NULL);
2780 }
2781
2782 /*
2783  * A periodic function for periodic scanning of the multicast forwarding
2784  * table for processing all "<=" bw_meter entries.
2785  */
2786 static void
2787 expire_bw_meter_process(void *unused)
2788 {
2789     if (mrt_api_config & MRT_MFC_BW_UPCALL)
2790         bw_meter_process();
2791     
2792     callout_reset(&bw_meter_ch, BW_METER_PERIOD,
2793                   expire_bw_meter_process, NULL);
2794 }
2795
2796 /*
2797  * End of bandwidth monitoring code
2798  */
2799
2800 #ifdef PIM
2801 /*
2802  * Send the packet up to the user daemon, or eventually do kernel encapsulation
2803  *
2804  */
2805 static int
2806 pim_register_send(struct ip *ip, struct vif *vifp,
2807         struct mbuf *m, struct mfc *rt)
2808 {
2809     struct mbuf *mb_copy, *mm;
2810     
2811     if (mrtdebug & DEBUG_PIM)
2812         log(LOG_DEBUG, "pim_register_send: ");
2813     
2814     mb_copy = pim_register_prepare(ip, m);
2815     if (mb_copy == NULL)
2816         return ENOBUFS;
2817     
2818     /*
2819      * Send all the fragments. Note that the mbuf for each fragment
2820      * is freed by the sending machinery.
2821      */
2822     for (mm = mb_copy; mm; mm = mb_copy) {
2823         mb_copy = mm->m_nextpkt;
2824         mm->m_nextpkt = 0;
2825         mm = m_pullup(mm, sizeof(struct ip));
2826         if (mm != NULL) {
2827             ip = mtod(mm, struct ip *);
2828             if ((mrt_api_config & MRT_MFC_RP) &&
2829                 (rt->mfc_rp.s_addr != INADDR_ANY)) {
2830                 pim_register_send_rp(ip, vifp, mm, rt);
2831             } else {
2832                 pim_register_send_upcall(ip, vifp, mm, rt);
2833             }
2834         }
2835     }
2836     
2837     return 0;
2838 }
2839
2840 /*
2841  * Return a copy of the data packet that is ready for PIM Register
2842  * encapsulation.
2843  * XXX: Note that in the returned copy the IP header is a valid one.
2844  */
2845 static struct mbuf *
2846 pim_register_prepare(struct ip *ip, struct mbuf *m)
2847 {
2848     struct mbuf *mb_copy = NULL;
2849     int mtu;
2850     
2851     /* Take care of delayed checksums */
2852     if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2853         in_delayed_cksum(m);
2854         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2855     }
2856
2857     /*
2858      * Copy the old packet & pullup its IP header into the
2859      * new mbuf so we can modify it.
2860      */
2861     mb_copy = m_copypacket(m, MB_DONTWAIT);
2862     if (mb_copy == NULL)
2863         return NULL;
2864     mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2865     if (mb_copy == NULL)
2866         return NULL;
2867     
2868     /* take care of the TTL */
2869     ip = mtod(mb_copy, struct ip *);
2870     --ip->ip_ttl;
2871     
2872     /* Compute the MTU after the PIM Register encapsulation */
2873     mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2874     
2875     if (ip->ip_len <= mtu) {
2876         /* Turn the IP header into a valid one */
2877         ip->ip_len = htons(ip->ip_len);
2878         ip->ip_off = htons(ip->ip_off);
2879         ip->ip_sum = 0;
2880         ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2881     } else {
2882         /* Fragment the packet */
2883         if (ip_fragment(ip, &mb_copy, mtu, 0, CSUM_DELAY_IP) != 0) {
2884             m_freem(mb_copy);
2885             return NULL;
2886         }
2887     }
2888     return mb_copy;
2889 }
2890
2891 /*
2892  * Send an upcall with the data packet to the user-level process.
2893  */
2894 static int
2895 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2896         struct mbuf *mb_copy, struct mfc *rt)
2897 {
2898     struct mbuf *mb_first;
2899     int len = ntohs(ip->ip_len);
2900     struct igmpmsg *im;
2901     struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2902     
2903     /*
2904      * Add a new mbuf with an upcall header
2905      */
2906     MGETHDR(mb_first, MB_DONTWAIT, MT_HEADER);
2907     if (mb_first == NULL) {
2908         m_freem(mb_copy);
2909         return ENOBUFS;
2910     }
2911     mb_first->m_data += max_linkhdr;
2912     mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2913     mb_first->m_len = sizeof(struct igmpmsg);
2914     mb_first->m_next = mb_copy;
2915     
2916     /* Send message to routing daemon */
2917     im = mtod(mb_first, struct igmpmsg *);
2918     im->im_msgtype      = IGMPMSG_WHOLEPKT;
2919     im->im_mbz          = 0;
2920     im->im_vif          = vifp - viftable;
2921     im->im_src          = ip->ip_src;
2922     im->im_dst          = ip->ip_dst;
2923     
2924     k_igmpsrc.sin_addr  = ip->ip_src;
2925     
2926     mrtstat.mrts_upcalls++;
2927     
2928     if (socket_send(ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2929         if (mrtdebug & DEBUG_PIM)
2930             log(LOG_WARNING,
2931                 "mcast: pim_register_send_upcall: ip_mrouter socket queue full");
2932         ++mrtstat.mrts_upq_sockfull;
2933         return ENOBUFS;
2934     }
2935     
2936     /* Keep statistics */
2937     pimstat.pims_snd_registers_msgs++;
2938     pimstat.pims_snd_registers_bytes += len;
2939     
2940     return 0;
2941 }
2942
2943 /*
2944  * Encapsulate the data packet in PIM Register message and send it to the RP.
2945  */
2946 static int
2947 pim_register_send_rp(struct ip *ip, struct vif *vifp,
2948         struct mbuf *mb_copy, struct mfc *rt)
2949 {
2950     struct mbuf *mb_first;
2951     struct ip *ip_outer;
2952     struct pim_encap_pimhdr *pimhdr;
2953     int len = ntohs(ip->ip_len);
2954     vifi_t vifi = rt->mfc_parent;
2955     
2956     if ((vifi >= numvifs) || (viftable[vifi].v_lcl_addr.s_addr == 0)) {
2957         m_freem(mb_copy);
2958         return EADDRNOTAVAIL;           /* The iif vif is invalid */
2959     }
2960     
2961     /*
2962      * Add a new mbuf with the encapsulating header
2963      */
2964     MGETHDR(mb_first, MB_DONTWAIT, MT_HEADER);
2965     if (mb_first == NULL) {
2966         m_freem(mb_copy);
2967         return ENOBUFS;
2968     }
2969     mb_first->m_data += max_linkhdr;
2970     mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2971     mb_first->m_next = mb_copy;
2972
2973     mb_first->m_pkthdr.len = len + mb_first->m_len;
2974     
2975     /*
2976      * Fill in the encapsulating IP and PIM header
2977      */
2978     ip_outer = mtod(mb_first, struct ip *);
2979     *ip_outer = pim_encap_iphdr;
2980 #ifdef RANDOM_IP_ID
2981     ip_outer->ip_id = ip_randomid();
2982 #else
2983     ip_outer->ip_id = htons(ip_id++);
2984 #endif
2985     ip_outer->ip_len = len + sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2986     ip_outer->ip_src = viftable[vifi].v_lcl_addr;
2987     ip_outer->ip_dst = rt->mfc_rp;
2988     /*
2989      * Copy the inner header TOS to the outer header, and take care of the
2990      * IP_DF bit.
2991      */
2992     ip_outer->ip_tos = ip->ip_tos;
2993     if (ntohs(ip->ip_off) & IP_DF)
2994         ip_outer->ip_off |= IP_DF;
2995     pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2996                                          + sizeof(pim_encap_iphdr));
2997     *pimhdr = pim_encap_pimhdr;
2998     /* If the iif crosses a border, set the Border-bit */
2999     if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & mrt_api_config)
3000         pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
3001     
3002     mb_first->m_data += sizeof(pim_encap_iphdr);
3003     pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
3004     mb_first->m_data -= sizeof(pim_encap_iphdr);
3005     
3006     if (vifp->v_rate_limit == 0)
3007         tbf_send_packet(vifp, mb_first);
3008     else
3009         tbf_control(vifp, mb_first, ip, ip_outer->ip_len);
3010     
3011     /* Keep statistics */
3012     pimstat.pims_snd_registers_msgs++;
3013     pimstat.pims_snd_registers_bytes += len;
3014     
3015     return 0;
3016 }
3017
3018 /*
3019  * PIM-SMv2 and PIM-DM messages processing.
3020  * Receives and verifies the PIM control messages, and passes them
3021  * up to the listening socket, using rip_input().
3022  * The only message with special processing is the PIM_REGISTER message
3023  * (used by PIM-SM): the PIM header is stripped off, and the inner packet
3024  * is passed to if_simloop().
3025  */
3026 void
3027 pim_input(struct mbuf *m, ...)
3028 {
3029     int off, proto;
3030     struct ip *ip = mtod(m, struct ip *);
3031     struct pim *pim;
3032     int minlen;
3033     int datalen = ip->ip_len;
3034     int ip_tos;
3035     int iphlen;
3036     __va_list ap;
3037
3038     __va_start(ap, m);
3039     off = __va_arg(ap, int);
3040     proto = __va_arg(ap, int);
3041     __va_end(ap);
3042
3043     iphlen = off;
3044
3045     /* Keep statistics */
3046     pimstat.pims_rcv_total_msgs++;
3047     pimstat.pims_rcv_total_bytes += datalen;
3048     
3049     /*
3050      * Validate lengths
3051      */
3052     if (datalen < PIM_MINLEN) {
3053         pimstat.pims_rcv_tooshort++;
3054         log(LOG_ERR, "pim_input: packet size too small %d from %lx\n",
3055             datalen, (u_long)ip->ip_src.s_addr);
3056         m_freem(m);
3057         return;
3058     }
3059     
3060     /*
3061      * If the packet is at least as big as a REGISTER, go agead
3062      * and grab the PIM REGISTER header size, to avoid another
3063      * possible m_pullup() later.
3064      * 
3065      * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
3066      * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
3067      */
3068     minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
3069     /*
3070      * Get the IP and PIM headers in contiguous memory, and
3071      * possibly the PIM REGISTER header.
3072      */
3073     if ((m->m_flags & M_EXT || m->m_len < minlen) &&
3074         (m = m_pullup(m, minlen)) == 0) {
3075         log(LOG_ERR, "pim_input: m_pullup failure\n");
3076         return;
3077     }
3078     /* m_pullup() may have given us a new mbuf so reset ip. */
3079     ip = mtod(m, struct ip *);
3080     ip_tos = ip->ip_tos;
3081     
3082     /* adjust mbuf to point to the PIM header */
3083     m->m_data += iphlen;
3084     m->m_len  -= iphlen;
3085     pim = mtod(m, struct pim *);
3086     
3087     /*
3088      * Validate checksum. If PIM REGISTER, exclude the data packet.
3089      *
3090      * XXX: some older PIMv2 implementations don't make this distinction,
3091      * so for compatibility reason perform the checksum over part of the
3092      * message, and if error, then over the whole message.
3093      */
3094     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
3095         /* do nothing, checksum okay */
3096     } else if (in_cksum(m, datalen)) {
3097         pimstat.pims_rcv_badsum++;
3098         if (mrtdebug & DEBUG_PIM)
3099             log(LOG_DEBUG, "pim_input: invalid checksum");
3100         m_freem(m);
3101         return;
3102     }
3103
3104     /* PIM version check */
3105     if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
3106         pimstat.pims_rcv_badversion++;
3107         log(LOG_ERR, "pim_input: incorrect version %d, expecting %d\n",
3108             PIM_VT_V(pim->pim_vt), PIM_VERSION);
3109         m_freem(m);
3110         return;
3111     }
3112     
3113     /* restore mbuf back to the outer IP */
3114     m->m_data -= iphlen;
3115     m->m_len  += iphlen;
3116     
3117     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
3118         /*
3119          * Since this is a REGISTER, we'll make a copy of the register
3120          * headers ip + pim + u_int32 + encap_ip, to be passed up to the
3121          * routing daemon.
3122          */
3123         struct sockaddr_in dst = { sizeof(dst), AF_INET };
3124         struct mbuf *mcp;
3125         struct ip *encap_ip;
3126         u_int32_t *reghdr;
3127         
3128         if ((reg_vif_num >= numvifs) || (reg_vif_num == VIFI_INVALID)) {
3129             if (mrtdebug & DEBUG_PIM)
3130                 log(LOG_DEBUG,
3131                     "pim_input: register vif not set: %d\n", reg_vif_num);
3132             m_freem(m);
3133             return;
3134         }
3135         
3136         /*
3137          * Validate length
3138          */
3139         if (datalen < PIM_REG_MINLEN) {
3140             pimstat.pims_rcv_tooshort++;
3141             pimstat.pims_rcv_badregisters++;
3142             log(LOG_ERR,
3143                 "pim_input: register packet size too small %d from %lx\n",
3144                 datalen, (u_long)ip->ip_src.s_addr);
3145             m_freem(m);
3146             return;
3147         }
3148         
3149         reghdr = (u_int32_t *)(pim + 1);
3150         encap_ip = (struct ip *)(reghdr + 1);
3151         
3152         if (mrtdebug & DEBUG_PIM) {
3153             log(LOG_DEBUG,
3154                 "pim_input[register], encap_ip: %lx -> %lx, encap_ip len %d\n",
3155                 (u_long)ntohl(encap_ip->ip_src.s_addr),
3156                 (u_long)ntohl(encap_ip->ip_dst.s_addr),
3157                 ntohs(encap_ip->ip_len));
3158         }
3159         
3160         /* verify the version number of the inner packet */
3161         if (encap_ip->ip_v != IPVERSION) {
3162             pimstat.pims_rcv_badregisters++;
3163             if (mrtdebug & DEBUG_PIM) {
3164                 log(LOG_DEBUG, "pim_input: invalid IP version (%d) "
3165                     "of the inner packet\n", encap_ip->ip_v);
3166             }
3167             m_freem(m);
3168             return;
3169         }
3170         
3171         /* verify the inner packet is destined to a mcast group */
3172         if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
3173             pimstat.pims_rcv_badregisters++;
3174             if (mrtdebug & DEBUG_PIM)
3175                 log(LOG_DEBUG,
3176                     "pim_input: inner packet of register is not "
3177                     "multicast %lx\n",
3178                     (u_long)ntohl(encap_ip->ip_dst.s_addr));
3179             m_freem(m);
3180             return;
3181         }
3182
3183         /* If a NULL_REGISTER, pass it to the daemon */
3184         if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
3185                 goto pim_input_to_daemon;
3186
3187         /*
3188          * Copy the TOS from the outer IP header to the inner IP header.
3189          */
3190         if (encap_ip->ip_tos != ip_tos) {
3191             /* Outer TOS -> inner TOS */
3192             encap_ip->ip_tos = ip_tos;
3193             /* Recompute the inner header checksum. Sigh... */
3194             
3195             /* adjust mbuf to point to the inner IP header */
3196             m->m_data += (iphlen + PIM_MINLEN);
3197             m->m_len  -= (iphlen + PIM_MINLEN);
3198             
3199             encap_ip->ip_sum = 0;
3200             encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
3201             
3202             /* restore mbuf to point back to the outer IP header */
3203             m->m_data -= (iphlen + PIM_MINLEN);
3204             m->m_len  += (iphlen + PIM_MINLEN);
3205         }
3206
3207         /*
3208          * Decapsulate the inner IP packet and loopback to forward it
3209          * as a normal multicast packet. Also, make a copy of the 
3210          *     outer_iphdr + pimhdr + reghdr + encap_iphdr
3211          * to pass to the daemon later, so it can take the appropriate
3212          * actions (e.g., send back PIM_REGISTER_STOP).
3213          * XXX: here m->m_data points to the outer IP header.
3214          */
3215         mcp = m_copy(m, 0, iphlen + PIM_REG_MINLEN);
3216         if (mcp == NULL) {
3217             log(LOG_ERR,
3218                 "pim_input: pim register: could not copy register head\n");
3219             m_freem(m);
3220             return;
3221         }
3222         
3223         /* Keep statistics */
3224         /* XXX: registers_bytes include only the encap. mcast pkt */
3225         pimstat.pims_rcv_registers_msgs++;
3226         pimstat.pims_rcv_registers_bytes += ntohs(encap_ip->ip_len);
3227         
3228         /*
3229          * forward the inner ip packet; point m_data at the inner ip.
3230          */
3231         m_adj(m, iphlen + PIM_MINLEN);
3232         
3233         if (mrtdebug & DEBUG_PIM) {
3234             log(LOG_DEBUG,
3235                 "pim_input: forwarding decapsulated register: "
3236                 "src %lx, dst %lx, vif %d\n",
3237                 (u_long)ntohl(encap_ip->ip_src.s_addr),
3238                 (u_long)ntohl(encap_ip->ip_dst.s_addr),
3239                 reg_vif_num);
3240         }
3241         if_simloop(viftable[reg_vif_num].v_ifp, m, dst.sin_family, 0);
3242         
3243         /* prepare the register head to send to the mrouting daemon */
3244         m = mcp;
3245     }
3246
3247 pim_input_to_daemon:    
3248     /*
3249      * Pass the PIM message up to the daemon; if it is a Register message,
3250      * pass the 'head' only up to the daemon. This includes the
3251      * outer IP header, PIM header, PIM-Register header and the
3252      * inner IP header.
3253      * XXX: the outer IP header pkt size of a Register is not adjust to
3254      * reflect the fact that the inner multicast data is truncated.
3255      */
3256     rip_input(m, iphlen, proto);
3257
3258     return;
3259 }
3260 #endif /* PIM */
3261
3262 static int
3263 ip_mroute_modevent(module_t mod, int type, void *unused)
3264 {
3265     switch (type) {
3266     case MOD_LOAD:
3267         crit_enter();
3268         /* XXX Protect against multiple loading */
3269         ip_mcast_src = X_ip_mcast_src;
3270         ip_mforward = X_ip_mforward;
3271         ip_mrouter_done = X_ip_mrouter_done;
3272         ip_mrouter_get = X_ip_mrouter_get;
3273         ip_mrouter_set = X_ip_mrouter_set;
3274         ip_rsvp_force_done = X_ip_rsvp_force_done;
3275         ip_rsvp_vif = X_ip_rsvp_vif;
3276         ipip_input = X_ipip_input;
3277         legal_vif_num = X_legal_vif_num;
3278         mrt_ioctl = X_mrt_ioctl;
3279         rsvp_input_p = X_rsvp_input;
3280         crit_exit();
3281         break;
3282
3283     case MOD_UNLOAD:
3284         if (ip_mrouter)
3285             return EINVAL;
3286
3287         crit_enter();
3288         ip_mcast_src = NULL;
3289         ip_mforward = NULL;
3290         ip_mrouter_done = NULL;
3291         ip_mrouter_get = NULL;
3292         ip_mrouter_set = NULL;
3293         ip_rsvp_force_done = NULL;
3294         ip_rsvp_vif = NULL;
3295         ipip_input = NULL;
3296         legal_vif_num = NULL;
3297         mrt_ioctl = NULL;
3298         rsvp_input_p = NULL;
3299         crit_exit();
3300         break;
3301     }
3302     return 0;
3303 }
3304
3305 static moduledata_t ip_mroutemod = {
3306     "ip_mroute",
3307     ip_mroute_modevent,
3308     0
3309 };
3310 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PSEUDO, SI_ORDER_ANY);