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