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