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