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