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