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