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