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