xref: /netbsd-src/sys/netinet/ip_mroute.c (revision ce2c90c7c172d95d2402a5b3d96d8f8e6d138a21)
1 /*	$NetBSD: ip_mroute.c,v 1.99 2006/10/12 01:32:38 christos 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.99 2006/10/12 01:32:38 christos 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, caddr_t 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 =
627 	    hashinit(MFCTBLSIZ, HASH_LIST, M_MRTABLE, M_WAITOK, &mfchash);
628 	bzero((caddr_t)nexpire, sizeof(nexpire));
629 
630 	pim_assert = 0;
631 
632 	callout_init(&expire_upcalls_ch);
633 	callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT,
634 		      expire_upcalls, NULL);
635 
636 	callout_init(&bw_upcalls_ch);
637 	callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
638 		      expire_bw_upcalls_send, NULL);
639 
640 	callout_init(&bw_meter_ch);
641 	callout_reset(&bw_meter_ch, BW_METER_PERIOD,
642 		      expire_bw_meter_process, NULL);
643 
644 	if (mrtdebug)
645 		log(LOG_DEBUG, "ip_mrouter_init\n");
646 
647 	return (0);
648 }
649 
650 /*
651  * Disable multicast routing
652  */
653 int
654 ip_mrouter_done(void)
655 {
656 	vifi_t vifi;
657 	struct vif *vifp;
658 	int i;
659 	int s;
660 
661 	s = splsoftnet();
662 
663 	/* Clear out all the vifs currently in use. */
664 	for (vifi = 0; vifi < numvifs; vifi++) {
665 		vifp = &viftable[vifi];
666 		if (!in_nullhost(vifp->v_lcl_addr))
667 			reset_vif(vifp);
668 	}
669 
670 	numvifs = 0;
671 	pim_assert = 0;
672 	mrt_api_config = 0;
673 
674 	callout_stop(&expire_upcalls_ch);
675 	callout_stop(&bw_upcalls_ch);
676 	callout_stop(&bw_meter_ch);
677 
678 	/*
679 	 * Free all multicast forwarding cache entries.
680 	 */
681 	for (i = 0; i < MFCTBLSIZ; i++) {
682 		struct mfc *rt, *nrt;
683 
684 		for (rt = LIST_FIRST(&mfchashtbl[i]); rt; rt = nrt) {
685 			nrt = LIST_NEXT(rt, mfc_hash);
686 
687 			expire_mfc(rt);
688 		}
689 	}
690 
691 	bzero((caddr_t)nexpire, sizeof(nexpire));
692 	free(mfchashtbl, M_MRTABLE);
693 	mfchashtbl = NULL;
694 
695 	bw_upcalls_n = 0;
696 	bzero(bw_meter_timers, sizeof(bw_meter_timers));
697 
698 	/* Reset de-encapsulation cache. */
699 
700 	ip_mrouter = NULL;
701 
702 	splx(s);
703 
704 	if (mrtdebug)
705 		log(LOG_DEBUG, "ip_mrouter_done\n");
706 
707 	return (0);
708 }
709 
710 void
711 ip_mrouter_detach(struct ifnet *ifp)
712 {
713 	int vifi, i;
714 	struct vif *vifp;
715 	struct mfc *rt;
716 	struct rtdetq *rte;
717 
718 	/* XXX not sure about side effect to userland routing daemon */
719 	for (vifi = 0; vifi < numvifs; vifi++) {
720 		vifp = &viftable[vifi];
721 		if (vifp->v_ifp == ifp)
722 			reset_vif(vifp);
723 	}
724 	for (i = 0; i < MFCTBLSIZ; i++) {
725 		if (nexpire[i] == 0)
726 			continue;
727 		LIST_FOREACH(rt, &mfchashtbl[i], mfc_hash) {
728 			for (rte = rt->mfc_stall; rte; rte = rte->next) {
729 				if (rte->ifp == ifp)
730 					rte->ifp = NULL;
731 			}
732 		}
733 	}
734 }
735 
736 static int
737 get_version(struct mbuf *m)
738 {
739 	int *v = mtod(m, int *);
740 
741 	*v = 0x0305;	/* XXX !!!! */
742 	m->m_len = sizeof(int);
743 	return (0);
744 }
745 
746 /*
747  * Set PIM assert processing global
748  */
749 static int
750 set_assert(struct mbuf *m)
751 {
752 	int *i;
753 
754 	if (m == NULL || m->m_len < sizeof(int))
755 		return (EINVAL);
756 
757 	i = mtod(m, int *);
758 	pim_assert = !!*i;
759 	return (0);
760 }
761 
762 /*
763  * Get PIM assert processing global
764  */
765 static int
766 get_assert(struct mbuf *m)
767 {
768 	int *i = mtod(m, int *);
769 
770 	*i = pim_assert;
771 	m->m_len = sizeof(int);
772 	return (0);
773 }
774 
775 /*
776  * Configure API capabilities
777  */
778 static int
779 set_api_config(struct mbuf *m)
780 {
781 	int i;
782 	u_int32_t *apival;
783 
784 	if (m == NULL || m->m_len < sizeof(u_int32_t))
785 		return (EINVAL);
786 
787 	apival = mtod(m, u_int32_t *);
788 
789 	/*
790 	 * We can set the API capabilities only if it is the first operation
791 	 * after MRT_INIT. I.e.:
792 	 *  - there are no vifs installed
793 	 *  - pim_assert is not enabled
794 	 *  - the MFC table is empty
795 	 */
796 	if (numvifs > 0) {
797 		*apival = 0;
798 		return (EPERM);
799 	}
800 	if (pim_assert) {
801 		*apival = 0;
802 		return (EPERM);
803 	}
804 	for (i = 0; i < MFCTBLSIZ; i++) {
805 		if (LIST_FIRST(&mfchashtbl[i]) != NULL) {
806 			*apival = 0;
807 			return (EPERM);
808 		}
809 	}
810 
811 	mrt_api_config = *apival & mrt_api_support;
812 	*apival = mrt_api_config;
813 
814 	return (0);
815 }
816 
817 /*
818  * Get API capabilities
819  */
820 static int
821 get_api_support(struct mbuf *m)
822 {
823 	u_int32_t *apival;
824 
825 	if (m == NULL || m->m_len < sizeof(u_int32_t))
826 		return (EINVAL);
827 
828 	apival = mtod(m, u_int32_t *);
829 
830 	*apival = mrt_api_support;
831 
832 	return (0);
833 }
834 
835 /*
836  * Get API configured capabilities
837  */
838 static int
839 get_api_config(struct mbuf *m)
840 {
841 	u_int32_t *apival;
842 
843 	if (m == NULL || m->m_len < sizeof(u_int32_t))
844 		return (EINVAL);
845 
846 	apival = mtod(m, u_int32_t *);
847 
848 	*apival = mrt_api_config;
849 
850 	return (0);
851 }
852 
853 static struct sockaddr_in sin = {
854 	.sin_len = sizeof(sin),
855 	.sin_family = AF_INET
856 };
857 
858 /*
859  * Add a vif to the vif table
860  */
861 static int
862 add_vif(struct mbuf *m)
863 {
864 	struct vifctl *vifcp;
865 	struct vif *vifp;
866 	struct ifaddr *ifa;
867 	struct ifnet *ifp;
868 	struct ifreq ifr;
869 	int error, s;
870 
871 	if (m == NULL || m->m_len < sizeof(struct vifctl))
872 		return (EINVAL);
873 
874 	vifcp = mtod(m, struct vifctl *);
875 	if (vifcp->vifc_vifi >= MAXVIFS)
876 		return (EINVAL);
877 	if (in_nullhost(vifcp->vifc_lcl_addr))
878 		return (EADDRNOTAVAIL);
879 
880 	vifp = &viftable[vifcp->vifc_vifi];
881 	if (!in_nullhost(vifp->v_lcl_addr))
882 		return (EADDRINUSE);
883 
884 	/* Find the interface with an address in AF_INET family. */
885 #ifdef PIM
886 	if (vifcp->vifc_flags & VIFF_REGISTER) {
887 		/*
888 		 * XXX: Because VIFF_REGISTER does not really need a valid
889 		 * local interface (e.g. it could be 127.0.0.2), we don't
890 		 * check its address.
891 		 */
892 	    ifp = NULL;
893 	} else
894 #endif
895 	{
896 		sin.sin_addr = vifcp->vifc_lcl_addr;
897 		ifa = ifa_ifwithaddr(sintosa(&sin));
898 		if (ifa == NULL)
899 			return (EADDRNOTAVAIL);
900 		ifp = ifa->ifa_ifp;
901 	}
902 
903 	if (vifcp->vifc_flags & VIFF_TUNNEL) {
904 		if (vifcp->vifc_flags & VIFF_SRCRT) {
905 			log(LOG_ERR, "source routed tunnels not supported\n");
906 			return (EOPNOTSUPP);
907 		}
908 
909 		/* attach this vif to decapsulator dispatch table */
910 		/*
911 		 * XXX Use addresses in registration so that matching
912 		 * can be done with radix tree in decapsulator.  But,
913 		 * we need to check inner header for multicast, so
914 		 * this requires both radix tree lookup and then a
915 		 * function to check, and this is not supported yet.
916 		 */
917 		vifp->v_encap_cookie = encap_attach_func(AF_INET, IPPROTO_IPV4,
918 		    vif_encapcheck, &vif_protosw, vifp);
919 		if (!vifp->v_encap_cookie)
920 			return (EINVAL);
921 
922 		/* Create a fake encapsulation interface. */
923 		ifp = (struct ifnet *)malloc(sizeof(*ifp), M_MRTABLE, M_WAITOK);
924 		bzero(ifp, sizeof(*ifp));
925 		snprintf(ifp->if_xname, sizeof(ifp->if_xname),
926 			 "mdecap%d", vifcp->vifc_vifi);
927 
928 		/* Prepare cached route entry. */
929 		bzero(&vifp->v_route, sizeof(vifp->v_route));
930 #ifdef PIM
931 	} else if (vifcp->vifc_flags & VIFF_REGISTER) {
932 		ifp = &multicast_register_if;
933 		if (mrtdebug)
934 			log(LOG_DEBUG, "Adding a register vif, ifp: %p\n",
935 			    (void *)ifp);
936 		if (reg_vif_num == VIFI_INVALID) {
937 			bzero(ifp, sizeof(*ifp));
938 			snprintf(ifp->if_xname, sizeof(ifp->if_xname),
939 				 "register_vif");
940 			ifp->if_flags = IFF_LOOPBACK;
941 			bzero(&vifp->v_route, sizeof(vifp->v_route));
942 			reg_vif_num = vifcp->vifc_vifi;
943 		}
944 #endif
945 	} else {
946 		/* Make sure the interface supports multicast. */
947 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
948 			return (EOPNOTSUPP);
949 
950 		/* Enable promiscuous reception of all IP multicasts. */
951 		satosin(&ifr.ifr_addr)->sin_len = sizeof(struct sockaddr_in);
952 		satosin(&ifr.ifr_addr)->sin_family = AF_INET;
953 		satosin(&ifr.ifr_addr)->sin_addr = zeroin_addr;
954 		error = (*ifp->if_ioctl)(ifp, SIOCADDMULTI, (caddr_t)&ifr);
955 		if (error)
956 			return (error);
957 	}
958 
959 	s = splsoftnet();
960 
961 	/* Define parameters for the tbf structure. */
962 	vifp->tbf_q = NULL;
963 	vifp->tbf_t = &vifp->tbf_q;
964 	microtime(&vifp->tbf_last_pkt_t);
965 	vifp->tbf_n_tok = 0;
966 	vifp->tbf_q_len = 0;
967 	vifp->tbf_max_q_len = MAXQSIZE;
968 
969 	vifp->v_flags = vifcp->vifc_flags;
970 	vifp->v_threshold = vifcp->vifc_threshold;
971 	/* scaling up here allows division by 1024 in critical code */
972 	vifp->v_rate_limit = vifcp->vifc_rate_limit * 1024 / 1000;
973 	vifp->v_lcl_addr = vifcp->vifc_lcl_addr;
974 	vifp->v_rmt_addr = vifcp->vifc_rmt_addr;
975 	vifp->v_ifp = ifp;
976 	/* Initialize per vif pkt counters. */
977 	vifp->v_pkt_in = 0;
978 	vifp->v_pkt_out = 0;
979 	vifp->v_bytes_in = 0;
980 	vifp->v_bytes_out = 0;
981 
982 	callout_init(&vifp->v_repq_ch);
983 
984 #ifdef RSVP_ISI
985 	vifp->v_rsvp_on = 0;
986 	vifp->v_rsvpd = NULL;
987 #endif /* RSVP_ISI */
988 
989 	splx(s);
990 
991 	/* Adjust numvifs up if the vifi is higher than numvifs. */
992 	if (numvifs <= vifcp->vifc_vifi)
993 		numvifs = vifcp->vifc_vifi + 1;
994 
995 	if (mrtdebug)
996 		log(LOG_DEBUG, "add_vif #%d, lcladdr %x, %s %x, thresh %x, rate %d\n",
997 		    vifcp->vifc_vifi,
998 		    ntohl(vifcp->vifc_lcl_addr.s_addr),
999 		    (vifcp->vifc_flags & VIFF_TUNNEL) ? "rmtaddr" : "mask",
1000 		    ntohl(vifcp->vifc_rmt_addr.s_addr),
1001 		    vifcp->vifc_threshold,
1002 		    vifcp->vifc_rate_limit);
1003 
1004 	return (0);
1005 }
1006 
1007 void
1008 reset_vif(struct vif *vifp)
1009 {
1010 	struct mbuf *m, *n;
1011 	struct ifnet *ifp;
1012 	struct ifreq ifr;
1013 
1014 	callout_stop(&vifp->v_repq_ch);
1015 
1016 	/* detach this vif from decapsulator dispatch table */
1017 	encap_detach(vifp->v_encap_cookie);
1018 	vifp->v_encap_cookie = NULL;
1019 
1020 	/*
1021 	 * Free packets queued at the interface
1022 	 */
1023 	for (m = vifp->tbf_q; m != NULL; m = n) {
1024 		n = m->m_nextpkt;
1025 		m_freem(m);
1026 	}
1027 
1028 	if (vifp->v_flags & VIFF_TUNNEL)
1029 		free(vifp->v_ifp, M_MRTABLE);
1030 	else if (vifp->v_flags & VIFF_REGISTER) {
1031 #ifdef PIM
1032 		reg_vif_num = VIFI_INVALID;
1033 #endif
1034 	} else {
1035 		satosin(&ifr.ifr_addr)->sin_len = sizeof(struct sockaddr_in);
1036 		satosin(&ifr.ifr_addr)->sin_family = AF_INET;
1037 		satosin(&ifr.ifr_addr)->sin_addr = zeroin_addr;
1038 		ifp = vifp->v_ifp;
1039 		(*ifp->if_ioctl)(ifp, SIOCDELMULTI, (caddr_t)&ifr);
1040 	}
1041 	bzero((caddr_t)vifp, sizeof(*vifp));
1042 }
1043 
1044 /*
1045  * Delete a vif from the vif table
1046  */
1047 static int
1048 del_vif(struct mbuf *m)
1049 {
1050 	vifi_t *vifip;
1051 	struct vif *vifp;
1052 	vifi_t vifi;
1053 	int s;
1054 
1055 	if (m == NULL || m->m_len < sizeof(vifi_t))
1056 		return (EINVAL);
1057 
1058 	vifip = mtod(m, vifi_t *);
1059 	if (*vifip >= numvifs)
1060 		return (EINVAL);
1061 
1062 	vifp = &viftable[*vifip];
1063 	if (in_nullhost(vifp->v_lcl_addr))
1064 		return (EADDRNOTAVAIL);
1065 
1066 	s = splsoftnet();
1067 
1068 	reset_vif(vifp);
1069 
1070 	/* Adjust numvifs down */
1071 	for (vifi = numvifs; vifi > 0; vifi--)
1072 		if (!in_nullhost(viftable[vifi - 1].v_lcl_addr))
1073 			break;
1074 	numvifs = vifi;
1075 
1076 	splx(s);
1077 
1078 	if (mrtdebug)
1079 		log(LOG_DEBUG, "del_vif %d, numvifs %d\n", *vifip, numvifs);
1080 
1081 	return (0);
1082 }
1083 
1084 /*
1085  * update an mfc entry without resetting counters and S,G addresses.
1086  */
1087 static void
1088 update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1089 {
1090 	int i;
1091 
1092 	rt->mfc_parent = mfccp->mfcc_parent;
1093 	for (i = 0; i < numvifs; i++) {
1094 		rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1095 		rt->mfc_flags[i] = mfccp->mfcc_flags[i] & mrt_api_config &
1096 			MRT_MFC_FLAGS_ALL;
1097 	}
1098 	/* set the RP address */
1099 	if (mrt_api_config & MRT_MFC_RP)
1100 		rt->mfc_rp = mfccp->mfcc_rp;
1101 	else
1102 		rt->mfc_rp = zeroin_addr;
1103 }
1104 
1105 /*
1106  * fully initialize an mfc entry from the parameter.
1107  */
1108 static void
1109 init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1110 {
1111 	rt->mfc_origin     = mfccp->mfcc_origin;
1112 	rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
1113 
1114 	update_mfc_params(rt, mfccp);
1115 
1116 	/* initialize pkt counters per src-grp */
1117 	rt->mfc_pkt_cnt    = 0;
1118 	rt->mfc_byte_cnt   = 0;
1119 	rt->mfc_wrong_if   = 0;
1120 	timerclear(&rt->mfc_last_assert);
1121 }
1122 
1123 static void
1124 expire_mfc(struct mfc *rt)
1125 {
1126 	struct rtdetq *rte, *nrte;
1127 
1128 	free_bw_list(rt->mfc_bw_meter);
1129 
1130 	for (rte = rt->mfc_stall; rte != NULL; rte = nrte) {
1131 		nrte = rte->next;
1132 		m_freem(rte->m);
1133 		free(rte, M_MRTABLE);
1134 	}
1135 
1136 	LIST_REMOVE(rt, mfc_hash);
1137 	free(rt, M_MRTABLE);
1138 }
1139 
1140 /*
1141  * Add an mfc entry
1142  */
1143 static int
1144 add_mfc(struct mbuf *m)
1145 {
1146 	struct mfcctl2 mfcctl2;
1147 	struct mfcctl2 *mfccp;
1148 	struct mfc *rt;
1149 	u_int32_t hash = 0;
1150 	struct rtdetq *rte, *nrte;
1151 	u_short nstl;
1152 	int s;
1153 	int mfcctl_size = sizeof(struct mfcctl);
1154 
1155 	if (mrt_api_config & MRT_API_FLAGS_ALL)
1156 		mfcctl_size = sizeof(struct mfcctl2);
1157 
1158 	if (m == NULL || m->m_len < mfcctl_size)
1159 		return (EINVAL);
1160 
1161 	/*
1162 	 * select data size depending on API version.
1163 	 */
1164 	if (mrt_api_config & MRT_API_FLAGS_ALL) {
1165 		struct mfcctl2 *mp2 = mtod(m, struct mfcctl2 *);
1166 		bcopy(mp2, (caddr_t)&mfcctl2, sizeof(*mp2));
1167 	} else {
1168 		struct mfcctl *mp = mtod(m, struct mfcctl *);
1169 		bcopy(mp, (caddr_t)&mfcctl2, sizeof(*mp));
1170 		bzero((caddr_t)&mfcctl2 + sizeof(struct mfcctl),
1171 		      sizeof(mfcctl2) - sizeof(struct mfcctl));
1172 	}
1173 	mfccp = &mfcctl2;
1174 
1175 	s = splsoftnet();
1176 	rt = mfc_find(&mfccp->mfcc_origin, &mfccp->mfcc_mcastgrp);
1177 
1178 	/* If an entry already exists, just update the fields */
1179 	if (rt) {
1180 		if (mrtdebug & DEBUG_MFC)
1181 			log(LOG_DEBUG, "add_mfc update o %x g %x p %x\n",
1182 			    ntohl(mfccp->mfcc_origin.s_addr),
1183 			    ntohl(mfccp->mfcc_mcastgrp.s_addr),
1184 			    mfccp->mfcc_parent);
1185 
1186 		update_mfc_params(rt, mfccp);
1187 
1188 		splx(s);
1189 		return (0);
1190 	}
1191 
1192 	/*
1193 	 * Find the entry for which the upcall was made and update
1194 	 */
1195 	nstl = 0;
1196 	hash = MFCHASH(mfccp->mfcc_origin, mfccp->mfcc_mcastgrp);
1197 	LIST_FOREACH(rt, &mfchashtbl[hash], mfc_hash) {
1198 		if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1199 		    in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp) &&
1200 		    rt->mfc_stall != NULL) {
1201 			if (nstl++)
1202 				log(LOG_ERR, "add_mfc %s o %x g %x p %x dbx %p\n",
1203 				    "multiple kernel entries",
1204 				    ntohl(mfccp->mfcc_origin.s_addr),
1205 				    ntohl(mfccp->mfcc_mcastgrp.s_addr),
1206 				    mfccp->mfcc_parent, rt->mfc_stall);
1207 
1208 			if (mrtdebug & DEBUG_MFC)
1209 				log(LOG_DEBUG, "add_mfc o %x g %x p %x dbg %p\n",
1210 				    ntohl(mfccp->mfcc_origin.s_addr),
1211 				    ntohl(mfccp->mfcc_mcastgrp.s_addr),
1212 				    mfccp->mfcc_parent, rt->mfc_stall);
1213 
1214 			rte = rt->mfc_stall;
1215 			init_mfc_params(rt, mfccp);
1216 			rt->mfc_stall = NULL;
1217 
1218 			rt->mfc_expire = 0; /* Don't clean this guy up */
1219 			nexpire[hash]--;
1220 
1221 			/* free packets Qed at the end of this entry */
1222 			for (; rte != NULL; rte = nrte) {
1223 				nrte = rte->next;
1224 				if (rte->ifp) {
1225 #ifdef RSVP_ISI
1226 					ip_mdq(rte->m, rte->ifp, rt, -1);
1227 #else
1228 					ip_mdq(rte->m, rte->ifp, rt);
1229 #endif /* RSVP_ISI */
1230 				}
1231 				m_freem(rte->m);
1232 #ifdef UPCALL_TIMING
1233 				collate(&rte->t);
1234 #endif /* UPCALL_TIMING */
1235 				free(rte, M_MRTABLE);
1236 			}
1237 		}
1238 	}
1239 
1240 	/*
1241 	 * It is possible that an entry is being inserted without an upcall
1242 	 */
1243 	if (nstl == 0) {
1244 		/*
1245 		 * No mfc; make a new one
1246 		 */
1247 		if (mrtdebug & DEBUG_MFC)
1248 			log(LOG_DEBUG, "add_mfc no upcall o %x g %x p %x\n",
1249 			    ntohl(mfccp->mfcc_origin.s_addr),
1250 			    ntohl(mfccp->mfcc_mcastgrp.s_addr),
1251 			    mfccp->mfcc_parent);
1252 
1253 		LIST_FOREACH(rt, &mfchashtbl[hash], mfc_hash) {
1254 			if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1255 			    in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp)) {
1256 				init_mfc_params(rt, mfccp);
1257 				if (rt->mfc_expire)
1258 					nexpire[hash]--;
1259 				rt->mfc_expire = 0;
1260 				break; /* XXX */
1261 			}
1262 		}
1263 		if (rt == NULL) {	/* no upcall, so make a new entry */
1264 			rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE,
1265 						  M_NOWAIT);
1266 			if (rt == NULL) {
1267 				splx(s);
1268 				return (ENOBUFS);
1269 			}
1270 
1271 			init_mfc_params(rt, mfccp);
1272 			rt->mfc_expire	= 0;
1273 			rt->mfc_stall	= NULL;
1274 			rt->mfc_bw_meter = NULL;
1275 
1276 			/* insert new entry at head of hash chain */
1277 			LIST_INSERT_HEAD(&mfchashtbl[hash], rt, mfc_hash);
1278 		}
1279 	}
1280 
1281 	splx(s);
1282 	return (0);
1283 }
1284 
1285 #ifdef UPCALL_TIMING
1286 /*
1287  * collect delay statistics on the upcalls
1288  */
1289 static void
1290 collate(struct timeval *t)
1291 {
1292 	u_int32_t d;
1293 	struct timeval tp;
1294 	u_int32_t delta;
1295 
1296 	microtime(&tp);
1297 
1298 	if (timercmp(t, &tp, <)) {
1299 		TV_DELTA(tp, *t, delta);
1300 
1301 		d = delta >> 10;
1302 		if (d > 50)
1303 			d = 50;
1304 
1305 		++upcall_data[d];
1306 	}
1307 }
1308 #endif /* UPCALL_TIMING */
1309 
1310 /*
1311  * Delete an mfc entry
1312  */
1313 static int
1314 del_mfc(struct mbuf *m)
1315 {
1316 	struct mfcctl2 mfcctl2;
1317 	struct mfcctl2 *mfccp;
1318 	struct mfc *rt;
1319 	int s;
1320 	int mfcctl_size = sizeof(struct mfcctl);
1321 	struct mfcctl *mp = mtod(m, struct mfcctl *);
1322 
1323 	/*
1324 	 * XXX: for deleting MFC entries the information in entries
1325 	 * of size "struct mfcctl" is sufficient.
1326 	 */
1327 
1328 	if (m == NULL || m->m_len < mfcctl_size)
1329 		return (EINVAL);
1330 
1331 	bcopy(mp, (caddr_t)&mfcctl2, sizeof(*mp));
1332 	bzero((caddr_t)&mfcctl2 + sizeof(struct mfcctl),
1333 	      sizeof(mfcctl2) - sizeof(struct mfcctl));
1334 
1335 	mfccp = &mfcctl2;
1336 
1337 	if (mrtdebug & DEBUG_MFC)
1338 		log(LOG_DEBUG, "del_mfc origin %x mcastgrp %x\n",
1339 		    ntohl(mfccp->mfcc_origin.s_addr),
1340 		    ntohl(mfccp->mfcc_mcastgrp.s_addr));
1341 
1342 	s = splsoftnet();
1343 
1344 	rt = mfc_find(&mfccp->mfcc_origin, &mfccp->mfcc_mcastgrp);
1345 	if (rt == NULL) {
1346 		splx(s);
1347 		return (EADDRNOTAVAIL);
1348 	}
1349 
1350 	/*
1351 	 * free the bw_meter entries
1352 	 */
1353 	free_bw_list(rt->mfc_bw_meter);
1354 	rt->mfc_bw_meter = NULL;
1355 
1356 	LIST_REMOVE(rt, mfc_hash);
1357 	free(rt, M_MRTABLE);
1358 
1359 	splx(s);
1360 	return (0);
1361 }
1362 
1363 static int
1364 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1365 {
1366 	if (s) {
1367 		if (sbappendaddr(&s->so_rcv, sintosa(src), mm,
1368 		    (struct mbuf *)NULL) != 0) {
1369 			sorwakeup(s);
1370 			return (0);
1371 		}
1372 	}
1373 	m_freem(mm);
1374 	return (-1);
1375 }
1376 
1377 /*
1378  * IP multicast forwarding function. This function assumes that the packet
1379  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1380  * pointed to by "ifp", and the packet is to be relayed to other networks
1381  * that have members of the packet's destination IP multicast group.
1382  *
1383  * The packet is returned unscathed to the caller, unless it is
1384  * erroneous, in which case a non-zero return value tells the caller to
1385  * discard it.
1386  */
1387 
1388 #define IP_HDR_LEN  20	/* # bytes of fixed IP header (excluding options) */
1389 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1390 
1391 int
1392 #ifdef RSVP_ISI
1393 ip_mforward(struct mbuf *m, struct ifnet *ifp, struct ip_moptions *imo)
1394 #else
1395 ip_mforward(struct mbuf *m, struct ifnet *ifp)
1396 #endif /* RSVP_ISI */
1397 {
1398 	struct ip *ip = mtod(m, struct ip *);
1399 	struct mfc *rt;
1400 	static int srctun = 0;
1401 	struct mbuf *mm;
1402 	int s;
1403 	vifi_t vifi;
1404 
1405 	if (mrtdebug & DEBUG_FORWARD)
1406 		log(LOG_DEBUG, "ip_mforward: src %x, dst %x, ifp %p\n",
1407 		    ntohl(ip->ip_src.s_addr), ntohl(ip->ip_dst.s_addr), ifp);
1408 
1409 	if (ip->ip_hl < (IP_HDR_LEN + TUNNEL_LEN) >> 2 ||
1410 	    ((u_char *)(ip + 1))[1] != IPOPT_LSRR) {
1411 		/*
1412 		 * Packet arrived via a physical interface or
1413 		 * an encapsulated tunnel or a register_vif.
1414 		 */
1415 	} else {
1416 		/*
1417 		 * Packet arrived through a source-route tunnel.
1418 		 * Source-route tunnels are no longer supported.
1419 		 */
1420 		if ((srctun++ % 1000) == 0)
1421 			log(LOG_ERR,
1422 			    "ip_mforward: received source-routed packet from %x\n",
1423 			    ntohl(ip->ip_src.s_addr));
1424 
1425 		return (1);
1426 	}
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_copy(m, 0, M_COPYALL);
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_copy(m, 0, hlen);
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 			sin.sin_addr = ip->ip_src;
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 __unused)
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 	int plen = ntohs(ip->ip_len) - (ip->ip_hl << 2);
1700 
1701 /*
1702  * Macro to send packet on vif.  Since RSVP packets don't get counted on
1703  * input, they shouldn't get counted on output, so statistics keeping is
1704  * separate.
1705  */
1706 #define MC_SEND(ip, vifp, m) do {					\
1707 	if ((vifp)->v_flags & VIFF_TUNNEL)				\
1708 		encap_send((ip), (vifp), (m));				\
1709 	else								\
1710 		phyint_send((ip), (vifp), (m));				\
1711 } while (/*CONSTCOND*/ 0)
1712 
1713 #ifdef RSVP_ISI
1714 	/*
1715 	 * If xmt_vif is not -1, send on only the requested vif.
1716 	 *
1717 	 * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.
1718 	 */
1719 	if (xmt_vif < numvifs) {
1720 #ifdef PIM
1721 		if (viftable[xmt_vif].v_flags & VIFF_REGISTER)
1722 			pim_register_send(ip, viftable + xmt_vif, m, rt);
1723 		else
1724 #endif
1725 		MC_SEND(ip, viftable + xmt_vif, m);
1726 		return (1);
1727 	}
1728 #endif /* RSVP_ISI */
1729 
1730 	/*
1731 	 * Don't forward if it didn't arrive from the parent vif for its origin.
1732 	 */
1733 	vifi = rt->mfc_parent;
1734 	if ((vifi >= numvifs) || (viftable[vifi].v_ifp != ifp)) {
1735 		/* came in the wrong interface */
1736 		if (mrtdebug & DEBUG_FORWARD)
1737 			log(LOG_DEBUG, "wrong if: ifp %p vifi %d vififp %p\n",
1738 			    ifp, vifi,
1739 			    vifi >= numvifs ? 0 : viftable[vifi].v_ifp);
1740 		++mrtstat.mrts_wrong_if;
1741 		++rt->mfc_wrong_if;
1742 		/*
1743 		 * If we are doing PIM assert processing, send a message
1744 		 * to the routing daemon.
1745 		 *
1746 		 * XXX: A PIM-SM router needs the WRONGVIF detection so it
1747 		 * can complete the SPT switch, regardless of the type
1748 		 * of the iif (broadcast media, GRE tunnel, etc).
1749 		 */
1750 		if (pim_assert && (vifi < numvifs) && viftable[vifi].v_ifp) {
1751 			struct timeval now;
1752 			u_int32_t delta;
1753 
1754 #ifdef PIM
1755 			if (ifp == &multicast_register_if)
1756 				pimstat.pims_rcv_registers_wrongiif++;
1757 #endif
1758 
1759 			/* Get vifi for the incoming packet */
1760 			for (vifi = 0;
1761 			     vifi < numvifs && viftable[vifi].v_ifp != ifp;
1762 			     vifi++)
1763 			    ;
1764 			if (vifi >= numvifs) {
1765 				/* The iif is not found: ignore the packet. */
1766 				return (0);
1767 			}
1768 
1769 			if (rt->mfc_flags[vifi] &
1770 			    MRT_MFC_FLAGS_DISABLE_WRONGVIF) {
1771 				/* WRONGVIF disabled: ignore the packet */
1772 				return (0);
1773 			}
1774 
1775 			microtime(&now);
1776 
1777 			TV_DELTA(rt->mfc_last_assert, now, delta);
1778 
1779 			if (delta > ASSERT_MSG_TIME) {
1780 				struct igmpmsg *im;
1781 				int hlen = ip->ip_hl << 2;
1782 				struct mbuf *mm = m_copy(m, 0, hlen);
1783 
1784 				M_PULLUP(mm, hlen);
1785 				if (mm == NULL)
1786 					return (ENOBUFS);
1787 
1788 				rt->mfc_last_assert = now;
1789 
1790 				im = mtod(mm, struct igmpmsg *);
1791 				im->im_msgtype	= IGMPMSG_WRONGVIF;
1792 				im->im_mbz	= 0;
1793 				im->im_vif	= vifi;
1794 
1795 				mrtstat.mrts_upcalls++;
1796 
1797 				sin.sin_addr = im->im_src;
1798 				if (socket_send(ip_mrouter, mm, &sin) < 0) {
1799 					log(LOG_WARNING,
1800 					    "ip_mforward: ip_mrouter socket queue full\n");
1801 					++mrtstat.mrts_upq_sockfull;
1802 					return (ENOBUFS);
1803 				}
1804 			}
1805 		}
1806 		return (0);
1807 	}
1808 
1809 	/* If I sourced this packet, it counts as output, else it was input. */
1810 	if (in_hosteq(ip->ip_src, viftable[vifi].v_lcl_addr)) {
1811 		viftable[vifi].v_pkt_out++;
1812 		viftable[vifi].v_bytes_out += plen;
1813 	} else {
1814 		viftable[vifi].v_pkt_in++;
1815 		viftable[vifi].v_bytes_in += plen;
1816 	}
1817 	rt->mfc_pkt_cnt++;
1818 	rt->mfc_byte_cnt += plen;
1819 
1820 	/*
1821 	 * For each vif, decide if a copy of the packet should be forwarded.
1822 	 * Forward if:
1823 	 *		- the ttl exceeds the vif's threshold
1824 	 *		- there are group members downstream on interface
1825 	 */
1826 	for (vifp = viftable, vifi = 0; vifi < numvifs; vifp++, vifi++)
1827 		if ((rt->mfc_ttls[vifi] > 0) &&
1828 			(ip->ip_ttl > rt->mfc_ttls[vifi])) {
1829 			vifp->v_pkt_out++;
1830 			vifp->v_bytes_out += plen;
1831 #ifdef PIM
1832 			if (vifp->v_flags & VIFF_REGISTER)
1833 				pim_register_send(ip, vifp, m, rt);
1834 			else
1835 #endif
1836 			MC_SEND(ip, vifp, m);
1837 		}
1838 
1839 	/*
1840 	 * Perform upcall-related bw measuring.
1841 	 */
1842 	if (rt->mfc_bw_meter != NULL) {
1843 		struct bw_meter *x;
1844 		struct timeval now;
1845 
1846 		microtime(&now);
1847 		for (x = rt->mfc_bw_meter; x != NULL; x = x->bm_mfc_next)
1848 			bw_meter_receive_packet(x, plen, &now);
1849 	}
1850 
1851 	return (0);
1852 }
1853 
1854 #ifdef RSVP_ISI
1855 /*
1856  * check if a vif number is legal/ok. This is used by ip_output.
1857  */
1858 int
1859 legal_vif_num(int vif)
1860 {
1861 	if (vif >= 0 && vif < numvifs)
1862 		return (1);
1863 	else
1864 		return (0);
1865 }
1866 #endif /* RSVP_ISI */
1867 
1868 static void
1869 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1870 {
1871 	struct mbuf *mb_copy;
1872 	int hlen = ip->ip_hl << 2;
1873 
1874 	/*
1875 	 * Make a new reference to the packet; make sure that
1876 	 * the IP header is actually copied, not just referenced,
1877 	 * so that ip_output() only scribbles on the copy.
1878 	 */
1879 	mb_copy = m_copy(m, 0, M_COPYALL);
1880 	M_PULLUP(mb_copy, hlen);
1881 	if (mb_copy == NULL)
1882 		return;
1883 
1884 	if (vifp->v_rate_limit <= 0)
1885 		tbf_send_packet(vifp, mb_copy);
1886 	else
1887 		tbf_control(vifp, mb_copy, mtod(mb_copy, struct ip *),
1888 		    ntohs(ip->ip_len));
1889 }
1890 
1891 static void
1892 encap_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1893 {
1894 	struct mbuf *mb_copy;
1895 	struct ip *ip_copy;
1896 	int i, len = ntohs(ip->ip_len) + sizeof(multicast_encap_iphdr);
1897 
1898 	/* Take care of delayed checksums */
1899 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
1900 		in_delayed_cksum(m);
1901 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
1902 	}
1903 
1904 	/*
1905 	 * copy the old packet & pullup it's IP header into the
1906 	 * new mbuf so we can modify it.  Try to fill the new
1907 	 * mbuf since if we don't the ethernet driver will.
1908 	 */
1909 	MGETHDR(mb_copy, M_DONTWAIT, MT_DATA);
1910 	if (mb_copy == NULL)
1911 		return;
1912 	mb_copy->m_data += max_linkhdr;
1913 	mb_copy->m_pkthdr.len = len;
1914 	mb_copy->m_len = sizeof(multicast_encap_iphdr);
1915 
1916 	if ((mb_copy->m_next = m_copy(m, 0, M_COPYALL)) == NULL) {
1917 		m_freem(mb_copy);
1918 		return;
1919 	}
1920 	i = MHLEN - max_linkhdr;
1921 	if (i > len)
1922 		i = len;
1923 	mb_copy = m_pullup(mb_copy, i);
1924 	if (mb_copy == NULL)
1925 		return;
1926 
1927 	/*
1928 	 * fill in the encapsulating IP header.
1929 	 */
1930 	ip_copy = mtod(mb_copy, struct ip *);
1931 	*ip_copy = multicast_encap_iphdr;
1932 	ip_copy->ip_id = ip_newid();
1933 	ip_copy->ip_len = htons(len);
1934 	ip_copy->ip_src = vifp->v_lcl_addr;
1935 	ip_copy->ip_dst = vifp->v_rmt_addr;
1936 
1937 	/*
1938 	 * turn the encapsulated IP header back into a valid one.
1939 	 */
1940 	ip = (struct ip *)((caddr_t)ip_copy + sizeof(multicast_encap_iphdr));
1941 	--ip->ip_ttl;
1942 	ip->ip_sum = 0;
1943 	mb_copy->m_data += sizeof(multicast_encap_iphdr);
1944 	ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
1945 	mb_copy->m_data -= sizeof(multicast_encap_iphdr);
1946 
1947 	if (vifp->v_rate_limit <= 0)
1948 		tbf_send_packet(vifp, mb_copy);
1949 	else
1950 		tbf_control(vifp, mb_copy, ip, ntohs(ip_copy->ip_len));
1951 }
1952 
1953 /*
1954  * De-encapsulate a packet and feed it back through ip input.
1955  */
1956 static void
1957 vif_input(struct mbuf *m, ...)
1958 {
1959 	int off, proto;
1960 	va_list ap;
1961 	struct vif *vifp;
1962 	int s;
1963 	struct ifqueue *ifq;
1964 
1965 	va_start(ap, m);
1966 	off = va_arg(ap, int);
1967 	proto = va_arg(ap, int);
1968 	va_end(ap);
1969 
1970 	vifp = (struct vif *)encap_getarg(m);
1971 	if (!vifp || proto != ENCAP_PROTO) {
1972 		m_freem(m);
1973 		mrtstat.mrts_bad_tunnel++;
1974 		return;
1975 	}
1976 
1977 	m_adj(m, off);
1978 	m->m_pkthdr.rcvif = vifp->v_ifp;
1979 	ifq = &ipintrq;
1980 	s = splnet();
1981 	if (IF_QFULL(ifq)) {
1982 		IF_DROP(ifq);
1983 		m_freem(m);
1984 	} else {
1985 		IF_ENQUEUE(ifq, m);
1986 		/*
1987 		 * normally we would need a "schednetisr(NETISR_IP)"
1988 		 * here but we were called by ip_input and it is going
1989 		 * to loop back & try to dequeue the packet we just
1990 		 * queued as soon as we return so we avoid the
1991 		 * unnecessary software interrrupt.
1992 		 */
1993 	}
1994 	splx(s);
1995 }
1996 
1997 /*
1998  * Check if the packet should be received on the vif denoted by arg.
1999  * (The encap selection code will call this once per vif since each is
2000  * registered separately.)
2001  */
2002 static int
2003 vif_encapcheck(struct mbuf *m, int off, int proto, void *arg)
2004 {
2005 	struct vif *vifp;
2006 	struct ip ip;
2007 
2008 #ifdef DIAGNOSTIC
2009 	if (!arg || proto != IPPROTO_IPV4)
2010 		panic("unexpected arg in vif_encapcheck");
2011 #endif
2012 
2013 	/*
2014 	 * Accept the packet only if the inner heaader is multicast
2015 	 * and the outer header matches a tunnel-mode vif.  Order
2016 	 * checks in the hope that common non-matching packets will be
2017 	 * rejected quickly.  Assume that unicast IPv4 traffic in a
2018 	 * parallel tunnel (e.g. gif(4)) is unlikely.
2019 	 */
2020 
2021 	/* Obtain the outer IP header and the vif pointer. */
2022 	m_copydata((struct mbuf *)m, 0, sizeof(ip), (caddr_t)&ip);
2023 	vifp = (struct vif *)arg;
2024 
2025 	/*
2026 	 * The outer source must match the vif's remote peer address.
2027 	 * For a multicast router with several tunnels, this is the
2028 	 * only check that will fail on packets in other tunnels,
2029 	 * assuming the local address is the same.
2030 	 */
2031 	if (!in_hosteq(vifp->v_rmt_addr, ip.ip_src))
2032 		return 0;
2033 
2034 	/* The outer destination must match the vif's local address. */
2035 	if (!in_hosteq(vifp->v_lcl_addr, ip.ip_dst))
2036 		return 0;
2037 
2038 	/* The vif must be of tunnel type. */
2039 	if ((vifp->v_flags & VIFF_TUNNEL) == 0)
2040 		return 0;
2041 
2042 	/* Check that the inner destination is multicast. */
2043 	m_copydata((struct mbuf *)m, off, sizeof(ip), (caddr_t)&ip);
2044 	if (!IN_MULTICAST(ip.ip_dst.s_addr))
2045 		return 0;
2046 
2047 	/*
2048 	 * We have checked that both the outer src and dst addresses
2049 	 * match the vif, and that the inner destination is multicast
2050 	 * (224/5).  By claiming more than 64, we intend to
2051 	 * preferentially take packets that also match a parallel
2052 	 * gif(4).
2053 	 */
2054 	return 32 + 32 + 5;
2055 }
2056 
2057 /*
2058  * Token bucket filter module
2059  */
2060 static void
2061 tbf_control(struct vif *vifp, struct mbuf *m, struct ip *ip, u_int32_t len)
2062 {
2063 
2064 	if (len > MAX_BKT_SIZE) {
2065 		/* drop if packet is too large */
2066 		mrtstat.mrts_pkt2large++;
2067 		m_freem(m);
2068 		return;
2069 	}
2070 
2071 	tbf_update_tokens(vifp);
2072 
2073 	/*
2074 	 * If there are enough tokens, and the queue is empty, send this packet
2075 	 * out immediately.  Otherwise, try to insert it on this vif's queue.
2076 	 */
2077 	if (vifp->tbf_q_len == 0) {
2078 		if (len <= vifp->tbf_n_tok) {
2079 			vifp->tbf_n_tok -= len;
2080 			tbf_send_packet(vifp, m);
2081 		} else {
2082 			/* queue packet and timeout till later */
2083 			tbf_queue(vifp, m);
2084 			callout_reset(&vifp->v_repq_ch, TBF_REPROCESS,
2085 			    tbf_reprocess_q, vifp);
2086 		}
2087 	} else {
2088 		if (vifp->tbf_q_len >= vifp->tbf_max_q_len &&
2089 		    !tbf_dq_sel(vifp, ip)) {
2090 			/* queue full, and couldn't make room */
2091 			mrtstat.mrts_q_overflow++;
2092 			m_freem(m);
2093 		} else {
2094 			/* queue length low enough, or made room */
2095 			tbf_queue(vifp, m);
2096 			tbf_process_q(vifp);
2097 		}
2098 	}
2099 }
2100 
2101 /*
2102  * adds a packet to the queue at the interface
2103  */
2104 static void
2105 tbf_queue(struct vif *vifp, struct mbuf *m)
2106 {
2107 	int s = splsoftnet();
2108 
2109 	/* insert at tail */
2110 	*vifp->tbf_t = m;
2111 	vifp->tbf_t = &m->m_nextpkt;
2112 	vifp->tbf_q_len++;
2113 
2114 	splx(s);
2115 }
2116 
2117 
2118 /*
2119  * processes the queue at the interface
2120  */
2121 static void
2122 tbf_process_q(struct vif *vifp)
2123 {
2124 	struct mbuf *m;
2125 	int len;
2126 	int s = splsoftnet();
2127 
2128 	/*
2129 	 * Loop through the queue at the interface and send as many packets
2130 	 * as possible.
2131 	 */
2132 	for (m = vifp->tbf_q; m != NULL; m = vifp->tbf_q) {
2133 		len = ntohs(mtod(m, struct ip *)->ip_len);
2134 
2135 		/* determine if the packet can be sent */
2136 		if (len <= vifp->tbf_n_tok) {
2137 			/* if so,
2138 			 * reduce no of tokens, dequeue the packet,
2139 			 * send the packet.
2140 			 */
2141 			if ((vifp->tbf_q = m->m_nextpkt) == NULL)
2142 				vifp->tbf_t = &vifp->tbf_q;
2143 			--vifp->tbf_q_len;
2144 
2145 			m->m_nextpkt = NULL;
2146 			vifp->tbf_n_tok -= len;
2147 			tbf_send_packet(vifp, m);
2148 		} else
2149 			break;
2150 	}
2151 	splx(s);
2152 }
2153 
2154 static void
2155 tbf_reprocess_q(void *arg)
2156 {
2157 	struct vif *vifp = arg;
2158 
2159 	if (ip_mrouter == NULL)
2160 		return;
2161 
2162 	tbf_update_tokens(vifp);
2163 	tbf_process_q(vifp);
2164 
2165 	if (vifp->tbf_q_len != 0)
2166 		callout_reset(&vifp->v_repq_ch, TBF_REPROCESS,
2167 		    tbf_reprocess_q, vifp);
2168 }
2169 
2170 /* function that will selectively discard a member of the queue
2171  * based on the precedence value and the priority
2172  */
2173 static int
2174 tbf_dq_sel(struct vif *vifp, struct ip *ip)
2175 {
2176 	u_int p;
2177 	struct mbuf **mp, *m;
2178 	int s = splsoftnet();
2179 
2180 	p = priority(vifp, ip);
2181 
2182 	for (mp = &vifp->tbf_q, m = *mp;
2183 	    m != NULL;
2184 	    mp = &m->m_nextpkt, m = *mp) {
2185 		if (p > priority(vifp, mtod(m, struct ip *))) {
2186 			if ((*mp = m->m_nextpkt) == NULL)
2187 				vifp->tbf_t = mp;
2188 			--vifp->tbf_q_len;
2189 
2190 			m_freem(m);
2191 			mrtstat.mrts_drop_sel++;
2192 			splx(s);
2193 			return (1);
2194 		}
2195 	}
2196 	splx(s);
2197 	return (0);
2198 }
2199 
2200 static void
2201 tbf_send_packet(struct vif *vifp, struct mbuf *m)
2202 {
2203 	int error;
2204 	int s = splsoftnet();
2205 
2206 	if (vifp->v_flags & VIFF_TUNNEL) {
2207 		/* If tunnel options */
2208 		ip_output(m, (struct mbuf *)NULL, &vifp->v_route,
2209 		    IP_FORWARDING, (struct ip_moptions *)NULL,
2210 		    (struct socket *)NULL);
2211 	} else {
2212 		/* if physical interface option, extract the options and then send */
2213 		struct ip_moptions imo;
2214 
2215 		imo.imo_multicast_ifp = vifp->v_ifp;
2216 		imo.imo_multicast_ttl = mtod(m, struct ip *)->ip_ttl - 1;
2217 		imo.imo_multicast_loop = 1;
2218 #ifdef RSVP_ISI
2219 		imo.imo_multicast_vif = -1;
2220 #endif
2221 
2222 		error = ip_output(m, (struct mbuf *)NULL, (struct route *)NULL,
2223 		    IP_FORWARDING|IP_MULTICASTOPTS, &imo,
2224 		    (struct socket *)NULL);
2225 
2226 		if (mrtdebug & DEBUG_XMIT)
2227 			log(LOG_DEBUG, "phyint_send on vif %ld err %d\n",
2228 			    (long)(vifp - viftable), error);
2229 	}
2230 	splx(s);
2231 }
2232 
2233 /* determine the current time and then
2234  * the elapsed time (between the last time and time now)
2235  * in milliseconds & update the no. of tokens in the bucket
2236  */
2237 static void
2238 tbf_update_tokens(struct vif *vifp)
2239 {
2240 	struct timeval tp;
2241 	u_int32_t tm;
2242 	int s = splsoftnet();
2243 
2244 	microtime(&tp);
2245 
2246 	TV_DELTA(tp, vifp->tbf_last_pkt_t, tm);
2247 
2248 	/*
2249 	 * This formula is actually
2250 	 * "time in seconds" * "bytes/second".
2251 	 *
2252 	 * (tm / 1000000) * (v_rate_limit * 1000 * (1000/1024) / 8)
2253 	 *
2254 	 * The (1000/1024) was introduced in add_vif to optimize
2255 	 * this divide into a shift.
2256 	 */
2257 	vifp->tbf_n_tok += tm * vifp->v_rate_limit / 8192;
2258 	vifp->tbf_last_pkt_t = tp;
2259 
2260 	if (vifp->tbf_n_tok > MAX_BKT_SIZE)
2261 		vifp->tbf_n_tok = MAX_BKT_SIZE;
2262 
2263 	splx(s);
2264 }
2265 
2266 static int
2267 priority(struct vif *vifp __unused, struct ip *ip)
2268 {
2269 	int prio = 50;	/* the lowest priority -- default case */
2270 
2271 	/* temporary hack; may add general packet classifier some day */
2272 
2273 	/*
2274 	 * The UDP port space is divided up into four priority ranges:
2275 	 * [0, 16384)     : unclassified - lowest priority
2276 	 * [16384, 32768) : audio - highest priority
2277 	 * [32768, 49152) : whiteboard - medium priority
2278 	 * [49152, 65536) : video - low priority
2279 	 */
2280 	if (ip->ip_p == IPPROTO_UDP) {
2281 		struct udphdr *udp = (struct udphdr *)(((char *)ip) + (ip->ip_hl << 2));
2282 
2283 		switch (ntohs(udp->uh_dport) & 0xc000) {
2284 		case 0x4000:
2285 			prio = 70;
2286 			break;
2287 		case 0x8000:
2288 			prio = 60;
2289 			break;
2290 		case 0xc000:
2291 			prio = 55;
2292 			break;
2293 		}
2294 
2295 		if (tbfdebug > 1)
2296 			log(LOG_DEBUG, "port %x prio %d\n",
2297 			    ntohs(udp->uh_dport), prio);
2298 	}
2299 
2300 	return (prio);
2301 }
2302 
2303 /*
2304  * End of token bucket filter modifications
2305  */
2306 #ifdef RSVP_ISI
2307 int
2308 ip_rsvp_vif_init(struct socket *so, struct mbuf *m)
2309 {
2310 	int vifi, s;
2311 
2312 	if (rsvpdebug)
2313 		printf("ip_rsvp_vif_init: so_type = %d, pr_protocol = %d\n",
2314 		    so->so_type, so->so_proto->pr_protocol);
2315 
2316 	if (so->so_type != SOCK_RAW ||
2317 	    so->so_proto->pr_protocol != IPPROTO_RSVP)
2318 		return (EOPNOTSUPP);
2319 
2320 	/* Check mbuf. */
2321 	if (m == NULL || m->m_len != sizeof(int)) {
2322 		return (EINVAL);
2323 	}
2324 	vifi = *(mtod(m, int *));
2325 
2326 	if (rsvpdebug)
2327 		printf("ip_rsvp_vif_init: vif = %d rsvp_on = %d\n",
2328 		       vifi, rsvp_on);
2329 
2330 	s = splsoftnet();
2331 
2332 	/* Check vif. */
2333 	if (!legal_vif_num(vifi)) {
2334 		splx(s);
2335 		return (EADDRNOTAVAIL);
2336 	}
2337 
2338 	/* Check if socket is available. */
2339 	if (viftable[vifi].v_rsvpd != NULL) {
2340 		splx(s);
2341 		return (EADDRINUSE);
2342 	}
2343 
2344 	viftable[vifi].v_rsvpd = so;
2345 	/*
2346 	 * This may seem silly, but we need to be sure we don't over-increment
2347 	 * the RSVP counter, in case something slips up.
2348 	 */
2349 	if (!viftable[vifi].v_rsvp_on) {
2350 		viftable[vifi].v_rsvp_on = 1;
2351 		rsvp_on++;
2352 	}
2353 
2354 	splx(s);
2355 	return (0);
2356 }
2357 
2358 int
2359 ip_rsvp_vif_done(struct socket *so, struct mbuf *m)
2360 {
2361 	int vifi, s;
2362 
2363 	if (rsvpdebug)
2364 		printf("ip_rsvp_vif_done: so_type = %d, pr_protocol = %d\n",
2365 		    so->so_type, so->so_proto->pr_protocol);
2366 
2367 	if (so->so_type != SOCK_RAW ||
2368 	    so->so_proto->pr_protocol != IPPROTO_RSVP)
2369 		return (EOPNOTSUPP);
2370 
2371 	/* Check mbuf. */
2372 	if (m == NULL || m->m_len != sizeof(int)) {
2373 		return (EINVAL);
2374 	}
2375 	vifi = *(mtod(m, int *));
2376 
2377 	s = splsoftnet();
2378 
2379 	/* Check vif. */
2380 	if (!legal_vif_num(vifi)) {
2381 		splx(s);
2382 		return (EADDRNOTAVAIL);
2383 	}
2384 
2385 	if (rsvpdebug)
2386 		printf("ip_rsvp_vif_done: v_rsvpd = %x so = %x\n",
2387 		    viftable[vifi].v_rsvpd, so);
2388 
2389 	viftable[vifi].v_rsvpd = NULL;
2390 	/*
2391 	 * This may seem silly, but we need to be sure we don't over-decrement
2392 	 * the RSVP counter, in case something slips up.
2393 	 */
2394 	if (viftable[vifi].v_rsvp_on) {
2395 		viftable[vifi].v_rsvp_on = 0;
2396 		rsvp_on--;
2397 	}
2398 
2399 	splx(s);
2400 	return (0);
2401 }
2402 
2403 void
2404 ip_rsvp_force_done(struct socket *so)
2405 {
2406 	int vifi, s;
2407 
2408 	/* Don't bother if it is not the right type of socket. */
2409 	if (so->so_type != SOCK_RAW ||
2410 	    so->so_proto->pr_protocol != IPPROTO_RSVP)
2411 		return;
2412 
2413 	s = splsoftnet();
2414 
2415 	/*
2416 	 * The socket may be attached to more than one vif...this
2417 	 * is perfectly legal.
2418 	 */
2419 	for (vifi = 0; vifi < numvifs; vifi++) {
2420 		if (viftable[vifi].v_rsvpd == so) {
2421 			viftable[vifi].v_rsvpd = NULL;
2422 			/*
2423 			 * This may seem silly, but we need to be sure we don't
2424 			 * over-decrement the RSVP counter, in case something
2425 			 * slips up.
2426 			 */
2427 			if (viftable[vifi].v_rsvp_on) {
2428 				viftable[vifi].v_rsvp_on = 0;
2429 				rsvp_on--;
2430 			}
2431 		}
2432 	}
2433 
2434 	splx(s);
2435 	return;
2436 }
2437 
2438 void
2439 rsvp_input(struct mbuf *m, struct ifnet *ifp)
2440 {
2441 	int vifi, s;
2442 	struct ip *ip = mtod(m, struct ip *);
2443 	static struct sockaddr_in rsvp_src = { sizeof(sin), AF_INET };
2444 
2445 	if (rsvpdebug)
2446 		printf("rsvp_input: rsvp_on %d\n", rsvp_on);
2447 
2448 	/*
2449 	 * Can still get packets with rsvp_on = 0 if there is a local member
2450 	 * of the group to which the RSVP packet is addressed.  But in this
2451 	 * case we want to throw the packet away.
2452 	 */
2453 	if (!rsvp_on) {
2454 		m_freem(m);
2455 		return;
2456 	}
2457 
2458 	/*
2459 	 * If the old-style non-vif-associated socket is set, then use
2460 	 * it and ignore the new ones.
2461 	 */
2462 	if (ip_rsvpd != NULL) {
2463 		if (rsvpdebug)
2464 			printf("rsvp_input: "
2465 			    "Sending packet up old-style socket\n");
2466 		rip_input(m);	/*XXX*/
2467 		return;
2468 	}
2469 
2470 	s = splsoftnet();
2471 
2472 	if (rsvpdebug)
2473 		printf("rsvp_input: check vifs\n");
2474 
2475 	/* Find which vif the packet arrived on. */
2476 	for (vifi = 0; vifi < numvifs; vifi++) {
2477 		if (viftable[vifi].v_ifp == ifp)
2478 			break;
2479 	}
2480 
2481 	if (vifi == numvifs) {
2482 		/* Can't find vif packet arrived on. Drop packet. */
2483 		if (rsvpdebug)
2484 			printf("rsvp_input: "
2485 			    "Can't find vif for packet...dropping it.\n");
2486 		m_freem(m);
2487 		splx(s);
2488 		return;
2489 	}
2490 
2491 	if (rsvpdebug)
2492 		printf("rsvp_input: check socket\n");
2493 
2494 	if (viftable[vifi].v_rsvpd == NULL) {
2495 		/*
2496 		 * drop packet, since there is no specific socket for this
2497 		 * interface
2498 		 */
2499 		if (rsvpdebug)
2500 			printf("rsvp_input: No socket defined for vif %d\n",
2501 			    vifi);
2502 		m_freem(m);
2503 		splx(s);
2504 		return;
2505 	}
2506 
2507 	rsvp_src.sin_addr = ip->ip_src;
2508 
2509 	if (rsvpdebug && m)
2510 		printf("rsvp_input: m->m_len = %d, sbspace() = %d\n",
2511 		    m->m_len, sbspace(&viftable[vifi].v_rsvpd->so_rcv));
2512 
2513 	if (socket_send(viftable[vifi].v_rsvpd, m, &rsvp_src) < 0)
2514 		if (rsvpdebug)
2515 			printf("rsvp_input: Failed to append to socket\n");
2516 	else
2517 		if (rsvpdebug)
2518 			printf("rsvp_input: send packet up\n");
2519 
2520 	splx(s);
2521 }
2522 #endif /* RSVP_ISI */
2523 
2524 /*
2525  * Code for bandwidth monitors
2526  */
2527 
2528 /*
2529  * Define common interface for timeval-related methods
2530  */
2531 #define	BW_TIMEVALCMP(tvp, uvp, cmp) timercmp((tvp), (uvp), cmp)
2532 #define	BW_TIMEVALDECR(vvp, uvp) timersub((vvp), (uvp), (vvp))
2533 #define	BW_TIMEVALADD(vvp, uvp) timeradd((vvp), (uvp), (vvp))
2534 
2535 static uint32_t
2536 compute_bw_meter_flags(struct bw_upcall *req)
2537 {
2538     uint32_t flags = 0;
2539 
2540     if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
2541 	flags |= BW_METER_UNIT_PACKETS;
2542     if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
2543 	flags |= BW_METER_UNIT_BYTES;
2544     if (req->bu_flags & BW_UPCALL_GEQ)
2545 	flags |= BW_METER_GEQ;
2546     if (req->bu_flags & BW_UPCALL_LEQ)
2547 	flags |= BW_METER_LEQ;
2548 
2549     return flags;
2550 }
2551 
2552 /*
2553  * Add a bw_meter entry
2554  */
2555 static int
2556 add_bw_upcall(struct mbuf *m)
2557 {
2558     int s;
2559     struct mfc *mfc;
2560     struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
2561 		BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
2562     struct timeval now;
2563     struct bw_meter *x;
2564     uint32_t flags;
2565     struct bw_upcall *req;
2566 
2567     if (m == NULL || m->m_len < sizeof(struct bw_upcall))
2568 	return EINVAL;
2569 
2570     req = mtod(m, struct bw_upcall *);
2571 
2572     if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2573 	return EOPNOTSUPP;
2574 
2575     /* Test if the flags are valid */
2576     if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
2577 	return EINVAL;
2578     if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
2579 	return EINVAL;
2580     if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2581 	    == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2582 	return EINVAL;
2583 
2584     /* Test if the threshold time interval is valid */
2585     if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
2586 	return EINVAL;
2587 
2588     flags = compute_bw_meter_flags(req);
2589 
2590     /*
2591      * Find if we have already same bw_meter entry
2592      */
2593     s = splsoftnet();
2594     mfc = mfc_find(&req->bu_src, &req->bu_dst);
2595     if (mfc == NULL) {
2596 	splx(s);
2597 	return EADDRNOTAVAIL;
2598     }
2599     for (x = mfc->mfc_bw_meter; x != NULL; x = x->bm_mfc_next) {
2600 	if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2601 			   &req->bu_threshold.b_time, ==)) &&
2602 	    (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2603 	    (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2604 	    (x->bm_flags & BW_METER_USER_FLAGS) == flags)  {
2605 	    splx(s);
2606 	    return 0;		/* XXX Already installed */
2607 	}
2608     }
2609 
2610     /* Allocate the new bw_meter entry */
2611     x = (struct bw_meter *)malloc(sizeof(*x), M_BWMETER, M_NOWAIT);
2612     if (x == NULL) {
2613 	splx(s);
2614 	return ENOBUFS;
2615     }
2616 
2617     /* Set the new bw_meter entry */
2618     x->bm_threshold.b_time = req->bu_threshold.b_time;
2619     microtime(&now);
2620     x->bm_start_time = now;
2621     x->bm_threshold.b_packets = req->bu_threshold.b_packets;
2622     x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
2623     x->bm_measured.b_packets = 0;
2624     x->bm_measured.b_bytes = 0;
2625     x->bm_flags = flags;
2626     x->bm_time_next = NULL;
2627     x->bm_time_hash = BW_METER_BUCKETS;
2628 
2629     /* Add the new bw_meter entry to the front of entries for this MFC */
2630     x->bm_mfc = mfc;
2631     x->bm_mfc_next = mfc->mfc_bw_meter;
2632     mfc->mfc_bw_meter = x;
2633     schedule_bw_meter(x, &now);
2634     splx(s);
2635 
2636     return 0;
2637 }
2638 
2639 static void
2640 free_bw_list(struct bw_meter *list)
2641 {
2642     while (list != NULL) {
2643 	struct bw_meter *x = list;
2644 
2645 	list = list->bm_mfc_next;
2646 	unschedule_bw_meter(x);
2647 	free(x, M_BWMETER);
2648     }
2649 }
2650 
2651 /*
2652  * Delete one or multiple bw_meter entries
2653  */
2654 static int
2655 del_bw_upcall(struct mbuf *m)
2656 {
2657     int s;
2658     struct mfc *mfc;
2659     struct bw_meter *x;
2660     struct bw_upcall *req;
2661 
2662     if (m == NULL || m->m_len < sizeof(struct bw_upcall))
2663 	return EINVAL;
2664 
2665     req = mtod(m, struct bw_upcall *);
2666 
2667     if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2668 	return EOPNOTSUPP;
2669 
2670     s = splsoftnet();
2671     /* Find the corresponding MFC entry */
2672     mfc = mfc_find(&req->bu_src, &req->bu_dst);
2673     if (mfc == NULL) {
2674 	splx(s);
2675 	return EADDRNOTAVAIL;
2676     } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2677 	/*
2678 	 * Delete all bw_meter entries for this mfc
2679 	 */
2680 	struct bw_meter *list;
2681 
2682 	list = mfc->mfc_bw_meter;
2683 	mfc->mfc_bw_meter = NULL;
2684 	free_bw_list(list);
2685 	splx(s);
2686 	return 0;
2687     } else {			/* Delete a single bw_meter entry */
2688 	struct bw_meter *prev;
2689 	uint32_t flags = 0;
2690 
2691 	flags = compute_bw_meter_flags(req);
2692 
2693 	/* Find the bw_meter entry to delete */
2694 	for (prev = NULL, x = mfc->mfc_bw_meter; x != NULL;
2695 	     prev = x, x = x->bm_mfc_next) {
2696 	    if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2697 			       &req->bu_threshold.b_time, ==)) &&
2698 		(x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2699 		(x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2700 		(x->bm_flags & BW_METER_USER_FLAGS) == flags)
2701 		break;
2702 	}
2703 	if (x != NULL) { /* Delete entry from the list for this MFC */
2704 	    if (prev != NULL)
2705 		prev->bm_mfc_next = x->bm_mfc_next;	/* remove from middle*/
2706 	    else
2707 		x->bm_mfc->mfc_bw_meter = x->bm_mfc_next;/* new head of list */
2708 
2709 	    unschedule_bw_meter(x);
2710 	    splx(s);
2711 	    /* Free the bw_meter entry */
2712 	    free(x, M_BWMETER);
2713 	    return 0;
2714 	} else {
2715 	    splx(s);
2716 	    return EINVAL;
2717 	}
2718     }
2719     /* NOTREACHED */
2720 }
2721 
2722 /*
2723  * Perform bandwidth measurement processing that may result in an upcall
2724  */
2725 static void
2726 bw_meter_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2727 {
2728     struct timeval delta;
2729 
2730     delta = *nowp;
2731     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2732 
2733     if (x->bm_flags & BW_METER_GEQ) {
2734 	/*
2735 	 * Processing for ">=" type of bw_meter entry
2736 	 */
2737 	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2738 	    /* Reset the bw_meter entry */
2739 	    x->bm_start_time = *nowp;
2740 	    x->bm_measured.b_packets = 0;
2741 	    x->bm_measured.b_bytes = 0;
2742 	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2743 	}
2744 
2745 	/* Record that a packet is received */
2746 	x->bm_measured.b_packets++;
2747 	x->bm_measured.b_bytes += plen;
2748 
2749 	/*
2750 	 * Test if we should deliver an upcall
2751 	 */
2752 	if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2753 	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2754 		 (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2755 		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2756 		 (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2757 		/* Prepare an upcall for delivery */
2758 		bw_meter_prepare_upcall(x, nowp);
2759 		x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2760 	    }
2761 	}
2762     } else if (x->bm_flags & BW_METER_LEQ) {
2763 	/*
2764 	 * Processing for "<=" type of bw_meter entry
2765 	 */
2766 	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2767 	    /*
2768 	     * We are behind time with the multicast forwarding table
2769 	     * scanning for "<=" type of bw_meter entries, so test now
2770 	     * if we should deliver an upcall.
2771 	     */
2772 	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2773 		 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2774 		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2775 		 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2776 		/* Prepare an upcall for delivery */
2777 		bw_meter_prepare_upcall(x, nowp);
2778 	    }
2779 	    /* Reschedule the bw_meter entry */
2780 	    unschedule_bw_meter(x);
2781 	    schedule_bw_meter(x, nowp);
2782 	}
2783 
2784 	/* Record that a packet is received */
2785 	x->bm_measured.b_packets++;
2786 	x->bm_measured.b_bytes += plen;
2787 
2788 	/*
2789 	 * Test if we should restart the measuring interval
2790 	 */
2791 	if ((x->bm_flags & BW_METER_UNIT_PACKETS &&
2792 	     x->bm_measured.b_packets <= x->bm_threshold.b_packets) ||
2793 	    (x->bm_flags & BW_METER_UNIT_BYTES &&
2794 	     x->bm_measured.b_bytes <= x->bm_threshold.b_bytes)) {
2795 	    /* Don't restart the measuring interval */
2796 	} else {
2797 	    /* Do restart the measuring interval */
2798 	    /*
2799 	     * XXX: note that we don't unschedule and schedule, because this
2800 	     * might be too much overhead per packet. Instead, when we process
2801 	     * all entries for a given timer hash bin, we check whether it is
2802 	     * really a timeout. If not, we reschedule at that time.
2803 	     */
2804 	    x->bm_start_time = *nowp;
2805 	    x->bm_measured.b_packets = 0;
2806 	    x->bm_measured.b_bytes = 0;
2807 	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2808 	}
2809     }
2810 }
2811 
2812 /*
2813  * Prepare a bandwidth-related upcall
2814  */
2815 static void
2816 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2817 {
2818     struct timeval delta;
2819     struct bw_upcall *u;
2820 
2821     /*
2822      * Compute the measured time interval
2823      */
2824     delta = *nowp;
2825     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2826 
2827     /*
2828      * If there are too many pending upcalls, deliver them now
2829      */
2830     if (bw_upcalls_n >= BW_UPCALLS_MAX)
2831 	bw_upcalls_send();
2832 
2833     /*
2834      * Set the bw_upcall entry
2835      */
2836     u = &bw_upcalls[bw_upcalls_n++];
2837     u->bu_src = x->bm_mfc->mfc_origin;
2838     u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2839     u->bu_threshold.b_time = x->bm_threshold.b_time;
2840     u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2841     u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2842     u->bu_measured.b_time = delta;
2843     u->bu_measured.b_packets = x->bm_measured.b_packets;
2844     u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2845     u->bu_flags = 0;
2846     if (x->bm_flags & BW_METER_UNIT_PACKETS)
2847 	u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2848     if (x->bm_flags & BW_METER_UNIT_BYTES)
2849 	u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2850     if (x->bm_flags & BW_METER_GEQ)
2851 	u->bu_flags |= BW_UPCALL_GEQ;
2852     if (x->bm_flags & BW_METER_LEQ)
2853 	u->bu_flags |= BW_UPCALL_LEQ;
2854 }
2855 
2856 /*
2857  * Send the pending bandwidth-related upcalls
2858  */
2859 static void
2860 bw_upcalls_send(void)
2861 {
2862     struct mbuf *m;
2863     int len = bw_upcalls_n * sizeof(bw_upcalls[0]);
2864     struct sockaddr_in k_igmpsrc = {
2865 	    .sin_len = sizeof(k_igmpsrc),
2866 	    .sin_family = AF_INET,
2867     };
2868     static struct igmpmsg igmpmsg = { 0,		/* unused1 */
2869 				      0,		/* unused2 */
2870 				      IGMPMSG_BW_UPCALL,/* im_msgtype */
2871 				      0,		/* im_mbz  */
2872 				      0,		/* im_vif  */
2873 				      0,		/* unused3 */
2874 				      { 0 },		/* im_src  */
2875 				      { 0 } };		/* im_dst  */
2876 
2877     if (bw_upcalls_n == 0)
2878 	return;			/* No pending upcalls */
2879 
2880     bw_upcalls_n = 0;
2881 
2882     /*
2883      * Allocate a new mbuf, initialize it with the header and
2884      * the payload for the pending calls.
2885      */
2886     MGETHDR(m, M_DONTWAIT, MT_HEADER);
2887     if (m == NULL) {
2888 	log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2889 	return;
2890     }
2891 
2892     m->m_len = m->m_pkthdr.len = 0;
2893     m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2894     m_copyback(m, sizeof(struct igmpmsg), len, (caddr_t)&bw_upcalls[0]);
2895 
2896     /*
2897      * Send the upcalls
2898      * XXX do we need to set the address in k_igmpsrc ?
2899      */
2900     mrtstat.mrts_upcalls++;
2901     if (socket_send(ip_mrouter, m, &k_igmpsrc) < 0) {
2902 	log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2903 	++mrtstat.mrts_upq_sockfull;
2904     }
2905 }
2906 
2907 /*
2908  * Compute the timeout hash value for the bw_meter entries
2909  */
2910 #define	BW_METER_TIMEHASH(bw_meter, hash)				\
2911     do {								\
2912 	struct timeval next_timeval = (bw_meter)->bm_start_time;	\
2913 									\
2914 	BW_TIMEVALADD(&next_timeval, &(bw_meter)->bm_threshold.b_time); \
2915 	(hash) = next_timeval.tv_sec;					\
2916 	if (next_timeval.tv_usec)					\
2917 	    (hash)++; /* XXX: make sure we don't timeout early */	\
2918 	(hash) %= BW_METER_BUCKETS;					\
2919     } while (/*CONSTCOND*/ 0)
2920 
2921 /*
2922  * Schedule a timer to process periodically bw_meter entry of type "<="
2923  * by linking the entry in the proper hash bucket.
2924  */
2925 static void
2926 schedule_bw_meter(struct bw_meter *x, struct timeval *nowp)
2927 {
2928     int time_hash;
2929 
2930     if (!(x->bm_flags & BW_METER_LEQ))
2931 	return;		/* XXX: we schedule timers only for "<=" entries */
2932 
2933     /*
2934      * Reset the bw_meter entry
2935      */
2936     x->bm_start_time = *nowp;
2937     x->bm_measured.b_packets = 0;
2938     x->bm_measured.b_bytes = 0;
2939     x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2940 
2941     /*
2942      * Compute the timeout hash value and insert the entry
2943      */
2944     BW_METER_TIMEHASH(x, time_hash);
2945     x->bm_time_next = bw_meter_timers[time_hash];
2946     bw_meter_timers[time_hash] = x;
2947     x->bm_time_hash = time_hash;
2948 }
2949 
2950 /*
2951  * Unschedule the periodic timer that processes bw_meter entry of type "<="
2952  * by removing the entry from the proper hash bucket.
2953  */
2954 static void
2955 unschedule_bw_meter(struct bw_meter *x)
2956 {
2957     int time_hash;
2958     struct bw_meter *prev, *tmp;
2959 
2960     if (!(x->bm_flags & BW_METER_LEQ))
2961 	return;		/* XXX: we schedule timers only for "<=" entries */
2962 
2963     /*
2964      * Compute the timeout hash value and delete the entry
2965      */
2966     time_hash = x->bm_time_hash;
2967     if (time_hash >= BW_METER_BUCKETS)
2968 	return;		/* Entry was not scheduled */
2969 
2970     for (prev = NULL, tmp = bw_meter_timers[time_hash];
2971 	     tmp != NULL; prev = tmp, tmp = tmp->bm_time_next)
2972 	if (tmp == x)
2973 	    break;
2974 
2975     if (tmp == NULL)
2976 	panic("unschedule_bw_meter: bw_meter entry not found");
2977 
2978     if (prev != NULL)
2979 	prev->bm_time_next = x->bm_time_next;
2980     else
2981 	bw_meter_timers[time_hash] = x->bm_time_next;
2982 
2983     x->bm_time_next = NULL;
2984     x->bm_time_hash = BW_METER_BUCKETS;
2985 }
2986 
2987 /*
2988  * Process all "<=" type of bw_meter that should be processed now,
2989  * and for each entry prepare an upcall if necessary. Each processed
2990  * entry is rescheduled again for the (periodic) processing.
2991  *
2992  * This is run periodically (once per second normally). On each round,
2993  * all the potentially matching entries are in the hash slot that we are
2994  * looking at.
2995  */
2996 static void
2997 bw_meter_process(void)
2998 {
2999     int s;
3000     static uint32_t last_tv_sec;	/* last time we processed this */
3001 
3002     uint32_t loops;
3003     int i;
3004     struct timeval now, process_endtime;
3005 
3006     microtime(&now);
3007     if (last_tv_sec == now.tv_sec)
3008 	return;		/* nothing to do */
3009 
3010     loops = now.tv_sec - last_tv_sec;
3011     last_tv_sec = now.tv_sec;
3012     if (loops > BW_METER_BUCKETS)
3013 	loops = BW_METER_BUCKETS;
3014 
3015     s = splsoftnet();
3016     /*
3017      * Process all bins of bw_meter entries from the one after the last
3018      * processed to the current one. On entry, i points to the last bucket
3019      * visited, so we need to increment i at the beginning of the loop.
3020      */
3021     for (i = (now.tv_sec - loops) % BW_METER_BUCKETS; loops > 0; loops--) {
3022 	struct bw_meter *x, *tmp_list;
3023 
3024 	if (++i >= BW_METER_BUCKETS)
3025 	    i = 0;
3026 
3027 	/* Disconnect the list of bw_meter entries from the bin */
3028 	tmp_list = bw_meter_timers[i];
3029 	bw_meter_timers[i] = NULL;
3030 
3031 	/* Process the list of bw_meter entries */
3032 	while (tmp_list != NULL) {
3033 	    x = tmp_list;
3034 	    tmp_list = tmp_list->bm_time_next;
3035 
3036 	    /* Test if the time interval is over */
3037 	    process_endtime = x->bm_start_time;
3038 	    BW_TIMEVALADD(&process_endtime, &x->bm_threshold.b_time);
3039 	    if (BW_TIMEVALCMP(&process_endtime, &now, >)) {
3040 		/* Not yet: reschedule, but don't reset */
3041 		int time_hash;
3042 
3043 		BW_METER_TIMEHASH(x, time_hash);
3044 		if (time_hash == i && process_endtime.tv_sec == now.tv_sec) {
3045 		    /*
3046 		     * XXX: somehow the bin processing is a bit ahead of time.
3047 		     * Put the entry in the next bin.
3048 		     */
3049 		    if (++time_hash >= BW_METER_BUCKETS)
3050 			time_hash = 0;
3051 		}
3052 		x->bm_time_next = bw_meter_timers[time_hash];
3053 		bw_meter_timers[time_hash] = x;
3054 		x->bm_time_hash = time_hash;
3055 
3056 		continue;
3057 	    }
3058 
3059 	    /*
3060 	     * Test if we should deliver an upcall
3061 	     */
3062 	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
3063 		 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
3064 		((x->bm_flags & BW_METER_UNIT_BYTES) &&
3065 		 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
3066 		/* Prepare an upcall for delivery */
3067 		bw_meter_prepare_upcall(x, &now);
3068 	    }
3069 
3070 	    /*
3071 	     * Reschedule for next processing
3072 	     */
3073 	    schedule_bw_meter(x, &now);
3074 	}
3075     }
3076 
3077     /* Send all upcalls that are pending delivery */
3078     bw_upcalls_send();
3079 
3080     splx(s);
3081 }
3082 
3083 /*
3084  * A periodic function for sending all upcalls that are pending delivery
3085  */
3086 static void
3087 expire_bw_upcalls_send(void *unused __unused)
3088 {
3089     int s;
3090 
3091     s = splsoftnet();
3092     bw_upcalls_send();
3093     splx(s);
3094 
3095     callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
3096 		  expire_bw_upcalls_send, NULL);
3097 }
3098 
3099 /*
3100  * A periodic function for periodic scanning of the multicast forwarding
3101  * table for processing all "<=" bw_meter entries.
3102  */
3103 static void
3104 expire_bw_meter_process(void *unused __unused)
3105 {
3106     if (mrt_api_config & MRT_MFC_BW_UPCALL)
3107 	bw_meter_process();
3108 
3109     callout_reset(&bw_meter_ch, BW_METER_PERIOD,
3110 		  expire_bw_meter_process, NULL);
3111 }
3112 
3113 /*
3114  * End of bandwidth monitoring code
3115  */
3116 
3117 #ifdef PIM
3118 /*
3119  * Send the packet up to the user daemon, or eventually do kernel encapsulation
3120  */
3121 static int
3122 pim_register_send(struct ip *ip, struct vif *vifp,
3123 	struct mbuf *m, struct mfc *rt)
3124 {
3125     struct mbuf *mb_copy, *mm;
3126 
3127     if (mrtdebug & DEBUG_PIM)
3128         log(LOG_DEBUG, "pim_register_send: ");
3129 
3130     mb_copy = pim_register_prepare(ip, m);
3131     if (mb_copy == NULL)
3132 	return ENOBUFS;
3133 
3134     /*
3135      * Send all the fragments. Note that the mbuf for each fragment
3136      * is freed by the sending machinery.
3137      */
3138     for (mm = mb_copy; mm; mm = mb_copy) {
3139 	mb_copy = mm->m_nextpkt;
3140 	mm->m_nextpkt = NULL;
3141 	mm = m_pullup(mm, sizeof(struct ip));
3142 	if (mm != NULL) {
3143 	    ip = mtod(mm, struct ip *);
3144 	    if ((mrt_api_config & MRT_MFC_RP) &&
3145 		!in_nullhost(rt->mfc_rp)) {
3146 		pim_register_send_rp(ip, vifp, mm, rt);
3147 	    } else {
3148 		pim_register_send_upcall(ip, vifp, mm, rt);
3149 	    }
3150 	}
3151     }
3152 
3153     return 0;
3154 }
3155 
3156 /*
3157  * Return a copy of the data packet that is ready for PIM Register
3158  * encapsulation.
3159  * XXX: Note that in the returned copy the IP header is a valid one.
3160  */
3161 static struct mbuf *
3162 pim_register_prepare(struct ip *ip, struct mbuf *m)
3163 {
3164     struct mbuf *mb_copy = NULL;
3165     int mtu;
3166 
3167     /* Take care of delayed checksums */
3168     if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
3169 	in_delayed_cksum(m);
3170 	m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
3171     }
3172 
3173     /*
3174      * Copy the old packet & pullup its IP header into the
3175      * new mbuf so we can modify it.
3176      */
3177     mb_copy = m_copy(m, 0, M_COPYALL);
3178     if (mb_copy == NULL)
3179 	return NULL;
3180     mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
3181     if (mb_copy == NULL)
3182 	return NULL;
3183 
3184     /* take care of the TTL */
3185     ip = mtod(mb_copy, struct ip *);
3186     --ip->ip_ttl;
3187 
3188     /* Compute the MTU after the PIM Register encapsulation */
3189     mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
3190 
3191     if (ntohs(ip->ip_len) <= mtu) {
3192 	/* Turn the IP header into a valid one */
3193 	ip->ip_sum = 0;
3194 	ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
3195     } else {
3196 	/* Fragment the packet */
3197 	if (ip_fragment(mb_copy, NULL, mtu) != 0) {
3198 	    /* XXX: mb_copy was freed by ip_fragment() */
3199 	    return NULL;
3200 	}
3201     }
3202     return mb_copy;
3203 }
3204 
3205 /*
3206  * Send an upcall with the data packet to the user-level process.
3207  */
3208 static int
3209 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
3210     struct mbuf *mb_copy, struct mfc *rt __unused)
3211 {
3212     struct mbuf *mb_first;
3213     int len = ntohs(ip->ip_len);
3214     struct igmpmsg *im;
3215     struct sockaddr_in k_igmpsrc = {
3216 	    .sin_len = sizeof(k_igmpsrc),
3217 	    .sin_family = AF_INET,
3218     };
3219 
3220     /*
3221      * Add a new mbuf with an upcall header
3222      */
3223     MGETHDR(mb_first, M_DONTWAIT, MT_HEADER);
3224     if (mb_first == NULL) {
3225 	m_freem(mb_copy);
3226 	return ENOBUFS;
3227     }
3228     mb_first->m_data += max_linkhdr;
3229     mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
3230     mb_first->m_len = sizeof(struct igmpmsg);
3231     mb_first->m_next = mb_copy;
3232 
3233     /* Send message to routing daemon */
3234     im = mtod(mb_first, struct igmpmsg *);
3235     im->im_msgtype	= IGMPMSG_WHOLEPKT;
3236     im->im_mbz		= 0;
3237     im->im_vif		= vifp - viftable;
3238     im->im_src		= ip->ip_src;
3239     im->im_dst		= ip->ip_dst;
3240 
3241     k_igmpsrc.sin_addr	= ip->ip_src;
3242 
3243     mrtstat.mrts_upcalls++;
3244 
3245     if (socket_send(ip_mrouter, mb_first, &k_igmpsrc) < 0) {
3246 	if (mrtdebug & DEBUG_PIM)
3247 	    log(LOG_WARNING,
3248 		"mcast: pim_register_send_upcall: ip_mrouter socket queue full");
3249 	++mrtstat.mrts_upq_sockfull;
3250 	return ENOBUFS;
3251     }
3252 
3253     /* Keep statistics */
3254     pimstat.pims_snd_registers_msgs++;
3255     pimstat.pims_snd_registers_bytes += len;
3256 
3257     return 0;
3258 }
3259 
3260 /*
3261  * Encapsulate the data packet in PIM Register message and send it to the RP.
3262  */
3263 static int
3264 pim_register_send_rp(struct ip *ip, struct vif *vifp,
3265 	struct mbuf *mb_copy, struct mfc *rt)
3266 {
3267     struct mbuf *mb_first;
3268     struct ip *ip_outer;
3269     struct pim_encap_pimhdr *pimhdr;
3270     int len = ntohs(ip->ip_len);
3271     vifi_t vifi = rt->mfc_parent;
3272 
3273     if ((vifi >= numvifs) || in_nullhost(viftable[vifi].v_lcl_addr)) {
3274 	m_freem(mb_copy);
3275 	return EADDRNOTAVAIL;		/* The iif vif is invalid */
3276     }
3277 
3278     /*
3279      * Add a new mbuf with the encapsulating header
3280      */
3281     MGETHDR(mb_first, M_DONTWAIT, MT_HEADER);
3282     if (mb_first == NULL) {
3283 	m_freem(mb_copy);
3284 	return ENOBUFS;
3285     }
3286     mb_first->m_data += max_linkhdr;
3287     mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
3288     mb_first->m_next = mb_copy;
3289 
3290     mb_first->m_pkthdr.len = len + mb_first->m_len;
3291 
3292     /*
3293      * Fill in the encapsulating IP and PIM header
3294      */
3295     ip_outer = mtod(mb_first, struct ip *);
3296     *ip_outer = pim_encap_iphdr;
3297     ip_outer->ip_id = ip_newid();
3298     ip_outer->ip_len = htons(len + sizeof(pim_encap_iphdr) +
3299 			     sizeof(pim_encap_pimhdr));
3300     ip_outer->ip_src = viftable[vifi].v_lcl_addr;
3301     ip_outer->ip_dst = rt->mfc_rp;
3302     /*
3303      * Copy the inner header TOS to the outer header, and take care of the
3304      * IP_DF bit.
3305      */
3306     ip_outer->ip_tos = ip->ip_tos;
3307     if (ntohs(ip->ip_off) & IP_DF)
3308 	ip_outer->ip_off |= IP_DF;
3309     pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
3310 					 + sizeof(pim_encap_iphdr));
3311     *pimhdr = pim_encap_pimhdr;
3312     /* If the iif crosses a border, set the Border-bit */
3313     if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & mrt_api_config)
3314 	pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
3315 
3316     mb_first->m_data += sizeof(pim_encap_iphdr);
3317     pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
3318     mb_first->m_data -= sizeof(pim_encap_iphdr);
3319 
3320     if (vifp->v_rate_limit == 0)
3321 	tbf_send_packet(vifp, mb_first);
3322     else
3323 	tbf_control(vifp, mb_first, ip, ntohs(ip_outer->ip_len));
3324 
3325     /* Keep statistics */
3326     pimstat.pims_snd_registers_msgs++;
3327     pimstat.pims_snd_registers_bytes += len;
3328 
3329     return 0;
3330 }
3331 
3332 /*
3333  * PIM-SMv2 and PIM-DM messages processing.
3334  * Receives and verifies the PIM control messages, and passes them
3335  * up to the listening socket, using rip_input().
3336  * The only message with special processing is the PIM_REGISTER message
3337  * (used by PIM-SM): the PIM header is stripped off, and the inner packet
3338  * is passed to if_simloop().
3339  */
3340 void
3341 pim_input(struct mbuf *m, ...)
3342 {
3343     struct ip *ip = mtod(m, struct ip *);
3344     struct pim *pim;
3345     int minlen;
3346     int datalen;
3347     int ip_tos;
3348     int proto;
3349     int iphlen;
3350     va_list ap;
3351 
3352     va_start(ap, m);
3353     iphlen = va_arg(ap, int);
3354     proto = va_arg(ap, int);
3355     va_end(ap);
3356 
3357     datalen = ntohs(ip->ip_len) - iphlen;
3358 
3359     /* Keep statistics */
3360     pimstat.pims_rcv_total_msgs++;
3361     pimstat.pims_rcv_total_bytes += datalen;
3362 
3363     /*
3364      * Validate lengths
3365      */
3366     if (datalen < PIM_MINLEN) {
3367 	pimstat.pims_rcv_tooshort++;
3368 	log(LOG_ERR, "pim_input: packet size too small %d from %lx\n",
3369 	    datalen, (u_long)ip->ip_src.s_addr);
3370 	m_freem(m);
3371 	return;
3372     }
3373 
3374     /*
3375      * If the packet is at least as big as a REGISTER, go agead
3376      * and grab the PIM REGISTER header size, to avoid another
3377      * possible m_pullup() later.
3378      *
3379      * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
3380      * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
3381      */
3382     minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
3383     /*
3384      * Get the IP and PIM headers in contiguous memory, and
3385      * possibly the PIM REGISTER header.
3386      */
3387     if ((m->m_flags & M_EXT || m->m_len < minlen) &&
3388 	(m = m_pullup(m, minlen)) == NULL) {
3389 	log(LOG_ERR, "pim_input: m_pullup failure\n");
3390 	return;
3391     }
3392     /* m_pullup() may have given us a new mbuf so reset ip. */
3393     ip = mtod(m, struct ip *);
3394     ip_tos = ip->ip_tos;
3395 
3396     /* adjust mbuf to point to the PIM header */
3397     m->m_data += iphlen;
3398     m->m_len  -= iphlen;
3399     pim = mtod(m, struct pim *);
3400 
3401     /*
3402      * Validate checksum. If PIM REGISTER, exclude the data packet.
3403      *
3404      * XXX: some older PIMv2 implementations don't make this distinction,
3405      * so for compatibility reason perform the checksum over part of the
3406      * message, and if error, then over the whole message.
3407      */
3408     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
3409 	/* do nothing, checksum okay */
3410     } else if (in_cksum(m, datalen)) {
3411 	pimstat.pims_rcv_badsum++;
3412 	if (mrtdebug & DEBUG_PIM)
3413 	    log(LOG_DEBUG, "pim_input: invalid checksum");
3414 	m_freem(m);
3415 	return;
3416     }
3417 
3418     /* PIM version check */
3419     if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
3420 	pimstat.pims_rcv_badversion++;
3421 	log(LOG_ERR, "pim_input: incorrect version %d, expecting %d\n",
3422 	    PIM_VT_V(pim->pim_vt), PIM_VERSION);
3423 	m_freem(m);
3424 	return;
3425     }
3426 
3427     /* restore mbuf back to the outer IP */
3428     m->m_data -= iphlen;
3429     m->m_len  += iphlen;
3430 
3431     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
3432 	/*
3433 	 * Since this is a REGISTER, we'll make a copy of the register
3434 	 * headers ip + pim + u_int32 + encap_ip, to be passed up to the
3435 	 * routing daemon.
3436 	 */
3437 	int s;
3438 	struct sockaddr_in dst = {
3439 		.sin_len = sizeof(dst),
3440 		.sin_family = AF_INET,
3441 	};
3442 	struct mbuf *mcp;
3443 	struct ip *encap_ip;
3444 	u_int32_t *reghdr;
3445 	struct ifnet *vifp;
3446 
3447 	s = splsoftnet();
3448 	if ((reg_vif_num >= numvifs) || (reg_vif_num == VIFI_INVALID)) {
3449 	    splx(s);
3450 	    if (mrtdebug & DEBUG_PIM)
3451 		log(LOG_DEBUG,
3452 		    "pim_input: register vif not set: %d\n", reg_vif_num);
3453 	    m_freem(m);
3454 	    return;
3455 	}
3456 	/* XXX need refcnt? */
3457 	vifp = viftable[reg_vif_num].v_ifp;
3458 	splx(s);
3459 
3460 	/*
3461 	 * Validate length
3462 	 */
3463 	if (datalen < PIM_REG_MINLEN) {
3464 	    pimstat.pims_rcv_tooshort++;
3465 	    pimstat.pims_rcv_badregisters++;
3466 	    log(LOG_ERR,
3467 		"pim_input: register packet size too small %d from %lx\n",
3468 		datalen, (u_long)ip->ip_src.s_addr);
3469 	    m_freem(m);
3470 	    return;
3471 	}
3472 
3473 	reghdr = (u_int32_t *)(pim + 1);
3474 	encap_ip = (struct ip *)(reghdr + 1);
3475 
3476 	if (mrtdebug & DEBUG_PIM) {
3477 	    log(LOG_DEBUG,
3478 		"pim_input[register], encap_ip: %lx -> %lx, encap_ip len %d\n",
3479 		(u_long)ntohl(encap_ip->ip_src.s_addr),
3480 		(u_long)ntohl(encap_ip->ip_dst.s_addr),
3481 		ntohs(encap_ip->ip_len));
3482 	}
3483 
3484 	/* verify the version number of the inner packet */
3485 	if (encap_ip->ip_v != IPVERSION) {
3486 	    pimstat.pims_rcv_badregisters++;
3487 	    if (mrtdebug & DEBUG_PIM) {
3488 		log(LOG_DEBUG, "pim_input: invalid IP version (%d) "
3489 		    "of the inner packet\n", encap_ip->ip_v);
3490 	    }
3491 	    m_freem(m);
3492 	    return;
3493 	}
3494 
3495 	/* verify the inner packet is destined to a mcast group */
3496 	if (!IN_MULTICAST(encap_ip->ip_dst.s_addr)) {
3497 	    pimstat.pims_rcv_badregisters++;
3498 	    if (mrtdebug & DEBUG_PIM)
3499 		log(LOG_DEBUG,
3500 		    "pim_input: inner packet of register is not "
3501 		    "multicast %lx\n",
3502 		    (u_long)ntohl(encap_ip->ip_dst.s_addr));
3503 	    m_freem(m);
3504 	    return;
3505 	}
3506 
3507 	/* If a NULL_REGISTER, pass it to the daemon */
3508 	if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
3509 	    goto pim_input_to_daemon;
3510 
3511 	/*
3512 	 * Copy the TOS from the outer IP header to the inner IP header.
3513 	 */
3514 	if (encap_ip->ip_tos != ip_tos) {
3515 	    /* Outer TOS -> inner TOS */
3516 	    encap_ip->ip_tos = ip_tos;
3517 	    /* Recompute the inner header checksum. Sigh... */
3518 
3519 	    /* adjust mbuf to point to the inner IP header */
3520 	    m->m_data += (iphlen + PIM_MINLEN);
3521 	    m->m_len  -= (iphlen + PIM_MINLEN);
3522 
3523 	    encap_ip->ip_sum = 0;
3524 	    encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
3525 
3526 	    /* restore mbuf to point back to the outer IP header */
3527 	    m->m_data -= (iphlen + PIM_MINLEN);
3528 	    m->m_len  += (iphlen + PIM_MINLEN);
3529 	}
3530 
3531 	/*
3532 	 * Decapsulate the inner IP packet and loopback to forward it
3533 	 * as a normal multicast packet. Also, make a copy of the
3534 	 *     outer_iphdr + pimhdr + reghdr + encap_iphdr
3535 	 * to pass to the daemon later, so it can take the appropriate
3536 	 * actions (e.g., send back PIM_REGISTER_STOP).
3537 	 * XXX: here m->m_data points to the outer IP header.
3538 	 */
3539 	mcp = m_copy(m, 0, iphlen + PIM_REG_MINLEN);
3540 	if (mcp == NULL) {
3541 	    log(LOG_ERR,
3542 		"pim_input: pim register: could not copy register head\n");
3543 	    m_freem(m);
3544 	    return;
3545 	}
3546 
3547 	/* Keep statistics */
3548 	/* XXX: registers_bytes include only the encap. mcast pkt */
3549 	pimstat.pims_rcv_registers_msgs++;
3550 	pimstat.pims_rcv_registers_bytes += ntohs(encap_ip->ip_len);
3551 
3552 	/*
3553 	 * forward the inner ip packet; point m_data at the inner ip.
3554 	 */
3555 	m_adj(m, iphlen + PIM_MINLEN);
3556 
3557 	if (mrtdebug & DEBUG_PIM) {
3558 	    log(LOG_DEBUG,
3559 		"pim_input: forwarding decapsulated register: "
3560 		"src %lx, dst %lx, vif %d\n",
3561 		(u_long)ntohl(encap_ip->ip_src.s_addr),
3562 		(u_long)ntohl(encap_ip->ip_dst.s_addr),
3563 		reg_vif_num);
3564 	}
3565 	/* NB: vifp was collected above; can it change on us? */
3566 	looutput(vifp, m, (struct sockaddr *)&dst, (struct rtentry *)NULL);
3567 
3568 	/* prepare the register head to send to the mrouting daemon */
3569 	m = mcp;
3570     }
3571 
3572 pim_input_to_daemon:
3573     /*
3574      * Pass the PIM message up to the daemon; if it is a Register message,
3575      * pass the 'head' only up to the daemon. This includes the
3576      * outer IP header, PIM header, PIM-Register header and the
3577      * inner IP header.
3578      * XXX: the outer IP header pkt size of a Register is not adjust to
3579      * reflect the fact that the inner multicast data is truncated.
3580      */
3581     rip_input(m, iphlen, proto);
3582 
3583     return;
3584 }
3585 #endif /* PIM */
3586