Initial import from FreeBSD RELENG_4:
[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  *
11  * MROUTING Revision: 3.5
12  * $FreeBSD: src/sys/netinet/ip_mroute.c,v 1.56.2.7 2003/01/23 21:06:45 sam Exp $
13  */
14
15 #include "opt_mrouting.h"
16 #include "opt_random_ip_id.h"
17
18 #include <sys/param.h>
19 #include <sys/kernel.h>
20 #include <sys/malloc.h>
21 #include <sys/mbuf.h>
22 #include <sys/protosw.h>
23 #include <sys/socket.h>
24 #include <sys/socketvar.h>
25 #include <sys/sockio.h>
26 #include <sys/sysctl.h>
27 #include <sys/syslog.h>
28 #include <sys/systm.h>
29 #include <sys/time.h>
30 #include <net/if.h>
31 #include <net/route.h>
32 #include <netinet/in.h>
33 #include <netinet/igmp.h>
34 #include <netinet/in_systm.h>
35 #include <netinet/in_var.h>
36 #include <netinet/ip.h>
37 #include <netinet/ip_mroute.h>
38 #include <netinet/ip_var.h>
39 #include <netinet/udp.h>
40 #include <machine/in_cksum.h>
41
42 /*
43  * Control debugging code for rsvp and multicast routing code.
44  * Can only set them with the debugger.
45  */
46 static  u_int   rsvpdebug;              /* non-zero enables debugging   */
47
48 static  u_int   mrtdebug;               /* any set of the flags below   */
49  
50 #define         DEBUG_MFC       0x02
51 #define         DEBUG_FORWARD   0x04
52 #define         DEBUG_EXPIRE    0x08
53 #define         DEBUG_XMIT      0x10
54
55 #define M_HASCL(m)      ((m)->m_flags & M_EXT)
56
57 static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast routing tables");
58
59 static struct mrtstat   mrtstat;
60 SYSCTL_STRUCT(_net_inet_ip, OID_AUTO, mrtstat, CTLFLAG_RW,
61     &mrtstat, mrtstat,
62     "Multicast Routing Statistics (struct mrtstat, netinet/ip_mroute.h)");
63
64 static struct mfc       *mfctable[MFCTBLSIZ];
65 static u_char           nexpire[MFCTBLSIZ];
66 static struct vif       viftable[MAXVIFS];
67
68 static struct callout_handle expire_upcalls_ch;
69
70 #define         EXPIRE_TIMEOUT  (hz / 4)        /* 4x / second          */
71 #define         UPCALL_EXPIRE   6               /* number of timeouts   */
72
73 /*
74  * Define the token bucket filter structures
75  * tbftable -> each vif has one of these for storing info
76  */
77
78 static struct tbf tbftable[MAXVIFS];
79 #define         TBF_REPROCESS   (hz / 100)      /* 100x / second */
80
81 /*
82  * 'Interfaces' associated with decapsulator (so we can tell
83  * packets that went through it from ones that get reflected
84  * by a broken gateway).  These interfaces are never linked into
85  * the system ifnet list & no routes point to them.  I.e., packets
86  * can't be sent this way.  They only exist as a placeholder for
87  * multicast source verification.
88  */
89 static struct ifnet multicast_decap_if[MAXVIFS];
90
91 #define ENCAP_TTL 64
92 #define ENCAP_PROTO IPPROTO_IPIP        /* 4 */
93
94 /* prototype IP hdr for encapsulated packets */
95 static struct ip multicast_encap_iphdr = {
96 #if BYTE_ORDER == LITTLE_ENDIAN
97         sizeof(struct ip) >> 2, IPVERSION,
98 #else
99         IPVERSION, sizeof(struct ip) >> 2,
100 #endif
101         0,                              /* tos */
102         sizeof(struct ip),              /* total length */
103         0,                              /* id */
104         0,                              /* frag offset */
105         ENCAP_TTL, ENCAP_PROTO,
106         0,                              /* checksum */
107 };
108
109 /*
110  * Private variables.
111  */
112 static vifi_t      numvifs;
113 static int have_encap_tunnel;
114
115 /*
116  * one-back cache used by ipip_input to locate a tunnel's vif
117  * given a datagram's src ip address.
118  */
119 static u_long last_encap_src;
120 static struct vif *last_encap_vif;
121
122 static u_long   X_ip_mcast_src(int vifi);
123 static int      X_ip_mforward(struct ip *ip, struct ifnet *ifp,
124                         struct mbuf *m, struct ip_moptions *imo);
125 static int      X_ip_mrouter_done(void);
126 static int      X_ip_mrouter_get(struct socket *so, struct sockopt *m);
127 static int      X_ip_mrouter_set(struct socket *so, struct sockopt *m);
128 static int      X_legal_vif_num(int vif);
129 static int      X_mrt_ioctl(int cmd, caddr_t data);
130
131 static int get_sg_cnt(struct sioc_sg_req *);
132 static int get_vif_cnt(struct sioc_vif_req *);
133 static int ip_mrouter_init(struct socket *, int);
134 static int add_vif(struct vifctl *);
135 static int del_vif(vifi_t);
136 static int add_mfc(struct mfcctl *);
137 static int del_mfc(struct mfcctl *);
138 static int socket_send(struct socket *, struct mbuf *, struct sockaddr_in *);
139 static int set_assert(int);
140 static void expire_upcalls(void *);
141 static int ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
142 static void phyint_send(struct ip *, struct vif *, struct mbuf *);
143 static void encap_send(struct ip *, struct vif *, struct mbuf *);
144 static void tbf_control(struct vif *, struct mbuf *, struct ip *, u_long);
145 static void tbf_queue(struct vif *, struct mbuf *);
146 static void tbf_process_q(struct vif *);
147 static void tbf_reprocess_q(void *);
148 static int tbf_dq_sel(struct vif *, struct ip *);
149 static void tbf_send_packet(struct vif *, struct mbuf *);
150 static void tbf_update_tokens(struct vif *);
151 static int priority(struct vif *, struct ip *);
152
153 /*
154  * whether or not special PIM assert processing is enabled.
155  */
156 static int pim_assert;
157 /*
158  * Rate limit for assert notification messages, in usec
159  */
160 #define ASSERT_MSG_TIME         3000000
161
162 /*
163  * Hash function for a source, group entry
164  */
165 #define MFCHASH(a, g) MFCHASHMOD(((a) >> 20) ^ ((a) >> 10) ^ (a) ^ \
166                         ((g) >> 20) ^ ((g) >> 10) ^ (g))
167
168 /*
169  * Find a route for a given origin IP address and Multicast group address
170  * Type of service parameter to be added in the future!!!
171  * Statistics are updated by the caller if needed
172  * (mrtstat.mrts_mfc_lookups and mrtstat.mrts_mfc_misses)
173  */
174 static struct mfc *
175 mfc_find(in_addr_t o, in_addr_t g)
176 {
177     struct mfc *rt;
178
179     for (rt = mfctable[MFCHASH(o,g)]; rt; rt = rt->mfc_next)
180         if ((rt->mfc_origin.s_addr == o) &&
181                 (rt->mfc_mcastgrp.s_addr == g) && (rt->mfc_stall == NULL))
182             break;
183     return rt;
184 }
185
186 /*
187  * Macros to compute elapsed time efficiently
188  * Borrowed from Van Jacobson's scheduling code
189  */
190 #define TV_DELTA(a, b, delta) {                                 \
191         int xxs;                                                \
192         delta = (a).tv_usec - (b).tv_usec;                      \
193         if ((xxs = (a).tv_sec - (b).tv_sec)) {                  \
194                 switch (xxs) {                                  \
195                 case 2:                                         \
196                         delta += 1000000;                       \
197                         /* FALLTHROUGH */                       \
198                 case 1:                                         \
199                         delta += 1000000;                       \
200                         break;                                  \
201                 default:                                        \
202                         delta += (1000000 * xxs);               \
203                 }                                               \
204         }                                                       \
205 }
206
207 #define TV_LT(a, b) (((a).tv_usec < (b).tv_usec && \
208               (a).tv_sec <= (b).tv_sec) || (a).tv_sec < (b).tv_sec)
209
210 /*
211  * Handle MRT setsockopt commands to modify the multicast routing tables.
212  */
213 static int
214 X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
215 {
216     int error, optval;
217     vifi_t      vifi;
218     struct      vifctl vifc;
219     struct      mfcctl mfc;
220
221     if (so != ip_mrouter && sopt->sopt_name != MRT_INIT)
222         return EPERM;
223
224     error = 0;
225     switch (sopt->sopt_name) {
226     case MRT_INIT:
227         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
228         if (error)
229             break;
230         error = ip_mrouter_init(so, optval);
231         break;
232
233     case MRT_DONE:
234         error = ip_mrouter_done();
235         break;
236
237     case MRT_ADD_VIF:
238         error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
239         if (error)
240             break;
241         error = add_vif(&vifc);
242         break;
243
244     case MRT_DEL_VIF:
245         error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
246         if (error)
247             break;
248         error = del_vif(vifi);
249         break;
250
251     case MRT_ADD_MFC:
252     case MRT_DEL_MFC:
253         error = sooptcopyin(sopt, &mfc, sizeof mfc, sizeof mfc);
254         if (error)
255             break;
256         if (sopt->sopt_name == MRT_ADD_MFC)
257             error = add_mfc(&mfc);
258         else
259             error = del_mfc(&mfc);
260         break;
261
262     case MRT_ASSERT:
263         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
264         if (error)
265             break;
266         set_assert(optval);
267         break;
268
269     default:
270         error = EOPNOTSUPP;
271         break;
272     }
273     return error;
274 }
275
276 /*
277  * Handle MRT getsockopt commands
278  */
279 static int
280 X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
281 {
282     int error;
283     static int version = 0x0305; /* !!! why is this here? XXX */
284
285     switch (sopt->sopt_name) {
286     case MRT_VERSION:
287         error = sooptcopyout(sopt, &version, sizeof version);
288         break;
289
290     case MRT_ASSERT:
291         error = sooptcopyout(sopt, &pim_assert, sizeof pim_assert);
292         break;
293
294     default:
295         error = EOPNOTSUPP;
296         break;
297     }
298     return error;
299 }
300
301 /*
302  * Handle ioctl commands to obtain information from the cache
303  */
304 static int
305 X_mrt_ioctl(int cmd, caddr_t data)
306 {
307     int error = 0;
308
309     switch (cmd) {
310     case SIOCGETVIFCNT:
311         error = get_vif_cnt((struct sioc_vif_req *)data);
312         break;
313
314     case SIOCGETSGCNT:
315         error = get_sg_cnt((struct sioc_sg_req *)data);
316         break;
317
318     default:
319         error = EINVAL;
320         break;
321     }
322     return error;
323 }
324
325 /*
326  * returns the packet, byte, rpf-failure count for the source group provided
327  */
328 static int
329 get_sg_cnt(struct sioc_sg_req *req)
330 {
331     int s;
332     struct mfc *rt;
333
334     s = splnet();
335     rt = mfc_find(req->src.s_addr, req->grp.s_addr);
336     splx(s);
337     if (rt == NULL) {
338         req->pktcnt = req->bytecnt = req->wrong_if = 0xffffffff;
339         return EADDRNOTAVAIL;
340     }
341     req->pktcnt = rt->mfc_pkt_cnt;
342     req->bytecnt = rt->mfc_byte_cnt;
343     req->wrong_if = rt->mfc_wrong_if;
344     return 0;
345 }
346
347 /*
348  * returns the input and output packet and byte counts on the vif provided
349  */
350 static int
351 get_vif_cnt(struct sioc_vif_req *req)
352 {
353     vifi_t vifi = req->vifi;
354
355     if (vifi >= numvifs)
356         return EINVAL;
357
358     req->icount = viftable[vifi].v_pkt_in;
359     req->ocount = viftable[vifi].v_pkt_out;
360     req->ibytes = viftable[vifi].v_bytes_in;
361     req->obytes = viftable[vifi].v_bytes_out;
362
363     return 0;
364 }
365
366 /*
367  * Enable multicast routing
368  */
369 static int
370 ip_mrouter_init(struct socket *so, int version)
371 {
372     if (mrtdebug)
373         log(LOG_DEBUG, "ip_mrouter_init: so_type = %d, pr_protocol = %d\n",
374             so->so_type, so->so_proto->pr_protocol);
375
376     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_IGMP)
377         return EOPNOTSUPP;
378
379     if (version != 1)
380         return ENOPROTOOPT;
381
382     if (ip_mrouter != NULL)
383         return EADDRINUSE;
384
385     ip_mrouter = so;
386
387     bzero((caddr_t)mfctable, sizeof(mfctable));
388     bzero((caddr_t)nexpire, sizeof(nexpire));
389
390     pim_assert = 0;
391
392     expire_upcalls_ch = timeout(expire_upcalls, NULL, EXPIRE_TIMEOUT);
393
394     if (mrtdebug)
395         log(LOG_DEBUG, "ip_mrouter_init\n");
396
397     return 0;
398 }
399
400 /*
401  * Disable multicast routing
402  */
403 static int
404 X_ip_mrouter_done(void)
405 {
406     vifi_t vifi;
407     int i;
408     struct ifnet *ifp;
409     struct ifreq ifr;
410     struct mfc *rt;
411     struct rtdetq *rte;
412     int s;
413
414     s = splnet();
415
416     /*
417      * For each phyint in use, disable promiscuous reception of all IP
418      * multicasts.
419      */
420     for (vifi = 0; vifi < numvifs; vifi++) {
421         if (viftable[vifi].v_lcl_addr.s_addr != 0 &&
422                 !(viftable[vifi].v_flags & VIFF_TUNNEL)) {
423             struct sockaddr_in *so = (struct sockaddr_in *)&(ifr.ifr_addr);
424
425             so->sin_len = sizeof(struct sockaddr_in);
426             so->sin_family = AF_INET;
427             so->sin_addr.s_addr = INADDR_ANY;
428             ifp = viftable[vifi].v_ifp;
429             if_allmulti(ifp, 0);
430         }
431     }
432     bzero((caddr_t)tbftable, sizeof(tbftable));
433     bzero((caddr_t)viftable, sizeof(viftable));
434     numvifs = 0;
435     pim_assert = 0;
436
437     untimeout(expire_upcalls, NULL, expire_upcalls_ch);
438
439     /*
440      * Free all multicast forwarding cache entries.
441      */
442     for (i = 0; i < MFCTBLSIZ; i++) {
443         for (rt = mfctable[i]; rt != NULL; ) {
444             struct mfc *nr = rt->mfc_next;
445
446             for (rte = rt->mfc_stall; rte != NULL; ) {
447                 struct rtdetq *n = rte->next;
448
449                 m_freem(rte->m);
450                 free(rte, M_MRTABLE);
451                 rte = n;
452             }
453             free(rt, M_MRTABLE);
454             rt = nr;
455         }
456     }
457
458     bzero((caddr_t)mfctable, sizeof(mfctable));
459
460     /*
461      * Reset de-encapsulation cache
462      */
463     last_encap_src = INADDR_ANY;
464     last_encap_vif = NULL;
465     have_encap_tunnel = 0;
466
467     ip_mrouter = NULL;
468
469     splx(s);
470
471     if (mrtdebug)
472         log(LOG_DEBUG, "ip_mrouter_done\n");
473
474     return 0;
475 }
476
477 /*
478  * Set PIM assert processing global
479  */
480 static int
481 set_assert(int i)
482 {
483     if ((i != 1) && (i != 0))
484         return EINVAL;
485
486     pim_assert = i;
487
488     return 0;
489 }
490
491 /*
492  * Add a vif to the vif table
493  */
494 static int
495 add_vif(struct vifctl *vifcp)
496 {
497     struct vif *vifp = viftable + vifcp->vifc_vifi;
498     struct sockaddr_in sin = {sizeof sin, AF_INET};
499     struct ifaddr *ifa;
500     struct ifnet *ifp;
501     int error, s;
502     struct tbf *v_tbf = tbftable + vifcp->vifc_vifi;
503
504     if (vifcp->vifc_vifi >= MAXVIFS)
505         return EINVAL;
506     if (vifp->v_lcl_addr.s_addr != INADDR_ANY)
507         return EADDRINUSE;
508     if (vifcp->vifc_lcl_addr.s_addr == INADDR_ANY)
509         return EADDRNOTAVAIL;
510
511     /* Find the interface with an address in AF_INET family */
512     sin.sin_addr = vifcp->vifc_lcl_addr;
513     ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
514     if (ifa == NULL)
515         return EADDRNOTAVAIL;
516     ifp = ifa->ifa_ifp;
517
518     if (vifcp->vifc_flags & VIFF_TUNNEL) {
519         if ((vifcp->vifc_flags & VIFF_SRCRT) == 0) {
520             /*
521              * An encapsulating tunnel is wanted.  Tell ipip_input() to
522              * start paying attention to encapsulated packets.
523              */
524             if (have_encap_tunnel == 0) {
525                 have_encap_tunnel = 1;
526                 for (s = 0; s < MAXVIFS; ++s) {
527                     multicast_decap_if[s].if_name = "mdecap";
528                     multicast_decap_if[s].if_unit = s;
529                 }
530             }
531             /*
532              * Set interface to fake encapsulator interface
533              */
534             ifp = &multicast_decap_if[vifcp->vifc_vifi];
535             /*
536              * Prepare cached route entry
537              */
538             bzero(&vifp->v_route, sizeof(vifp->v_route));
539         } else {
540             log(LOG_ERR, "source routed tunnels not supported\n");
541             return EOPNOTSUPP;
542         }
543     } else {            /* Make sure the interface supports multicast */
544         if ((ifp->if_flags & IFF_MULTICAST) == 0)
545             return EOPNOTSUPP;
546
547         /* Enable promiscuous reception of all IP multicasts from the if */
548         s = splnet();
549         error = if_allmulti(ifp, 1);
550         splx(s);
551         if (error)
552             return error;
553     }
554
555     s = splnet();
556     /* define parameters for the tbf structure */
557     vifp->v_tbf = v_tbf;
558     GET_TIME(vifp->v_tbf->tbf_last_pkt_t);
559     vifp->v_tbf->tbf_n_tok = 0;
560     vifp->v_tbf->tbf_q_len = 0;
561     vifp->v_tbf->tbf_max_q_len = MAXQSIZE;
562     vifp->v_tbf->tbf_q = vifp->v_tbf->tbf_t = NULL;
563
564     vifp->v_flags     = vifcp->vifc_flags;
565     vifp->v_threshold = vifcp->vifc_threshold;
566     vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
567     vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
568     vifp->v_ifp       = ifp;
569     /* scaling up here allows division by 1024 in critical code */
570     vifp->v_rate_limit= vifcp->vifc_rate_limit * 1024 / 1000;
571     vifp->v_rsvp_on   = 0;
572     vifp->v_rsvpd     = NULL;
573     /* initialize per vif pkt counters */
574     vifp->v_pkt_in    = 0;
575     vifp->v_pkt_out   = 0;
576     vifp->v_bytes_in  = 0;
577     vifp->v_bytes_out = 0;
578     splx(s);
579
580     /* Adjust numvifs up if the vifi is higher than numvifs */
581     if (numvifs <= vifcp->vifc_vifi) numvifs = vifcp->vifc_vifi + 1;
582
583     if (mrtdebug)
584         log(LOG_DEBUG, "add_vif #%d, lcladdr %lx, %s %lx, thresh %x, rate %d\n",
585             vifcp->vifc_vifi,
586             (u_long)ntohl(vifcp->vifc_lcl_addr.s_addr),
587             (vifcp->vifc_flags & VIFF_TUNNEL) ? "rmtaddr" : "mask",
588             (u_long)ntohl(vifcp->vifc_rmt_addr.s_addr),
589             vifcp->vifc_threshold,
590             vifcp->vifc_rate_limit);
591
592     return 0;
593 }
594
595 /*
596  * Delete a vif from the vif table
597  */
598 static int
599 del_vif(vifi_t vifi)
600 {
601     struct vif *vifp;
602     int s;
603
604     if (vifi >= numvifs)
605         return EINVAL;
606     vifp = &viftable[vifi];
607     if (vifp->v_lcl_addr.s_addr == INADDR_ANY)
608         return EADDRNOTAVAIL;
609
610     s = splnet();
611
612     if (!(vifp->v_flags & VIFF_TUNNEL))
613         if_allmulti(vifp->v_ifp, 0);
614
615     if (vifp == last_encap_vif) {
616         last_encap_vif = NULL;
617         last_encap_src = INADDR_ANY;
618     }
619
620     /*
621      * Free packets queued at the interface
622      */
623     while (vifp->v_tbf->tbf_q) {
624         struct mbuf *m = vifp->v_tbf->tbf_q;
625
626         vifp->v_tbf->tbf_q = m->m_act;
627         m_freem(m);
628     }
629
630     bzero((caddr_t)vifp->v_tbf, sizeof(*(vifp->v_tbf)));
631     bzero((caddr_t)vifp, sizeof (*vifp));
632
633     if (mrtdebug)
634         log(LOG_DEBUG, "del_vif %d, numvifs %d\n", vifi, numvifs);
635
636     /* Adjust numvifs down */
637     for (vifi = numvifs; vifi > 0; vifi--)
638         if (viftable[vifi-1].v_lcl_addr.s_addr != INADDR_ANY)
639             break;
640     numvifs = vifi;
641
642     splx(s);
643
644     return 0;
645 }
646
647 /*
648  * update an mfc entry without resetting counters and S,G addresses.
649  */
650 static void
651 update_mfc_params(struct mfc *rt, struct mfcctl *mfccp)
652 {
653     int i;
654
655     rt->mfc_parent = mfccp->mfcc_parent;
656     for (i = 0; i < numvifs; i++)
657         rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
658 }
659
660 /*
661  * fully initialize an mfc entry from the parameter.
662  */
663 static void
664 init_mfc_params(struct mfc *rt, struct mfcctl *mfccp)
665 {
666     rt->mfc_origin     = mfccp->mfcc_origin;
667     rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
668
669     update_mfc_params(rt, mfccp);
670
671     /* initialize pkt counters per src-grp */
672     rt->mfc_pkt_cnt    = 0;
673     rt->mfc_byte_cnt   = 0;
674     rt->mfc_wrong_if   = 0;
675     rt->mfc_last_assert.tv_sec = rt->mfc_last_assert.tv_usec = 0;
676 }
677
678
679 /*
680  * Add an mfc entry
681  */
682 static int
683 add_mfc(struct mfcctl *mfccp)
684 {
685     struct mfc *rt;
686     u_long hash;
687     struct rtdetq *rte;
688     u_short nstl;
689     int s;
690
691     rt = mfc_find(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
692
693     /* If an entry already exists, just update the fields */
694     if (rt) {
695         if (mrtdebug & DEBUG_MFC)
696             log(LOG_DEBUG,"add_mfc update o %lx g %lx p %x\n",
697                 (u_long)ntohl(mfccp->mfcc_origin.s_addr),
698                 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
699                 mfccp->mfcc_parent);
700
701         s = splnet();
702         update_mfc_params(rt, mfccp);
703         splx(s);
704         return 0;
705     }
706
707     /*
708      * Find the entry for which the upcall was made and update
709      */
710     s = splnet();
711     hash = MFCHASH(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
712     for (rt = mfctable[hash], nstl = 0; rt; rt = rt->mfc_next) {
713
714         if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
715                 (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr) &&
716                 (rt->mfc_stall != NULL)) {
717
718             if (nstl++)
719                 log(LOG_ERR, "add_mfc %s o %lx g %lx p %x dbx %p\n",
720                     "multiple kernel entries",
721                     (u_long)ntohl(mfccp->mfcc_origin.s_addr),
722                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
723                     mfccp->mfcc_parent, (void *)rt->mfc_stall);
724
725             if (mrtdebug & DEBUG_MFC)
726                 log(LOG_DEBUG,"add_mfc o %lx g %lx p %x dbg %p\n",
727                     (u_long)ntohl(mfccp->mfcc_origin.s_addr),
728                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
729                     mfccp->mfcc_parent, (void *)rt->mfc_stall);
730
731             init_mfc_params(rt, mfccp);
732
733             rt->mfc_expire = 0; /* Don't clean this guy up */
734             nexpire[hash]--;
735
736             /* free packets Qed at the end of this entry */
737             for (rte = rt->mfc_stall; rte != NULL; ) {
738                 struct rtdetq *n = rte->next;
739
740                 ip_mdq(rte->m, rte->ifp, rt, -1);
741                 m_freem(rte->m);
742                 free(rte, M_MRTABLE);
743                 rte = n;
744             }
745             rt->mfc_stall = NULL;
746         }
747     }
748
749     /*
750      * It is possible that an entry is being inserted without an upcall
751      */
752     if (nstl == 0) {
753         if (mrtdebug & DEBUG_MFC)
754             log(LOG_DEBUG,"add_mfc no upcall h %lu o %lx g %lx p %x\n",
755                 hash, (u_long)ntohl(mfccp->mfcc_origin.s_addr),
756                 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
757                 mfccp->mfcc_parent);
758
759         for (rt = mfctable[hash]; rt != NULL; rt = rt->mfc_next) {
760             if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
761                     (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr)) {
762                 init_mfc_params(rt, mfccp);
763                 if (rt->mfc_expire)
764                     nexpire[hash]--;
765                 rt->mfc_expire = 0;
766                 break; /* XXX */
767             }
768         }
769         if (rt == NULL) {               /* no upcall, so make a new entry */
770             rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
771             if (rt == NULL) {
772                 splx(s);
773                 return ENOBUFS;
774             }
775
776             init_mfc_params(rt, mfccp);
777             rt->mfc_expire     = 0;
778             rt->mfc_stall      = NULL;
779
780             /* insert new entry at head of hash chain */
781             rt->mfc_next = mfctable[hash];
782             mfctable[hash] = rt;
783         }
784     }
785     splx(s);
786     return 0;
787 }
788
789 /*
790  * Delete an mfc entry
791  */
792 static int
793 del_mfc(struct mfcctl *mfccp)
794 {
795     struct in_addr      origin;
796     struct in_addr      mcastgrp;
797     struct mfc          *rt;
798     struct mfc          **nptr;
799     u_long              hash;
800     int s;
801
802     origin = mfccp->mfcc_origin;
803     mcastgrp = mfccp->mfcc_mcastgrp;
804
805     if (mrtdebug & DEBUG_MFC)
806         log(LOG_DEBUG,"del_mfc orig %lx mcastgrp %lx\n",
807             (u_long)ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
808
809     s = splnet();
810
811     hash = MFCHASH(origin.s_addr, mcastgrp.s_addr);
812     for (nptr = &mfctable[hash]; (rt = *nptr) != NULL; nptr = &rt->mfc_next)
813         if (origin.s_addr == rt->mfc_origin.s_addr &&
814                 mcastgrp.s_addr == rt->mfc_mcastgrp.s_addr &&
815                 rt->mfc_stall == NULL)
816             break;
817     if (rt == NULL) {
818         splx(s);
819         return EADDRNOTAVAIL;
820     }
821
822     *nptr = rt->mfc_next;
823     free(rt, M_MRTABLE);
824
825     splx(s);
826
827     return 0;
828 }
829
830 /*
831  * Send a message to mrouted on the multicast routing socket
832  */
833 static int
834 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
835 {
836     if (s) {
837         if (sbappendaddr(&s->so_rcv, (struct sockaddr *)src, mm, NULL) != 0) {
838             sorwakeup(s);
839             return 0;
840         }
841     }
842     m_freem(mm);
843     return -1;
844 }
845
846 /*
847  * IP multicast forwarding function. This function assumes that the packet
848  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
849  * pointed to by "ifp", and the packet is to be relayed to other networks
850  * that have members of the packet's destination IP multicast group.
851  *
852  * The packet is returned unscathed to the caller, unless it is
853  * erroneous, in which case a non-zero return value tells the caller to
854  * discard it.
855  */
856
857 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
858
859 static int
860 X_ip_mforward(struct ip *ip, struct ifnet *ifp,
861         struct mbuf *m, struct ip_moptions *imo)
862 {
863     struct mfc *rt;
864     int s;
865     vifi_t vifi;
866
867     if (mrtdebug & DEBUG_FORWARD)
868         log(LOG_DEBUG, "ip_mforward: src %lx, dst %lx, ifp %p\n",
869             (u_long)ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr),
870             (void *)ifp);
871
872     if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
873                 ((u_char *)(ip + 1))[1] != IPOPT_LSRR ) {
874         /*
875          * Packet arrived via a physical interface or
876          * an encapsulated tunnel.
877          */
878     } else {
879         /*
880          * Packet arrived through a source-route tunnel.
881          * Source-route tunnels are no longer supported.
882          */
883         static int last_log;
884         if (last_log != time_second) {
885             last_log = time_second;
886             log(LOG_ERR,
887                 "ip_mforward: received source-routed packet from %lx\n",
888                 (u_long)ntohl(ip->ip_src.s_addr));
889         }
890         return 1;
891     }
892
893     if ((imo) && ((vifi = imo->imo_multicast_vif) < numvifs)) {
894         if (ip->ip_ttl < 255)
895             ip->ip_ttl++;       /* compensate for -1 in *_send routines */
896         if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
897             struct vif *vifp = viftable + vifi;
898
899             printf("Sending IPPROTO_RSVP from %lx to %lx on vif %d (%s%s%d)\n",
900                 (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr),
901                 vifi,
902                 (vifp->v_flags & VIFF_TUNNEL) ? "tunnel on " : "",
903                 vifp->v_ifp->if_name, vifp->v_ifp->if_unit);
904         }
905         return ip_mdq(m, ifp, NULL, vifi);
906     }
907     if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
908         printf("Warning: IPPROTO_RSVP from %lx to %lx without vif option\n",
909             (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr));
910         if (!imo)
911             printf("In fact, no options were specified at all\n");
912     }
913
914     /*
915      * Don't forward a packet with time-to-live of zero or one,
916      * or a packet destined to a local-only group.
917      */
918     if (ip->ip_ttl <= 1 || ntohl(ip->ip_dst.s_addr) <= INADDR_MAX_LOCAL_GROUP)
919         return 0;
920
921     /*
922      * Determine forwarding vifs from the forwarding cache table
923      */
924     s = splnet();
925     ++mrtstat.mrts_mfc_lookups;
926     rt = mfc_find(ip->ip_src.s_addr, ip->ip_dst.s_addr);
927
928     /* Entry exists, so forward if necessary */
929     if (rt != NULL) {
930         splx(s);
931         return ip_mdq(m, ifp, rt, -1);
932     } else {
933         /*
934          * If we don't have a route for packet's origin,
935          * Make a copy of the packet & send message to routing daemon
936          */
937
938         struct mbuf *mb0;
939         struct rtdetq *rte;
940         u_long hash;
941         int hlen = ip->ip_hl << 2;
942
943         ++mrtstat.mrts_mfc_misses;
944
945         mrtstat.mrts_no_route++;
946         if (mrtdebug & (DEBUG_FORWARD | DEBUG_MFC))
947             log(LOG_DEBUG, "ip_mforward: no rte s %lx g %lx\n",
948                 (u_long)ntohl(ip->ip_src.s_addr),
949                 (u_long)ntohl(ip->ip_dst.s_addr));
950
951         /*
952          * Allocate mbufs early so that we don't do extra work if we are
953          * just going to fail anyway.  Make sure to pullup the header so
954          * that other people can't step on it.
955          */
956         rte = (struct rtdetq *)malloc((sizeof *rte), M_MRTABLE, M_NOWAIT);
957         if (rte == NULL) {
958             splx(s);
959             return ENOBUFS;
960         }
961         mb0 = m_copy(m, 0, M_COPYALL);
962         if (mb0 && (M_HASCL(mb0) || mb0->m_len < hlen))
963             mb0 = m_pullup(mb0, hlen);
964         if (mb0 == NULL) {
965             free(rte, M_MRTABLE);
966             splx(s);
967             return ENOBUFS;
968         }
969
970         /* is there an upcall waiting for this flow ? */
971         hash = MFCHASH(ip->ip_src.s_addr, ip->ip_dst.s_addr);
972         for (rt = mfctable[hash]; rt; rt = rt->mfc_next) {
973             if ((ip->ip_src.s_addr == rt->mfc_origin.s_addr) &&
974                     (ip->ip_dst.s_addr == rt->mfc_mcastgrp.s_addr) &&
975                     (rt->mfc_stall != NULL))
976                 break;
977         }
978
979         if (rt == NULL) {
980             int i;
981             struct igmpmsg *im;
982             struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
983             struct mbuf *mm;
984
985             /*
986              * Locate the vifi for the incoming interface for this packet.
987              * If none found, drop packet.
988              */
989             for (vifi=0; vifi<numvifs && viftable[vifi].v_ifp != ifp; vifi++)
990                 ;
991             if (vifi >= numvifs)        /* vif not found, drop packet */
992                 goto non_fatal;
993
994             /* no upcall, so make a new entry */
995             rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
996             if (rt == NULL)
997                 goto fail;
998             /* Make a copy of the header to send to the user level process */
999             mm = m_copy(mb0, 0, hlen);
1000             if (mm == NULL)
1001                 goto fail1;
1002
1003             /*
1004              * Send message to routing daemon to install
1005              * a route into the kernel table
1006              */
1007
1008             im = mtod(mm, struct igmpmsg *);
1009             im->im_msgtype = IGMPMSG_NOCACHE;
1010             im->im_mbz = 0;
1011             im->im_vif = vifi;
1012
1013             mrtstat.mrts_upcalls++;
1014
1015             k_igmpsrc.sin_addr = ip->ip_src;
1016             if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1017                 log(LOG_WARNING, "ip_mforward: ip_mrouter socket queue full\n");
1018                 ++mrtstat.mrts_upq_sockfull;
1019 fail1:
1020                 free(rt, M_MRTABLE);
1021 fail:
1022                 free(rte, M_MRTABLE);
1023                 m_freem(mb0);
1024                 splx(s);
1025                 return ENOBUFS;
1026             }
1027
1028             /* insert new entry at head of hash chain */
1029             rt->mfc_origin.s_addr     = ip->ip_src.s_addr;
1030             rt->mfc_mcastgrp.s_addr   = ip->ip_dst.s_addr;
1031             rt->mfc_expire            = UPCALL_EXPIRE;
1032             nexpire[hash]++;
1033             for (i = 0; i < numvifs; i++)
1034                 rt->mfc_ttls[i] = 0;
1035             rt->mfc_parent = -1;
1036
1037             /* link into table */
1038             rt->mfc_next   = mfctable[hash];
1039             mfctable[hash] = rt;
1040             rt->mfc_stall = rte;
1041
1042         } else {
1043             /* determine if q has overflowed */
1044             int npkts = 0;
1045             struct rtdetq **p;
1046
1047             /*
1048              * XXX ouch! we need to append to the list, but we
1049              * only have a pointer to the front, so we have to
1050              * scan the entire list every time.
1051              */
1052             for (p = &rt->mfc_stall; *p != NULL; p = &(*p)->next)
1053                 npkts++;
1054
1055             if (npkts > MAX_UPQ) {
1056                 mrtstat.mrts_upq_ovflw++;
1057 non_fatal:
1058                 free(rte, M_MRTABLE);
1059                 m_freem(mb0);
1060                 splx(s);
1061                 return 0;
1062             }
1063
1064             /* Add this entry to the end of the queue */
1065             *p = rte;
1066         }
1067
1068         rte->m                  = mb0;
1069         rte->ifp                = ifp;
1070         rte->next               = NULL;
1071
1072         splx(s);
1073
1074         return 0;
1075     }
1076 }
1077
1078 /*
1079  * Clean up the cache entry if upcall is not serviced
1080  */
1081 static void
1082 expire_upcalls(void *unused)
1083 {
1084     struct rtdetq *rte;
1085     struct mfc *mfc, **nptr;
1086     int i;
1087     int s;
1088
1089     s = splnet();
1090     for (i = 0; i < MFCTBLSIZ; i++) {
1091         if (nexpire[i] == 0)
1092             continue;
1093         nptr = &mfctable[i];
1094         for (mfc = *nptr; mfc != NULL; mfc = *nptr) {
1095             /*
1096              * Skip real cache entries
1097              * Make sure it wasn't marked to not expire (shouldn't happen)
1098              * If it expires now
1099              */
1100             if (mfc->mfc_stall != NULL && mfc->mfc_expire != 0 &&
1101                     --mfc->mfc_expire == 0) {
1102                 if (mrtdebug & DEBUG_EXPIRE)
1103                     log(LOG_DEBUG, "expire_upcalls: expiring (%lx %lx)\n",
1104                         (u_long)ntohl(mfc->mfc_origin.s_addr),
1105                         (u_long)ntohl(mfc->mfc_mcastgrp.s_addr));
1106                 /*
1107                  * drop all the packets
1108                  * free the mbuf with the pkt, if, timing info
1109                  */
1110                 for (rte = mfc->mfc_stall; rte; ) {
1111                     struct rtdetq *n = rte->next;
1112
1113                     m_freem(rte->m);
1114                     free(rte, M_MRTABLE);
1115                     rte = n;
1116                 }
1117                 ++mrtstat.mrts_cache_cleanups;
1118                 nexpire[i]--;
1119
1120                 *nptr = mfc->mfc_next;
1121                 free(mfc, M_MRTABLE);
1122             } else {
1123                 nptr = &mfc->mfc_next;
1124             }
1125         }
1126     }
1127     splx(s);
1128     expire_upcalls_ch = timeout(expire_upcalls, NULL, EXPIRE_TIMEOUT);
1129 }
1130
1131 /*
1132  * Packet forwarding routine once entry in the cache is made
1133  */
1134 static int
1135 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1136 {
1137     struct ip  *ip = mtod(m, struct ip *);
1138     vifi_t vifi;
1139     int plen = ip->ip_len;
1140
1141 /*
1142  * Macro to send packet on vif.  Since RSVP packets don't get counted on
1143  * input, they shouldn't get counted on output, so statistics keeping is
1144  * separate.
1145  */
1146 #define MC_SEND(ip,vifp,m) {                             \
1147                 if ((vifp)->v_flags & VIFF_TUNNEL)       \
1148                     encap_send((ip), (vifp), (m));       \
1149                 else                                     \
1150                     phyint_send((ip), (vifp), (m));      \
1151 }
1152
1153     /*
1154      * If xmt_vif is not -1, send on only the requested vif.
1155      *
1156      * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1157      */
1158     if (xmt_vif < numvifs) {
1159         MC_SEND(ip, viftable + xmt_vif, m);
1160         return 1;
1161     }
1162
1163     /*
1164      * Don't forward if it didn't arrive from the parent vif for its origin.
1165      */
1166     vifi = rt->mfc_parent;
1167     if ((vifi >= numvifs) || (viftable[vifi].v_ifp != ifp)) {
1168         /* came in the wrong interface */
1169         if (mrtdebug & DEBUG_FORWARD)
1170             log(LOG_DEBUG, "wrong if: ifp %p vifi %d vififp %p\n",
1171                 (void *)ifp, vifi, (void *)viftable[vifi].v_ifp);
1172         ++mrtstat.mrts_wrong_if;
1173         ++rt->mfc_wrong_if;
1174         /*
1175          * If we are doing PIM assert processing, and we are forwarding
1176          * packets on this interface, and it is a broadcast medium
1177          * interface (and not a tunnel), send a message to the routing daemon.
1178          */
1179         if (pim_assert && rt->mfc_ttls[vifi] &&
1180                 (ifp->if_flags & IFF_BROADCAST) &&
1181                 !(viftable[vifi].v_flags & VIFF_TUNNEL)) {
1182             struct timeval now;
1183             u_long delta;
1184
1185             GET_TIME(now);
1186
1187             TV_DELTA(rt->mfc_last_assert, now, delta);
1188
1189             if (delta > ASSERT_MSG_TIME) {
1190                 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1191                 struct igmpmsg *im;
1192                 int hlen = ip->ip_hl << 2;
1193                 struct mbuf *mm = m_copy(m, 0, hlen);
1194
1195                 if (mm && (M_HASCL(mm) || mm->m_len < hlen))
1196                     mm = m_pullup(mm, hlen);
1197                 if (mm == NULL)
1198                     return ENOBUFS;
1199
1200                 rt->mfc_last_assert = now;
1201
1202                 im = mtod(mm, struct igmpmsg *);
1203                 im->im_msgtype  = IGMPMSG_WRONGVIF;
1204                 im->im_mbz              = 0;
1205                 im->im_vif              = vifi;
1206
1207                 k_igmpsrc.sin_addr = im->im_src;
1208
1209                 if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1210                     log(LOG_WARNING,
1211                         "ip_mforward: ip_mrouter socket queue full\n");
1212                     ++mrtstat.mrts_upq_sockfull;
1213                     return ENOBUFS;
1214                 }
1215             }
1216         }
1217         return 0;
1218     }
1219
1220     /* If I sourced this packet, it counts as output, else it was input. */
1221     if (ip->ip_src.s_addr == viftable[vifi].v_lcl_addr.s_addr) {
1222         viftable[vifi].v_pkt_out++;
1223         viftable[vifi].v_bytes_out += plen;
1224     } else {
1225         viftable[vifi].v_pkt_in++;
1226         viftable[vifi].v_bytes_in += plen;
1227     }
1228     rt->mfc_pkt_cnt++;
1229     rt->mfc_byte_cnt += plen;
1230
1231     /*
1232      * For each vif, decide if a copy of the packet should be forwarded.
1233      * Forward if:
1234      *          - the ttl exceeds the vif's threshold
1235      *          - there are group members downstream on interface
1236      */
1237     for (vifi = 0; vifi < numvifs; vifi++)
1238         if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1239             viftable[vifi].v_pkt_out++;
1240             viftable[vifi].v_bytes_out += plen;
1241             MC_SEND(ip, viftable+vifi, m);
1242         }
1243
1244     return 0;
1245 }
1246
1247 /*
1248  * check if a vif number is legal/ok. This is used by ip_output.
1249  */
1250 static int
1251 X_legal_vif_num(int vif)
1252 {
1253     return (vif >= 0 && vif < numvifs);
1254 }
1255
1256 /*
1257  * Return the local address used by this vif
1258  */
1259 static u_long
1260 X_ip_mcast_src(int vifi)
1261 {
1262     if (vifi >= 0 && vifi < numvifs)
1263         return viftable[vifi].v_lcl_addr.s_addr;
1264     else
1265         return INADDR_ANY;
1266 }
1267
1268 static void
1269 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1270 {
1271     struct mbuf *mb_copy;
1272     int hlen = ip->ip_hl << 2;
1273
1274     /*
1275      * Make a new reference to the packet; make sure that
1276      * the IP header is actually copied, not just referenced,
1277      * so that ip_output() only scribbles on the copy.
1278      */
1279     mb_copy = m_copy(m, 0, M_COPYALL);
1280     if (mb_copy && (M_HASCL(mb_copy) || mb_copy->m_len < hlen))
1281         mb_copy = m_pullup(mb_copy, hlen);
1282     if (mb_copy == NULL)
1283         return;
1284
1285     if (vifp->v_rate_limit == 0)
1286         tbf_send_packet(vifp, mb_copy);
1287     else
1288         tbf_control(vifp, mb_copy, mtod(mb_copy, struct ip *), ip->ip_len);
1289 }
1290
1291 static void
1292 encap_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1293 {
1294     struct mbuf *mb_copy;
1295     struct ip *ip_copy;
1296     int i, len = ip->ip_len;
1297
1298     /*
1299      * XXX: take care of delayed checksums.
1300      * XXX: if network interfaces are capable of computing checksum for
1301      * encapsulated multicast data packets, we need to reconsider this.
1302      */
1303     if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1304         in_delayed_cksum(m);
1305         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1306     }
1307
1308     /*
1309      * copy the old packet & pullup its IP header into the
1310      * new mbuf so we can modify it.  Try to fill the new
1311      * mbuf since if we don't the ethernet driver will.
1312      */
1313     MGETHDR(mb_copy, M_DONTWAIT, MT_HEADER);
1314     if (mb_copy == NULL)
1315         return;
1316     mb_copy->m_data += max_linkhdr;
1317     mb_copy->m_len = sizeof(multicast_encap_iphdr);
1318
1319     if ((mb_copy->m_next = m_copy(m, 0, M_COPYALL)) == NULL) {
1320         m_freem(mb_copy);
1321         return;
1322     }
1323     i = MHLEN - M_LEADINGSPACE(mb_copy);
1324     if (i > len)
1325         i = len;
1326     mb_copy = m_pullup(mb_copy, i);
1327     if (mb_copy == NULL)
1328         return;
1329     mb_copy->m_pkthdr.len = len + sizeof(multicast_encap_iphdr);
1330
1331     /*
1332      * fill in the encapsulating IP header.
1333      */
1334     ip_copy = mtod(mb_copy, struct ip *);
1335     *ip_copy = multicast_encap_iphdr;
1336 #ifdef RANDOM_IP_ID
1337     ip_copy->ip_id = ip_randomid();
1338 #else
1339     ip_copy->ip_id = htons(ip_id++);
1340 #endif
1341     ip_copy->ip_len += len;
1342     ip_copy->ip_src = vifp->v_lcl_addr;
1343     ip_copy->ip_dst = vifp->v_rmt_addr;
1344
1345     /*
1346      * turn the encapsulated IP header back into a valid one.
1347      */
1348     ip = (struct ip *)((caddr_t)ip_copy + sizeof(multicast_encap_iphdr));
1349     --ip->ip_ttl;
1350     ip->ip_len = htons(ip->ip_len);
1351     ip->ip_off = htons(ip->ip_off);
1352     ip->ip_sum = 0;
1353     mb_copy->m_data += sizeof(multicast_encap_iphdr);
1354     ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
1355     mb_copy->m_data -= sizeof(multicast_encap_iphdr);
1356
1357     if (vifp->v_rate_limit == 0)
1358         tbf_send_packet(vifp, mb_copy);
1359     else
1360         tbf_control(vifp, mb_copy, ip, ip_copy->ip_len);
1361 }
1362
1363 /*
1364  * De-encapsulate a packet and feed it back through ip input (this
1365  * routine is called whenever IP gets a packet with proto type
1366  * ENCAP_PROTO and a local destination address).
1367  *
1368  * This is similar to mroute_encapcheck() + mroute_encap_input() in -current.
1369  */
1370 static void
1371 X_ipip_input(struct mbuf *m, int off, int proto)
1372 {
1373     struct ip *ip = mtod(m, struct ip *);
1374     int hlen = ip->ip_hl << 2;
1375     int s;
1376     struct ifqueue *ifq;
1377
1378     if (!have_encap_tunnel) {
1379         rip_input(m, off, proto);
1380         return;
1381     }
1382     /*
1383      * dump the packet if it's not to a multicast destination or if
1384      * we don't have an encapsulating tunnel with the source.
1385      * Note:  This code assumes that the remote site IP address
1386      * uniquely identifies the tunnel (i.e., that this site has
1387      * at most one tunnel with the remote site).
1388      */
1389     if (!IN_MULTICAST(ntohl(((struct ip *)((char *)ip+hlen))->ip_dst.s_addr))) {
1390         ++mrtstat.mrts_bad_tunnel;
1391         m_freem(m);
1392         return;
1393     }
1394     if (ip->ip_src.s_addr != last_encap_src) {
1395         struct vif *vifp = viftable;
1396         struct vif *vife = vifp + numvifs;
1397
1398         last_encap_src = ip->ip_src.s_addr;
1399         last_encap_vif = NULL;
1400         for ( ; vifp < vife; ++vifp)
1401             if (vifp->v_rmt_addr.s_addr == ip->ip_src.s_addr) {
1402                 if ((vifp->v_flags & (VIFF_TUNNEL|VIFF_SRCRT))
1403                     == VIFF_TUNNEL)
1404                     last_encap_vif = vifp;
1405                 break;
1406             }
1407     }
1408     if (last_encap_vif == NULL) {
1409         last_encap_src = INADDR_ANY;
1410         mrtstat.mrts_cant_tunnel++; /*XXX*/
1411         m_freem(m);
1412         if (mrtdebug)
1413             log(LOG_DEBUG, "ip_mforward: no tunnel with %lx\n",
1414                 (u_long)ntohl(ip->ip_src.s_addr));
1415         return;
1416     }
1417
1418     if (hlen > sizeof(struct ip))
1419         ip_stripoptions(m, NULL);
1420     m->m_data += sizeof(struct ip);
1421     m->m_len -= sizeof(struct ip);
1422     m->m_pkthdr.len -= sizeof(struct ip);
1423     m->m_pkthdr.rcvif = last_encap_vif->v_ifp;
1424
1425     ifq = &ipintrq;
1426     s = splimp();
1427     if (IF_QFULL(ifq)) {
1428         IF_DROP(ifq);
1429         m_freem(m);
1430     } else {
1431         IF_ENQUEUE(ifq, m);
1432         /*
1433          * normally we would need a "schednetisr(NETISR_IP)"
1434          * here but we were called by ip_input and it is going
1435          * to loop back & try to dequeue the packet we just
1436          * queued as soon as we return so we avoid the
1437          * unnecessary software interrrupt.
1438          */
1439     }
1440     splx(s);
1441 }
1442
1443 /*
1444  * Token bucket filter module
1445  */
1446
1447 static void
1448 tbf_control(struct vif *vifp, struct mbuf *m, struct ip *ip, u_long p_len)
1449 {
1450     struct tbf *t = vifp->v_tbf;
1451
1452     if (p_len > MAX_BKT_SIZE) {         /* drop if packet is too large */
1453         mrtstat.mrts_pkt2large++;
1454         m_freem(m);
1455         return;
1456     }
1457
1458     tbf_update_tokens(vifp);
1459
1460     if (t->tbf_q_len == 0) {            /* queue empty...               */
1461         if (p_len <= t->tbf_n_tok) {    /* send packet if enough tokens */
1462             t->tbf_n_tok -= p_len;
1463             tbf_send_packet(vifp, m);
1464         } else {                        /* no, queue packet and try later */
1465             tbf_queue(vifp, m);
1466             timeout(tbf_reprocess_q, (caddr_t)vifp, TBF_REPROCESS);
1467         }
1468     } else if (t->tbf_q_len < t->tbf_max_q_len) {
1469         /* finite queue length, so queue pkts and process queue */
1470         tbf_queue(vifp, m);
1471         tbf_process_q(vifp);
1472     } else {
1473         /* queue full, try to dq and queue and process */
1474         if (!tbf_dq_sel(vifp, ip)) {
1475             mrtstat.mrts_q_overflow++;
1476             m_freem(m);
1477         } else {
1478             tbf_queue(vifp, m);
1479             tbf_process_q(vifp);
1480         }
1481     }
1482 }
1483
1484 /*
1485  * adds a packet to the queue at the interface
1486  */
1487 static void
1488 tbf_queue(struct vif *vifp, struct mbuf *m)
1489 {
1490     int s = splnet();
1491     struct tbf *t = vifp->v_tbf;
1492
1493     if (t->tbf_t == NULL)       /* Queue was empty */
1494         t->tbf_q = m;
1495     else                        /* Insert at tail */
1496         t->tbf_t->m_act = m;
1497
1498     t->tbf_t = m;               /* Set new tail pointer */
1499
1500 #ifdef DIAGNOSTIC
1501     /* Make sure we didn't get fed a bogus mbuf */
1502     if (m->m_act)
1503         panic("tbf_queue: m_act");
1504 #endif
1505     m->m_act = NULL;
1506
1507     t->tbf_q_len++;
1508
1509     splx(s);
1510 }
1511
1512 /*
1513  * processes the queue at the interface
1514  */
1515 static void
1516 tbf_process_q(struct vif *vifp)
1517 {
1518     int s = splnet();
1519     struct tbf *t = vifp->v_tbf;
1520
1521     /* loop through the queue at the interface and send as many packets
1522      * as possible
1523      */
1524     while (t->tbf_q_len > 0) {
1525         struct mbuf *m = t->tbf_q;
1526         int len = mtod(m, struct ip *)->ip_len;
1527
1528         /* determine if the packet can be sent */
1529         if (len > t->tbf_n_tok) /* not enough tokens, we are done */
1530             break;
1531         /* ok, reduce no of tokens, dequeue and send the packet. */
1532         t->tbf_n_tok -= len;
1533
1534         t->tbf_q = m->m_act;
1535         if (--t->tbf_q_len == 0)
1536             t->tbf_t = NULL;
1537
1538         m->m_act = NULL;
1539         tbf_send_packet(vifp, m);
1540     }
1541     splx(s);
1542 }
1543
1544 static void
1545 tbf_reprocess_q(void *xvifp)
1546 {
1547     struct vif *vifp = xvifp;
1548
1549     if (ip_mrouter == NULL)
1550         return;
1551     tbf_update_tokens(vifp);
1552     tbf_process_q(vifp);
1553     if (vifp->v_tbf->tbf_q_len)
1554         timeout(tbf_reprocess_q, (caddr_t)vifp, TBF_REPROCESS);
1555 }
1556
1557 /* function that will selectively discard a member of the queue
1558  * based on the precedence value and the priority
1559  */
1560 static int
1561 tbf_dq_sel(struct vif *vifp, struct ip *ip)
1562 {
1563     int s = splnet();
1564     u_int p;
1565     struct mbuf *m, *last;
1566     struct mbuf **np;
1567     struct tbf *t = vifp->v_tbf;
1568
1569     p = priority(vifp, ip);
1570
1571     np = &t->tbf_q;
1572     last = NULL;
1573     while ((m = *np) != NULL) {
1574         if (p > priority(vifp, mtod(m, struct ip *))) {
1575             *np = m->m_act;
1576             /* If we're removing the last packet, fix the tail pointer */
1577             if (m == t->tbf_t)
1578                 t->tbf_t = last;
1579             m_freem(m);
1580             /* It's impossible for the queue to be empty, but check anyways. */
1581             if (--t->tbf_q_len == 0)
1582                 t->tbf_t = NULL;
1583             splx(s);
1584             mrtstat.mrts_drop_sel++;
1585             return 1;
1586         }
1587         np = &m->m_act;
1588         last = m;
1589     }
1590     splx(s);
1591     return 0;
1592 }
1593
1594 static void
1595 tbf_send_packet(struct vif *vifp, struct mbuf *m)
1596 {
1597     int s = splnet();
1598
1599     if (vifp->v_flags & VIFF_TUNNEL)    /* If tunnel options */
1600         ip_output(m, NULL, &vifp->v_route, IP_FORWARDING, NULL, NULL);
1601     else {
1602         struct ip_moptions imo;
1603         int error;
1604         static struct route ro; /* XXX check this */
1605
1606         imo.imo_multicast_ifp  = vifp->v_ifp;
1607         imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1608         imo.imo_multicast_loop = 1;
1609         imo.imo_multicast_vif  = -1;
1610
1611         /*
1612          * Re-entrancy should not be a problem here, because
1613          * the packets that we send out and are looped back at us
1614          * should get rejected because they appear to come from
1615          * the loopback interface, thus preventing looping.
1616          */
1617         error = ip_output(m, NULL, &ro, IP_FORWARDING, &imo, NULL);
1618
1619         if (mrtdebug & DEBUG_XMIT)
1620             log(LOG_DEBUG, "phyint_send on vif %d err %d\n",
1621                 (int)(vifp - viftable), error);
1622     }
1623     splx(s);
1624 }
1625
1626 /* determine the current time and then
1627  * the elapsed time (between the last time and time now)
1628  * in milliseconds & update the no. of tokens in the bucket
1629  */
1630 static void
1631 tbf_update_tokens(struct vif *vifp)
1632 {
1633     struct timeval tp;
1634     u_long tm;
1635     int s = splnet();
1636     struct tbf *t = vifp->v_tbf;
1637
1638     GET_TIME(tp);
1639
1640     TV_DELTA(tp, t->tbf_last_pkt_t, tm);
1641
1642     /*
1643      * This formula is actually
1644      * "time in seconds" * "bytes/second".
1645      *
1646      * (tm / 1000000) * (v_rate_limit * 1000 * (1000/1024) / 8)
1647      *
1648      * The (1000/1024) was introduced in add_vif to optimize
1649      * this divide into a shift.
1650      */
1651     t->tbf_n_tok += tm * vifp->v_rate_limit / 1024 / 8;
1652     t->tbf_last_pkt_t = tp;
1653
1654     if (t->tbf_n_tok > MAX_BKT_SIZE)
1655         t->tbf_n_tok = MAX_BKT_SIZE;
1656
1657     splx(s);
1658 }
1659
1660 static int
1661 priority(struct vif *vifp, struct ip *ip)
1662 {
1663     int prio = 50; /* the lowest priority -- default case */
1664
1665     /* temporary hack; may add general packet classifier some day */
1666
1667     /*
1668      * The UDP port space is divided up into four priority ranges:
1669      * [0, 16384)     : unclassified - lowest priority
1670      * [16384, 32768) : audio - highest priority
1671      * [32768, 49152) : whiteboard - medium priority
1672      * [49152, 65536) : video - low priority
1673      *
1674      * Everything else gets lowest priority.
1675      */
1676     if (ip->ip_p == IPPROTO_UDP) {
1677         struct udphdr *udp = (struct udphdr *)(((char *)ip) + (ip->ip_hl << 2));
1678         switch (ntohs(udp->uh_dport) & 0xc000) {
1679         case 0x4000:
1680             prio = 70;
1681             break;
1682         case 0x8000:
1683             prio = 60;
1684             break;
1685         case 0xc000:
1686             prio = 55;
1687             break;
1688         }
1689     }
1690     return prio;
1691 }
1692
1693 /*
1694  * End of token bucket filter modifications
1695  */
1696
1697 static int
1698 X_ip_rsvp_vif(struct socket *so, struct sockopt *sopt)
1699 {
1700     int error, vifi, s;
1701
1702     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
1703         return EOPNOTSUPP;
1704
1705     error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
1706     if (error)
1707         return error;
1708
1709     s = splnet();
1710
1711     if (vifi < 0 || vifi >= numvifs) { /* Error if vif is invalid */
1712         splx(s);
1713         return EADDRNOTAVAIL;
1714     }
1715
1716     if (sopt->sopt_name == IP_RSVP_VIF_ON) {
1717         /* Check if socket is available. */
1718         if (viftable[vifi].v_rsvpd != NULL) {
1719             splx(s);
1720             return EADDRINUSE;
1721         }
1722
1723         viftable[vifi].v_rsvpd = so;
1724         /* This may seem silly, but we need to be sure we don't over-increment
1725          * the RSVP counter, in case something slips up.
1726          */
1727         if (!viftable[vifi].v_rsvp_on) {
1728             viftable[vifi].v_rsvp_on = 1;
1729             rsvp_on++;
1730         }
1731     } else { /* must be VIF_OFF */
1732         /*
1733          * XXX as an additional consistency check, one could make sure
1734          * that viftable[vifi].v_rsvpd == so, otherwise passing so as
1735          * first parameter is pretty useless.
1736          */
1737         viftable[vifi].v_rsvpd = NULL;
1738         /*
1739          * This may seem silly, but we need to be sure we don't over-decrement
1740          * the RSVP counter, in case something slips up.
1741          */
1742         if (viftable[vifi].v_rsvp_on) {
1743             viftable[vifi].v_rsvp_on = 0;
1744             rsvp_on--;
1745         }
1746     }
1747     splx(s);
1748     return 0;
1749 }
1750
1751 static void
1752 X_ip_rsvp_force_done(struct socket *so)
1753 {
1754     int vifi;
1755     int s;
1756
1757     /* Don't bother if it is not the right type of socket. */
1758     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
1759         return;
1760
1761     s = splnet();
1762
1763     /* The socket may be attached to more than one vif...this
1764      * is perfectly legal.
1765      */
1766     for (vifi = 0; vifi < numvifs; vifi++) {
1767         if (viftable[vifi].v_rsvpd == so) {
1768             viftable[vifi].v_rsvpd = NULL;
1769             /* This may seem silly, but we need to be sure we don't
1770              * over-decrement the RSVP counter, in case something slips up.
1771              */
1772             if (viftable[vifi].v_rsvp_on) {
1773                 viftable[vifi].v_rsvp_on = 0;
1774                 rsvp_on--;
1775             }
1776         }
1777     }
1778
1779     splx(s);
1780 }
1781
1782 static void
1783 X_rsvp_input(struct mbuf *m, int off, int proto)
1784 {
1785     int vifi;
1786     struct ip *ip = mtod(m, struct ip *);
1787     struct sockaddr_in rsvp_src = { sizeof rsvp_src, AF_INET };
1788     int s;
1789     struct ifnet *ifp;
1790
1791     if (rsvpdebug)
1792         printf("rsvp_input: rsvp_on %d\n",rsvp_on);
1793
1794     /* Can still get packets with rsvp_on = 0 if there is a local member
1795      * of the group to which the RSVP packet is addressed.  But in this
1796      * case we want to throw the packet away.
1797      */
1798     if (!rsvp_on) {
1799         m_freem(m);
1800         return;
1801     }
1802
1803     s = splnet();
1804
1805     if (rsvpdebug)
1806         printf("rsvp_input: check vifs\n");
1807
1808 #ifdef DIAGNOSTIC
1809     if (!(m->m_flags & M_PKTHDR))
1810         panic("rsvp_input no hdr");
1811 #endif
1812
1813     ifp = m->m_pkthdr.rcvif;
1814     /* Find which vif the packet arrived on. */
1815     for (vifi = 0; vifi < numvifs; vifi++)
1816         if (viftable[vifi].v_ifp == ifp)
1817             break;
1818
1819     if (vifi == numvifs || viftable[vifi].v_rsvpd == NULL) {
1820         /*
1821          * If the old-style non-vif-associated socket is set,
1822          * then use it.  Otherwise, drop packet since there
1823          * is no specific socket for this vif.
1824          */
1825         if (ip_rsvpd != NULL) {
1826             if (rsvpdebug)
1827                 printf("rsvp_input: Sending packet up old-style socket\n");
1828             rip_input(m, off, proto);  /* xxx */
1829         } else {
1830             if (rsvpdebug && vifi == numvifs)
1831                 printf("rsvp_input: Can't find vif for packet.\n");
1832             else if (rsvpdebug && viftable[vifi].v_rsvpd == NULL)
1833                 printf("rsvp_input: No socket defined for vif %d\n",vifi);
1834             m_freem(m);
1835         }
1836         splx(s);
1837         return;
1838     }
1839     rsvp_src.sin_addr = ip->ip_src;
1840
1841     if (rsvpdebug && m)
1842         printf("rsvp_input: m->m_len = %d, sbspace() = %ld\n",
1843                m->m_len,sbspace(&(viftable[vifi].v_rsvpd->so_rcv)));
1844
1845     if (socket_send(viftable[vifi].v_rsvpd, m, &rsvp_src) < 0) {
1846         if (rsvpdebug)
1847             printf("rsvp_input: Failed to append to socket\n");
1848     } else {
1849         if (rsvpdebug)
1850             printf("rsvp_input: send packet up\n");
1851     }
1852
1853     splx(s);
1854 }
1855
1856 static int
1857 ip_mroute_modevent(module_t mod, int type, void *unused)
1858 {
1859     int s;
1860
1861     switch (type) {
1862     case MOD_LOAD:
1863         s = splnet();
1864         /* XXX Protect against multiple loading */
1865         ip_mcast_src = X_ip_mcast_src;
1866         ip_mforward = X_ip_mforward;
1867         ip_mrouter_done = X_ip_mrouter_done;
1868         ip_mrouter_get = X_ip_mrouter_get;
1869         ip_mrouter_set = X_ip_mrouter_set;
1870         ip_rsvp_force_done = X_ip_rsvp_force_done;
1871         ip_rsvp_vif = X_ip_rsvp_vif;
1872         ipip_input = X_ipip_input;
1873         legal_vif_num = X_legal_vif_num;
1874         mrt_ioctl = X_mrt_ioctl;
1875         rsvp_input_p = X_rsvp_input;
1876         splx(s);
1877         break;
1878
1879     case MOD_UNLOAD:
1880         if (ip_mrouter)
1881             return EINVAL;
1882
1883         s = splnet();
1884         ip_mcast_src = NULL;
1885         ip_mforward = NULL;
1886         ip_mrouter_done = NULL;
1887         ip_mrouter_get = NULL;
1888         ip_mrouter_set = NULL;
1889         ip_rsvp_force_done = NULL;
1890         ip_rsvp_vif = NULL;
1891         ipip_input = NULL;
1892         legal_vif_num = NULL;
1893         mrt_ioctl = NULL;
1894         rsvp_input_p = NULL;
1895         splx(s);
1896         break;
1897     }
1898     return 0;
1899 }
1900
1901 static moduledata_t ip_mroutemod = {
1902     "ip_mroute",
1903     ip_mroute_modevent,
1904     0
1905 };
1906 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PSEUDO, SI_ORDER_ANY);