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