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