xref: /freebsd/sys/netinet/ip_mroute.c (revision 637e4ef1a6bcd8677dabd8c08916df3091be5f64)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989 Stephen Deering
5  * Copyright (c) 1992, 1993
6  *      The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Stephen Deering of Stanford University.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *      @(#)ip_mroute.c 8.2 (Berkeley) 11/15/93
36  */
37 
38 /*
39  * IP multicast forwarding procedures
40  *
41  * Written by David Waitzman, BBN Labs, August 1988.
42  * Modified by Steve Deering, Stanford, February 1989.
43  * Modified by Mark J. Steiglitz, Stanford, May, 1991
44  * Modified by Van Jacobson, LBL, January 1993
45  * Modified by Ajit Thyagarajan, PARC, August 1993
46  * Modified by Bill Fenner, PARC, April 1995
47  * Modified by Ahmed Helmy, SGI, June 1996
48  * Modified by George Edmond Eddy (Rusty), ISI, February 1998
49  * Modified by Pavlin Radoslavov, USC/ISI, May 1998, August 1999, October 2000
50  * Modified by Hitoshi Asaeda, WIDE, August 2000
51  * Modified by Pavlin Radoslavov, ICSI, October 2002
52  * Modified by Wojciech Macek, Semihalf, May 2021
53  *
54  * MROUTING Revision: 3.5
55  * and PIM-SMv2 and PIM-DM support, advanced API support,
56  * bandwidth metering and signaling
57  */
58 
59 /*
60  * TODO: Prefix functions with ipmf_.
61  * TODO: Maintain a refcount on if_allmulti() in ifnet or in the protocol
62  * domain attachment (if_afdata) so we can track consumers of that service.
63  * TODO: Deprecate routing socket path for SIOCGETSGCNT and SIOCGETVIFCNT,
64  * move it to socket options.
65  * TODO: Cleanup LSRR removal further.
66  * TODO: Push RSVP stubs into raw_ip.c.
67  * TODO: Use bitstring.h for vif set.
68  * TODO: Fix mrt6_ioctl dangling ref when dynamically loaded.
69  * TODO: Sync ip6_mroute.c with this file.
70  */
71 
72 #include <sys/cdefs.h>
73 #include "opt_inet.h"
74 #include "opt_mrouting.h"
75 
76 #define _PIM_VT 1
77 
78 #include <sys/types.h>
79 #include <sys/param.h>
80 #include <sys/kernel.h>
81 #include <sys/stddef.h>
82 #include <sys/condvar.h>
83 #include <sys/eventhandler.h>
84 #include <sys/lock.h>
85 #include <sys/kthread.h>
86 #include <sys/ktr.h>
87 #include <sys/malloc.h>
88 #include <sys/mbuf.h>
89 #include <sys/module.h>
90 #include <sys/priv.h>
91 #include <sys/protosw.h>
92 #include <sys/signalvar.h>
93 #include <sys/socket.h>
94 #include <sys/socketvar.h>
95 #include <sys/sockio.h>
96 #include <sys/sx.h>
97 #include <sys/sysctl.h>
98 #include <sys/syslog.h>
99 #include <sys/systm.h>
100 #include <sys/taskqueue.h>
101 #include <sys/time.h>
102 #include <sys/counter.h>
103 #include <machine/atomic.h>
104 
105 #include <net/if.h>
106 #include <net/if_var.h>
107 #include <net/if_private.h>
108 #include <net/if_types.h>
109 #include <net/netisr.h>
110 #include <net/route.h>
111 #include <net/vnet.h>
112 
113 #include <netinet/in.h>
114 #include <netinet/igmp.h>
115 #include <netinet/in_systm.h>
116 #include <netinet/in_var.h>
117 #include <netinet/ip.h>
118 #include <netinet/ip_encap.h>
119 #include <netinet/ip_mroute.h>
120 #include <netinet/ip_var.h>
121 #include <netinet/ip_options.h>
122 #include <netinet/pim.h>
123 #include <netinet/pim_var.h>
124 #include <netinet/udp.h>
125 
126 #include <machine/in_cksum.h>
127 
128 #ifndef KTR_IPMF
129 #define KTR_IPMF KTR_INET
130 #endif
131 
132 #define		VIFI_INVALID	((vifi_t) -1)
133 
134 static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast forwarding cache");
135 
136 /*
137  * Locking.  We use two locks: one for the virtual interface table and
138  * one for the forwarding table.  These locks may be nested in which case
139  * the VIF lock must always be taken first.  Note that each lock is used
140  * to cover not only the specific data structure but also related data
141  * structures.
142  */
143 
144 static struct rwlock mrouter_lock;
145 #define	MRW_RLOCK()		rw_rlock(&mrouter_lock)
146 #define	MRW_WLOCK()		rw_wlock(&mrouter_lock)
147 #define	MRW_RUNLOCK()		rw_runlock(&mrouter_lock)
148 #define	MRW_WUNLOCK()		rw_wunlock(&mrouter_lock)
149 #define	MRW_UNLOCK()		rw_unlock(&mrouter_lock)
150 #define	MRW_LOCK_ASSERT()	rw_assert(&mrouter_lock, RA_LOCKED)
151 #define	MRW_WLOCK_ASSERT()	rw_assert(&mrouter_lock, RA_WLOCKED)
152 #define	MRW_LOCK_TRY_UPGRADE()	rw_try_upgrade(&mrouter_lock)
153 #define	MRW_WOWNED()		rw_wowned(&mrouter_lock)
154 #define	MRW_LOCK_INIT()						\
155 	rw_init(&mrouter_lock, "IPv4 multicast forwarding")
156 #define	MRW_LOCK_DESTROY()	rw_destroy(&mrouter_lock)
157 
158 static int ip_mrouter_cnt;	/* # of vnets with active mrouters */
159 static int ip_mrouter_unloading; /* Allow no more V_ip_mrouter sockets */
160 
161 VNET_PCPUSTAT_DEFINE_STATIC(struct mrtstat, mrtstat);
162 VNET_PCPUSTAT_SYSINIT(mrtstat);
163 VNET_PCPUSTAT_SYSUNINIT(mrtstat);
164 SYSCTL_VNET_PCPUSTAT(_net_inet_ip, OID_AUTO, mrtstat, struct mrtstat,
165     mrtstat, "IPv4 Multicast Forwarding Statistics (struct mrtstat, "
166     "netinet/ip_mroute.h)");
167 
168 VNET_DEFINE_STATIC(u_long, mfchash);
169 #define	V_mfchash		VNET(mfchash)
170 #define	MFCHASH(a, g)							\
171 	((((a).s_addr >> 20) ^ ((a).s_addr >> 10) ^ (a).s_addr ^ \
172 	  ((g).s_addr >> 20) ^ ((g).s_addr >> 10) ^ (g).s_addr) & V_mfchash)
173 #define	MFCHASHSIZE	256
174 
175 static u_long mfchashsize = MFCHASHSIZE;	/* Hash size */
176 SYSCTL_ULONG(_net_inet_ip, OID_AUTO, mfchashsize, CTLFLAG_RDTUN,
177     &mfchashsize, 0, "IPv4 Multicast Forwarding Table hash size");
178 VNET_DEFINE_STATIC(u_char *, nexpire);		/* 0..mfchashsize-1 */
179 #define	V_nexpire		VNET(nexpire)
180 VNET_DEFINE_STATIC(LIST_HEAD(mfchashhdr, mfc)*, mfchashtbl);
181 #define	V_mfchashtbl		VNET(mfchashtbl)
182 VNET_DEFINE_STATIC(struct taskqueue *, task_queue);
183 #define	V_task_queue		VNET(task_queue)
184 VNET_DEFINE_STATIC(struct task, task);
185 #define	V_task		VNET(task)
186 
187 VNET_DEFINE_STATIC(vifi_t, numvifs);
188 #define	V_numvifs		VNET(numvifs)
189 VNET_DEFINE_STATIC(struct vif *, viftable);
190 #define	V_viftable		VNET(viftable)
191 
192 static eventhandler_tag if_detach_event_tag = NULL;
193 
194 VNET_DEFINE_STATIC(struct callout, expire_upcalls_ch);
195 #define	V_expire_upcalls_ch	VNET(expire_upcalls_ch)
196 
197 VNET_DEFINE_STATIC(struct mtx, buf_ring_mtx);
198 #define	V_buf_ring_mtx	VNET(buf_ring_mtx)
199 
200 #define		EXPIRE_TIMEOUT	(hz / 4)	/* 4x / second		*/
201 #define		UPCALL_EXPIRE	6		/* number of timeouts	*/
202 
203 /*
204  * Bandwidth meter variables and constants
205  */
206 static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
207 
208 /*
209  * Pending upcalls are stored in a ring which is flushed when
210  * full, or periodically
211  */
212 VNET_DEFINE_STATIC(struct callout, bw_upcalls_ch);
213 #define	V_bw_upcalls_ch		VNET(bw_upcalls_ch)
214 VNET_DEFINE_STATIC(struct buf_ring *, bw_upcalls_ring);
215 #define	V_bw_upcalls_ring    	VNET(bw_upcalls_ring)
216 VNET_DEFINE_STATIC(struct mtx, bw_upcalls_ring_mtx);
217 #define	V_bw_upcalls_ring_mtx    	VNET(bw_upcalls_ring_mtx)
218 
219 #define BW_UPCALLS_PERIOD (hz)		/* periodical flush of bw upcalls */
220 
221 VNET_PCPUSTAT_DEFINE_STATIC(struct pimstat, pimstat);
222 VNET_PCPUSTAT_SYSINIT(pimstat);
223 VNET_PCPUSTAT_SYSUNINIT(pimstat);
224 
225 SYSCTL_NODE(_net_inet, IPPROTO_PIM, pim, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
226     "PIM");
227 SYSCTL_VNET_PCPUSTAT(_net_inet_pim, PIMCTL_STATS, stats, struct pimstat,
228     pimstat, "PIM Statistics (struct pimstat, netinet/pim_var.h)");
229 
230 static u_long	pim_squelch_wholepkt = 0;
231 SYSCTL_ULONG(_net_inet_pim, OID_AUTO, squelch_wholepkt, CTLFLAG_RWTUN,
232     &pim_squelch_wholepkt, 0,
233     "Disable IGMP_WHOLEPKT notifications if rendezvous point is unspecified");
234 
235 static const struct encaptab *pim_encap_cookie;
236 static int pim_encapcheck(const struct mbuf *, int, int, void *);
237 static int pim_input(struct mbuf *, int, int, void *);
238 
239 extern int in_mcast_loop;
240 
241 static const struct encap_config ipv4_encap_cfg = {
242 	.proto = IPPROTO_PIM,
243 	.min_length = sizeof(struct ip) + PIM_MINLEN,
244 	.exact_match = 8,
245 	.check = pim_encapcheck,
246 	.input = pim_input
247 };
248 
249 /*
250  * Note: the PIM Register encapsulation adds the following in front of a
251  * data packet:
252  *
253  * struct pim_encap_hdr {
254  *    struct ip ip;
255  *    struct pim_encap_pimhdr  pim;
256  * }
257  *
258  */
259 
260 struct pim_encap_pimhdr {
261 	struct pim pim;
262 	uint32_t   flags;
263 };
264 #define		PIM_ENCAP_TTL	64
265 
266 static struct ip pim_encap_iphdr = {
267 #if BYTE_ORDER == LITTLE_ENDIAN
268 	sizeof(struct ip) >> 2,
269 	IPVERSION,
270 #else
271 	IPVERSION,
272 	sizeof(struct ip) >> 2,
273 #endif
274 	0,			/* tos */
275 	sizeof(struct ip),	/* total length */
276 	0,			/* id */
277 	0,			/* frag offset */
278 	PIM_ENCAP_TTL,
279 	IPPROTO_PIM,
280 	0,			/* checksum */
281 };
282 
283 static struct pim_encap_pimhdr pim_encap_pimhdr = {
284     {
285 	PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
286 	0,			/* reserved */
287 	0,			/* checksum */
288     },
289     0				/* flags */
290 };
291 
292 VNET_DEFINE_STATIC(vifi_t, reg_vif_num) = VIFI_INVALID;
293 #define	V_reg_vif_num		VNET(reg_vif_num)
294 VNET_DEFINE_STATIC(struct ifnet *, multicast_register_if);
295 #define	V_multicast_register_if	VNET(multicast_register_if)
296 
297 /*
298  * Private variables.
299  */
300 
301 static u_long	X_ip_mcast_src(int);
302 static int	X_ip_mforward(struct ip *, struct ifnet *, struct mbuf *,
303 		    struct ip_moptions *);
304 static int	X_ip_mrouter_done(void);
305 static int	X_ip_mrouter_get(struct socket *, struct sockopt *);
306 static int	X_ip_mrouter_set(struct socket *, struct sockopt *);
307 static int	X_legal_vif_num(int);
308 static int	X_mrt_ioctl(u_long, caddr_t, int);
309 
310 static int	add_bw_upcall(struct bw_upcall *);
311 static int	add_mfc(struct mfcctl2 *);
312 static int	add_vif(struct vifctl *);
313 static void	bw_meter_prepare_upcall(struct bw_meter *, struct timeval *);
314 static void	bw_meter_geq_receive_packet(struct bw_meter *, int,
315 		    struct timeval *);
316 static void	bw_upcalls_send(void);
317 static int	del_bw_upcall(struct bw_upcall *);
318 static int	del_mfc(struct mfcctl2 *);
319 static int	del_vif(vifi_t);
320 static int	del_vif_locked(vifi_t, struct ifnet **, struct ifnet **);
321 static void	expire_bw_upcalls_send(void *);
322 static void	expire_mfc(struct mfc *);
323 static void	expire_upcalls(void *);
324 static void	free_bw_list(struct bw_meter *);
325 static int	get_sg_cnt(struct sioc_sg_req *);
326 static int	get_vif_cnt(struct sioc_vif_req *);
327 static void	if_detached_event(void *, struct ifnet *);
328 static int	ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
329 static int	ip_mrouter_init(struct socket *, int);
330 static __inline struct mfc *
331 		mfc_find(struct in_addr *, struct in_addr *);
332 static void	phyint_send(struct ip *, struct vif *, struct mbuf *);
333 static struct mbuf *
334 		pim_register_prepare(struct ip *, struct mbuf *);
335 static int	pim_register_send(struct ip *, struct vif *,
336 		    struct mbuf *, struct mfc *);
337 static int	pim_register_send_rp(struct ip *, struct vif *,
338 		    struct mbuf *, struct mfc *);
339 static int	pim_register_send_upcall(struct ip *, struct vif *,
340 		    struct mbuf *, struct mfc *);
341 static void	send_packet(struct vif *, struct mbuf *);
342 static int	set_api_config(uint32_t *);
343 static int	set_assert(int);
344 static int	socket_send(struct socket *, struct mbuf *,
345 		    struct sockaddr_in *);
346 
347 /*
348  * Kernel multicast forwarding API capabilities and setup.
349  * If more API capabilities are added to the kernel, they should be
350  * recorded in `mrt_api_support'.
351  */
352 #define MRT_API_VERSION		0x0305
353 
354 static const int mrt_api_version = MRT_API_VERSION;
355 static const uint32_t mrt_api_support = (MRT_MFC_FLAGS_DISABLE_WRONGVIF |
356 					 MRT_MFC_FLAGS_BORDER_VIF |
357 					 MRT_MFC_RP |
358 					 MRT_MFC_BW_UPCALL);
359 VNET_DEFINE_STATIC(uint32_t, mrt_api_config);
360 #define	V_mrt_api_config	VNET(mrt_api_config)
361 VNET_DEFINE_STATIC(int, pim_assert_enabled);
362 #define	V_pim_assert_enabled	VNET(pim_assert_enabled)
363 static struct timeval pim_assert_interval = { 3, 0 };	/* Rate limit */
364 
365 /*
366  * Find a route for a given origin IP address and multicast group address.
367  * Statistics must be updated by the caller.
368  */
369 static __inline struct mfc *
370 mfc_find(struct in_addr *o, struct in_addr *g)
371 {
372 	struct mfc *rt;
373 
374 	/*
375 	 * Might be called both RLOCK and WLOCK.
376 	 * Check if any, it's caller responsibility
377 	 * to choose correct option.
378 	 */
379 	MRW_LOCK_ASSERT();
380 
381 	LIST_FOREACH(rt, &V_mfchashtbl[MFCHASH(*o, *g)], mfc_hash) {
382 		if (in_hosteq(rt->mfc_origin, *o) &&
383 		    in_hosteq(rt->mfc_mcastgrp, *g) &&
384 		    buf_ring_empty(rt->mfc_stall_ring))
385 			break;
386 	}
387 
388 	return (rt);
389 }
390 
391 static __inline struct mfc *
392 mfc_alloc(void)
393 {
394 	struct mfc *rt;
395 	rt = malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT | M_ZERO);
396 	if (rt == NULL)
397 		return rt;
398 
399 	rt->mfc_stall_ring = buf_ring_alloc(MAX_UPQ, M_MRTABLE,
400 	    M_NOWAIT, &V_buf_ring_mtx);
401 	if (rt->mfc_stall_ring == NULL) {
402 		free(rt, M_MRTABLE);
403 		return NULL;
404 	}
405 
406 	return rt;
407 }
408 
409 /*
410  * Handle MRT setsockopt commands to modify the multicast forwarding tables.
411  */
412 static int
413 X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
414 {
415 	int error, optval;
416 	vifi_t vifi;
417 	struct vifctl vifc;
418 	struct mfcctl2 mfc;
419 	struct bw_upcall bw_upcall;
420 	uint32_t i;
421 
422 	if (so != V_ip_mrouter && sopt->sopt_name != MRT_INIT)
423 		return EPERM;
424 
425 	error = 0;
426 	switch (sopt->sopt_name) {
427 	case MRT_INIT:
428 		error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
429 		if (error)
430 			break;
431 		error = ip_mrouter_init(so, optval);
432 		break;
433 	case MRT_DONE:
434 		error = ip_mrouter_done();
435 		break;
436 	case MRT_ADD_VIF:
437 		error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
438 		if (error)
439 			break;
440 		error = add_vif(&vifc);
441 		break;
442 	case MRT_DEL_VIF:
443 		error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
444 		if (error)
445 			break;
446 		error = del_vif(vifi);
447 		break;
448 	case MRT_ADD_MFC:
449 	case MRT_DEL_MFC:
450 		/*
451 		 * select data size depending on API version.
452 		 */
453 		if (sopt->sopt_name == MRT_ADD_MFC &&
454 		    V_mrt_api_config & MRT_API_FLAGS_ALL) {
455 			error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl2),
456 			    sizeof(struct mfcctl2));
457 		} else {
458 			error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl),
459 			    sizeof(struct mfcctl));
460 			bzero((caddr_t)&mfc + sizeof(struct mfcctl),
461 			    sizeof(mfc) - sizeof(struct mfcctl));
462 		}
463 		if (error)
464 			break;
465 		if (sopt->sopt_name == MRT_ADD_MFC)
466 			error = add_mfc(&mfc);
467 		else
468 			error = del_mfc(&mfc);
469 		break;
470 
471 	case MRT_ASSERT:
472 		error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
473 		if (error)
474 			break;
475 		set_assert(optval);
476 		break;
477 
478 	case MRT_API_CONFIG:
479 		error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
480 		if (!error)
481 			error = set_api_config(&i);
482 		if (!error)
483 			error = sooptcopyout(sopt, &i, sizeof i);
484 		break;
485 
486 	case MRT_ADD_BW_UPCALL:
487 	case MRT_DEL_BW_UPCALL:
488 		error = sooptcopyin(sopt, &bw_upcall, sizeof bw_upcall,
489 		    sizeof bw_upcall);
490 		if (error)
491 			break;
492 		if (sopt->sopt_name == MRT_ADD_BW_UPCALL)
493 			error = add_bw_upcall(&bw_upcall);
494 		else
495 			error = del_bw_upcall(&bw_upcall);
496 		break;
497 
498 	default:
499 		error = EOPNOTSUPP;
500 		break;
501 	}
502 	return error;
503 }
504 
505 /*
506  * Handle MRT getsockopt commands
507  */
508 static int
509 X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
510 {
511 	int error;
512 
513 	switch (sopt->sopt_name) {
514 	case MRT_VERSION:
515 		error = sooptcopyout(sopt, &mrt_api_version,
516 		    sizeof mrt_api_version);
517 		break;
518 	case MRT_ASSERT:
519 		error = sooptcopyout(sopt, &V_pim_assert_enabled,
520 		    sizeof V_pim_assert_enabled);
521 		break;
522 	case MRT_API_SUPPORT:
523 		error = sooptcopyout(sopt, &mrt_api_support,
524 		    sizeof mrt_api_support);
525 		break;
526 	case MRT_API_CONFIG:
527 		error = sooptcopyout(sopt, &V_mrt_api_config,
528 		    sizeof V_mrt_api_config);
529 		break;
530 	default:
531 		error = EOPNOTSUPP;
532 		break;
533 	}
534 	return error;
535 }
536 
537 /*
538  * Handle ioctl commands to obtain information from the cache
539  */
540 static int
541 X_mrt_ioctl(u_long cmd, caddr_t data, int fibnum __unused)
542 {
543 	int error;
544 
545 	/*
546 	 * Currently the only function calling this ioctl routine is rtioctl_fib().
547 	 * Typically, only root can create the raw socket in order to execute
548 	 * this ioctl method, however the request might be coming from a prison
549 	 */
550 	error = priv_check(curthread, PRIV_NETINET_MROUTE);
551 	if (error)
552 		return (error);
553 	switch (cmd) {
554 	case (SIOCGETVIFCNT):
555 		error = get_vif_cnt((struct sioc_vif_req *)data);
556 		break;
557 
558 	case (SIOCGETSGCNT):
559 		error = get_sg_cnt((struct sioc_sg_req *)data);
560 		break;
561 
562 	default:
563 		error = EINVAL;
564 		break;
565 	}
566 	return error;
567 }
568 
569 /*
570  * returns the packet, byte, rpf-failure count for the source group provided
571  */
572 static int
573 get_sg_cnt(struct sioc_sg_req *req)
574 {
575 	struct mfc *rt;
576 
577 	MRW_RLOCK();
578 	rt = mfc_find(&req->src, &req->grp);
579 	if (rt == NULL) {
580 		MRW_RUNLOCK();
581 		req->pktcnt = req->bytecnt = req->wrong_if = 0xffffffff;
582 		return EADDRNOTAVAIL;
583 	}
584 	req->pktcnt = rt->mfc_pkt_cnt;
585 	req->bytecnt = rt->mfc_byte_cnt;
586 	req->wrong_if = rt->mfc_wrong_if;
587 	MRW_RUNLOCK();
588 	return 0;
589 }
590 
591 /*
592  * returns the input and output packet and byte counts on the vif provided
593  */
594 static int
595 get_vif_cnt(struct sioc_vif_req *req)
596 {
597 	vifi_t vifi = req->vifi;
598 
599 	MRW_RLOCK();
600 	if (vifi >= V_numvifs) {
601 		MRW_RUNLOCK();
602 		return EINVAL;
603 	}
604 
605 	mtx_lock_spin(&V_viftable[vifi].v_spin);
606 	req->icount = V_viftable[vifi].v_pkt_in;
607 	req->ocount = V_viftable[vifi].v_pkt_out;
608 	req->ibytes = V_viftable[vifi].v_bytes_in;
609 	req->obytes = V_viftable[vifi].v_bytes_out;
610 	mtx_unlock_spin(&V_viftable[vifi].v_spin);
611 	MRW_RUNLOCK();
612 
613 	return 0;
614 }
615 
616 static void
617 if_detached_event(void *arg __unused, struct ifnet *ifp)
618 {
619 	vifi_t vifi;
620 	u_long i, vifi_cnt = 0;
621 	struct ifnet *free_ptr, *multi_leave;
622 
623 	MRW_WLOCK();
624 
625 	if (V_ip_mrouter == NULL) {
626 		MRW_WUNLOCK();
627 		return;
628 	}
629 
630 	/*
631 	 * Tear down multicast forwarder state associated with this ifnet.
632 	 * 1. Walk the vif list, matching vifs against this ifnet.
633 	 * 2. Walk the multicast forwarding cache (mfc) looking for
634 	 *    inner matches with this vif's index.
635 	 * 3. Expire any matching multicast forwarding cache entries.
636 	 * 4. Free vif state. This should disable ALLMULTI on the interface.
637 	 */
638 restart:
639 	for (vifi = 0; vifi < V_numvifs; vifi++) {
640 		if (V_viftable[vifi].v_ifp != ifp)
641 			continue;
642 		for (i = 0; i < mfchashsize; i++) {
643 			struct mfc *rt, *nrt;
644 
645 			LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
646 				if (rt->mfc_parent == vifi) {
647 					expire_mfc(rt);
648 				}
649 			}
650 		}
651 		del_vif_locked(vifi, &multi_leave, &free_ptr);
652 		if (free_ptr != NULL)
653 			vifi_cnt++;
654 		if (multi_leave) {
655 			MRW_WUNLOCK();
656 			if_allmulti(multi_leave, 0);
657 			MRW_WLOCK();
658 			goto restart;
659 		}
660 	}
661 
662 	MRW_WUNLOCK();
663 
664 	/*
665 	 * Free IFP. We don't have to use free_ptr here as it is the same
666 	 * that ifp. Perform free as many times as required in case
667 	 * refcount is greater than 1.
668 	 */
669 	for (i = 0; i < vifi_cnt; i++)
670 		if_free(ifp);
671 }
672 
673 static void
674 ip_mrouter_upcall_thread(void *arg, int pending __unused)
675 {
676 	CURVNET_SET((struct vnet *) arg);
677 
678 	MRW_WLOCK();
679 	bw_upcalls_send();
680 	MRW_WUNLOCK();
681 
682 	CURVNET_RESTORE();
683 }
684 
685 /*
686  * Enable multicast forwarding.
687  */
688 static int
689 ip_mrouter_init(struct socket *so, int version)
690 {
691 
692 	CTR2(KTR_IPMF, "%s: so %p", __func__, so);
693 
694 	if (version != 1)
695 		return ENOPROTOOPT;
696 
697 	MRW_WLOCK();
698 
699 	if (ip_mrouter_unloading) {
700 		MRW_WUNLOCK();
701 		return ENOPROTOOPT;
702 	}
703 
704 	if (V_ip_mrouter != NULL) {
705 		MRW_WUNLOCK();
706 		return EADDRINUSE;
707 	}
708 
709 	V_mfchashtbl = hashinit_flags(mfchashsize, M_MRTABLE, &V_mfchash,
710 	    HASH_NOWAIT);
711 	if (V_mfchashtbl == NULL) {
712 		MRW_WUNLOCK();
713 		return (ENOMEM);
714 	}
715 
716 	/* Create upcall ring */
717 	mtx_init(&V_bw_upcalls_ring_mtx, "mroute upcall buf_ring mtx", NULL, MTX_DEF);
718 	V_bw_upcalls_ring = buf_ring_alloc(BW_UPCALLS_MAX, M_MRTABLE,
719 	    M_NOWAIT, &V_bw_upcalls_ring_mtx);
720 	if (!V_bw_upcalls_ring) {
721 		MRW_WUNLOCK();
722 		return (ENOMEM);
723 	}
724 
725 	TASK_INIT(&V_task, 0, ip_mrouter_upcall_thread, curvnet);
726 	taskqueue_cancel(V_task_queue, &V_task, NULL);
727 	taskqueue_unblock(V_task_queue);
728 
729 	callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
730 	    curvnet);
731 	callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
732 	    curvnet);
733 
734 	V_ip_mrouter = so;
735 	atomic_add_int(&ip_mrouter_cnt, 1);
736 
737 	/* This is a mutex required by buf_ring init, but not used internally */
738 	mtx_init(&V_buf_ring_mtx, "mroute buf_ring mtx", NULL, MTX_DEF);
739 
740 	MRW_WUNLOCK();
741 
742 	CTR1(KTR_IPMF, "%s: done", __func__);
743 
744 	return 0;
745 }
746 
747 /*
748  * Disable multicast forwarding.
749  */
750 static int
751 X_ip_mrouter_done(void)
752 {
753 	struct ifnet **ifps;
754 	int nifp;
755 	u_long i;
756 	vifi_t vifi;
757 	struct bw_upcall *bu;
758 
759 	if (V_ip_mrouter == NULL)
760 		return (EINVAL);
761 
762 	/*
763 	 * Detach/disable hooks to the reset of the system.
764 	 */
765 	V_ip_mrouter = NULL;
766 	atomic_subtract_int(&ip_mrouter_cnt, 1);
767 	V_mrt_api_config = 0;
768 
769 	/*
770 	 * Wait for all epoch sections to complete to ensure
771 	 * V_ip_mrouter = NULL is visible to others.
772 	 */
773 	epoch_wait_preempt(net_epoch_preempt);
774 
775 	/* Stop and drain task queue */
776 	taskqueue_block(V_task_queue);
777 	while (taskqueue_cancel(V_task_queue, &V_task, NULL)) {
778 		taskqueue_drain(V_task_queue, &V_task);
779 	}
780 
781 	ifps = malloc(MAXVIFS * sizeof(*ifps), M_TEMP, M_WAITOK);
782 
783 	MRW_WLOCK();
784 	taskqueue_cancel(V_task_queue, &V_task, NULL);
785 
786 	/* Destroy upcall ring */
787 	while ((bu = buf_ring_dequeue_mc(V_bw_upcalls_ring)) != NULL) {
788 		free(bu, M_MRTABLE);
789 	}
790 	buf_ring_free(V_bw_upcalls_ring, M_MRTABLE);
791 	mtx_destroy(&V_bw_upcalls_ring_mtx);
792 
793 	/*
794 	 * For each phyint in use, prepare to disable promiscuous reception
795 	 * of all IP multicasts.  Defer the actual call until the lock is released;
796 	 * just record the list of interfaces while locked.  Some interfaces use
797 	 * sx locks in their ioctl routines, which is not allowed while holding
798 	 * a non-sleepable lock.
799 	 */
800 	KASSERT(V_numvifs <= MAXVIFS, ("More vifs than possible"));
801 	for (vifi = 0, nifp = 0; vifi < V_numvifs; vifi++) {
802 		if (!in_nullhost(V_viftable[vifi].v_lcl_addr) &&
803 		    !(V_viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
804 			ifps[nifp++] = V_viftable[vifi].v_ifp;
805 		}
806 	}
807 	bzero((caddr_t)V_viftable, sizeof(*V_viftable) * MAXVIFS);
808 	V_numvifs = 0;
809 	V_pim_assert_enabled = 0;
810 
811 	callout_stop(&V_expire_upcalls_ch);
812 	callout_stop(&V_bw_upcalls_ch);
813 
814 	/*
815 	 * Free all multicast forwarding cache entries.
816 	 * Do not use hashdestroy(), as we must perform other cleanup.
817 	 */
818 	for (i = 0; i < mfchashsize; i++) {
819 		struct mfc *rt, *nrt;
820 
821 		LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
822 			expire_mfc(rt);
823 		}
824 	}
825 	free(V_mfchashtbl, M_MRTABLE);
826 	V_mfchashtbl = NULL;
827 
828 	bzero(V_nexpire, sizeof(V_nexpire[0]) * mfchashsize);
829 
830 	V_reg_vif_num = VIFI_INVALID;
831 
832 	mtx_destroy(&V_buf_ring_mtx);
833 
834 	MRW_WUNLOCK();
835 
836 	/*
837 	 * Now drop our claim on promiscuous multicast on the interfaces recorded
838 	 * above.  This is safe to do now because ALLMULTI is reference counted.
839 	 */
840 	for (vifi = 0; vifi < nifp; vifi++)
841 		if_allmulti(ifps[vifi], 0);
842 	free(ifps, M_TEMP);
843 
844 	CTR1(KTR_IPMF, "%s: done", __func__);
845 
846 	return 0;
847 }
848 
849 /*
850  * Set PIM assert processing global
851  */
852 static int
853 set_assert(int i)
854 {
855 	if ((i != 1) && (i != 0))
856 		return EINVAL;
857 
858 	V_pim_assert_enabled = i;
859 
860 	return 0;
861 }
862 
863 /*
864  * Configure API capabilities
865  */
866 int
867 set_api_config(uint32_t *apival)
868 {
869 	u_long i;
870 
871 	/*
872 	 * We can set the API capabilities only if it is the first operation
873 	 * after MRT_INIT. I.e.:
874 	 *  - there are no vifs installed
875 	 *  - pim_assert is not enabled
876 	 *  - the MFC table is empty
877 	 */
878 	if (V_numvifs > 0) {
879 		*apival = 0;
880 		return EPERM;
881 	}
882 	if (V_pim_assert_enabled) {
883 		*apival = 0;
884 		return EPERM;
885 	}
886 
887 	MRW_RLOCK();
888 
889 	for (i = 0; i < mfchashsize; i++) {
890 		if (LIST_FIRST(&V_mfchashtbl[i]) != NULL) {
891 			MRW_RUNLOCK();
892 			*apival = 0;
893 			return EPERM;
894 		}
895 	}
896 
897 	MRW_RUNLOCK();
898 
899 	V_mrt_api_config = *apival & mrt_api_support;
900 	*apival = V_mrt_api_config;
901 
902 	return 0;
903 }
904 
905 /*
906  * Add a vif to the vif table
907  */
908 static int
909 add_vif(struct vifctl *vifcp)
910 {
911 	struct vif *vifp = V_viftable + vifcp->vifc_vifi;
912 	struct sockaddr_in sin = {sizeof sin, AF_INET};
913 	struct ifaddr *ifa;
914 	struct ifnet *ifp;
915 	int error;
916 
917 	if (vifcp->vifc_vifi >= MAXVIFS)
918 		return EINVAL;
919 	/* rate limiting is no longer supported by this code */
920 	if (vifcp->vifc_rate_limit != 0) {
921 		log(LOG_ERR, "rate limiting is no longer supported\n");
922 		return EINVAL;
923 	}
924 
925 	if (in_nullhost(vifcp->vifc_lcl_addr))
926 		return EADDRNOTAVAIL;
927 
928 	/* Find the interface with an address in AF_INET family */
929 	if (vifcp->vifc_flags & VIFF_REGISTER) {
930 		/*
931 		 * XXX: Because VIFF_REGISTER does not really need a valid
932 		 * local interface (e.g. it could be 127.0.0.2), we don't
933 		 * check its address.
934 		 */
935 		ifp = NULL;
936 	} else {
937 		struct epoch_tracker et;
938 
939 		sin.sin_addr = vifcp->vifc_lcl_addr;
940 		NET_EPOCH_ENTER(et);
941 		ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
942 		if (ifa == NULL) {
943 			NET_EPOCH_EXIT(et);
944 			return EADDRNOTAVAIL;
945 		}
946 		ifp = ifa->ifa_ifp;
947 		/* XXX FIXME we need to take a ref on ifp and cleanup properly! */
948 		NET_EPOCH_EXIT(et);
949 	}
950 
951 	if ((vifcp->vifc_flags & VIFF_TUNNEL) != 0) {
952 		CTR1(KTR_IPMF, "%s: tunnels are no longer supported", __func__);
953 		return EOPNOTSUPP;
954 	} else if (vifcp->vifc_flags & VIFF_REGISTER) {
955 		ifp = V_multicast_register_if = if_alloc(IFT_LOOP);
956 		CTR2(KTR_IPMF, "%s: add register vif for ifp %p", __func__, ifp);
957 		if (V_reg_vif_num == VIFI_INVALID) {
958 			if_initname(V_multicast_register_if, "register_vif", 0);
959 			V_reg_vif_num = vifcp->vifc_vifi;
960 		}
961 	} else {		/* Make sure the interface supports multicast */
962 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
963 			return EOPNOTSUPP;
964 
965 		/* Enable promiscuous reception of all IP multicasts from the if */
966 		error = if_allmulti(ifp, 1);
967 		if (error)
968 			return error;
969 	}
970 
971 	MRW_WLOCK();
972 
973 	if (!in_nullhost(vifp->v_lcl_addr)) {
974 		if (ifp)
975 			V_multicast_register_if = NULL;
976 		MRW_WUNLOCK();
977 		if (ifp)
978 			if_free(ifp);
979 		return EADDRINUSE;
980 	}
981 
982 	vifp->v_flags     = vifcp->vifc_flags;
983 	vifp->v_threshold = vifcp->vifc_threshold;
984 	vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
985 	vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
986 	vifp->v_ifp       = ifp;
987 	/* initialize per vif pkt counters */
988 	vifp->v_pkt_in    = 0;
989 	vifp->v_pkt_out   = 0;
990 	vifp->v_bytes_in  = 0;
991 	vifp->v_bytes_out = 0;
992 	sprintf(vifp->v_spin_name, "BM[%d] spin", vifcp->vifc_vifi);
993 	mtx_init(&vifp->v_spin, vifp->v_spin_name, NULL, MTX_SPIN);
994 
995 	/* Adjust numvifs up if the vifi is higher than numvifs */
996 	if (V_numvifs <= vifcp->vifc_vifi)
997 		V_numvifs = vifcp->vifc_vifi + 1;
998 
999 	MRW_WUNLOCK();
1000 
1001 	CTR4(KTR_IPMF, "%s: add vif %d laddr 0x%08x thresh %x", __func__,
1002 	    (int)vifcp->vifc_vifi, ntohl(vifcp->vifc_lcl_addr.s_addr),
1003 	    (int)vifcp->vifc_threshold);
1004 
1005 	return 0;
1006 }
1007 
1008 /*
1009  * Delete a vif from the vif table
1010  */
1011 static int
1012 del_vif_locked(vifi_t vifi, struct ifnet **ifp_multi_leave, struct ifnet **ifp_free)
1013 {
1014 	struct vif *vifp;
1015 
1016 	*ifp_free = NULL;
1017 	*ifp_multi_leave = NULL;
1018 
1019 	MRW_WLOCK_ASSERT();
1020 
1021 	if (vifi >= V_numvifs) {
1022 		return EINVAL;
1023 	}
1024 	vifp = &V_viftable[vifi];
1025 	if (in_nullhost(vifp->v_lcl_addr)) {
1026 		return EADDRNOTAVAIL;
1027 	}
1028 
1029 	if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
1030 		*ifp_multi_leave = vifp->v_ifp;
1031 
1032 	if (vifp->v_flags & VIFF_REGISTER) {
1033 		V_reg_vif_num = VIFI_INVALID;
1034 		if (vifp->v_ifp) {
1035 			if (vifp->v_ifp == V_multicast_register_if)
1036 				V_multicast_register_if = NULL;
1037 			*ifp_free = vifp->v_ifp;
1038 		}
1039 	}
1040 
1041 	mtx_destroy(&vifp->v_spin);
1042 
1043 	bzero((caddr_t)vifp, sizeof (*vifp));
1044 
1045 	CTR2(KTR_IPMF, "%s: delete vif %d", __func__, (int)vifi);
1046 
1047 	/* Adjust numvifs down */
1048 	for (vifi = V_numvifs; vifi > 0; vifi--)
1049 		if (!in_nullhost(V_viftable[vifi-1].v_lcl_addr))
1050 			break;
1051 	V_numvifs = vifi;
1052 
1053 	return 0;
1054 }
1055 
1056 static int
1057 del_vif(vifi_t vifi)
1058 {
1059 	int cc;
1060 	struct ifnet *free_ptr, *multi_leave;
1061 
1062 	MRW_WLOCK();
1063 	cc = del_vif_locked(vifi, &multi_leave, &free_ptr);
1064 	MRW_WUNLOCK();
1065 
1066 	if (multi_leave)
1067 		if_allmulti(multi_leave, 0);
1068 	if (free_ptr) {
1069 		if_free(free_ptr);
1070 	}
1071 
1072 	return cc;
1073 }
1074 
1075 /*
1076  * update an mfc entry without resetting counters and S,G addresses.
1077  */
1078 static void
1079 update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1080 {
1081 	int i;
1082 
1083 	rt->mfc_parent = mfccp->mfcc_parent;
1084 	for (i = 0; i < V_numvifs; i++) {
1085 		rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1086 		rt->mfc_flags[i] = mfccp->mfcc_flags[i] & V_mrt_api_config &
1087 			MRT_MFC_FLAGS_ALL;
1088 	}
1089 	/* set the RP address */
1090 	if (V_mrt_api_config & MRT_MFC_RP)
1091 		rt->mfc_rp = mfccp->mfcc_rp;
1092 	else
1093 		rt->mfc_rp.s_addr = INADDR_ANY;
1094 }
1095 
1096 /*
1097  * fully initialize an mfc entry from the parameter.
1098  */
1099 static void
1100 init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1101 {
1102 	rt->mfc_origin     = mfccp->mfcc_origin;
1103 	rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
1104 
1105 	update_mfc_params(rt, mfccp);
1106 
1107 	/* initialize pkt counters per src-grp */
1108 	rt->mfc_pkt_cnt    = 0;
1109 	rt->mfc_byte_cnt   = 0;
1110 	rt->mfc_wrong_if   = 0;
1111 	timevalclear(&rt->mfc_last_assert);
1112 }
1113 
1114 static void
1115 expire_mfc(struct mfc *rt)
1116 {
1117 	struct rtdetq *rte;
1118 
1119 	MRW_WLOCK_ASSERT();
1120 
1121 	free_bw_list(rt->mfc_bw_meter_leq);
1122 	free_bw_list(rt->mfc_bw_meter_geq);
1123 
1124 	while (!buf_ring_empty(rt->mfc_stall_ring)) {
1125 		rte = buf_ring_dequeue_mc(rt->mfc_stall_ring);
1126 		if (rte) {
1127 			m_freem(rte->m);
1128 			free(rte, M_MRTABLE);
1129 		}
1130 	}
1131 	buf_ring_free(rt->mfc_stall_ring, M_MRTABLE);
1132 
1133 	LIST_REMOVE(rt, mfc_hash);
1134 	free(rt, M_MRTABLE);
1135 }
1136 
1137 /*
1138  * Add an mfc entry
1139  */
1140 static int
1141 add_mfc(struct mfcctl2 *mfccp)
1142 {
1143 	struct mfc *rt;
1144 	struct rtdetq *rte;
1145 	u_long hash = 0;
1146 	u_short nstl;
1147 	struct epoch_tracker et;
1148 
1149 	MRW_WLOCK();
1150 	rt = mfc_find(&mfccp->mfcc_origin, &mfccp->mfcc_mcastgrp);
1151 
1152 	/* If an entry already exists, just update the fields */
1153 	if (rt) {
1154 		CTR4(KTR_IPMF, "%s: update mfc orig 0x%08x group %lx parent %x",
1155 		    __func__, ntohl(mfccp->mfcc_origin.s_addr),
1156 		    (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1157 		    mfccp->mfcc_parent);
1158 		update_mfc_params(rt, mfccp);
1159 		MRW_WUNLOCK();
1160 		return (0);
1161 	}
1162 
1163 	/*
1164 	 * Find the entry for which the upcall was made and update
1165 	 */
1166 	nstl = 0;
1167 	hash = MFCHASH(mfccp->mfcc_origin, mfccp->mfcc_mcastgrp);
1168 	NET_EPOCH_ENTER(et);
1169 	LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1170 		if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1171 		    in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp) &&
1172 		    !buf_ring_empty(rt->mfc_stall_ring)) {
1173 			CTR5(KTR_IPMF,
1174 			   "%s: add mfc orig 0x%08x group %lx parent %x qh %p",
1175 			    __func__, ntohl(mfccp->mfcc_origin.s_addr),
1176 			    (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1177 			    mfccp->mfcc_parent,
1178 			    rt->mfc_stall_ring);
1179 			if (nstl++)
1180 				CTR1(KTR_IPMF, "%s: multiple matches", __func__);
1181 
1182 			init_mfc_params(rt, mfccp);
1183 			rt->mfc_expire = 0;	/* Don't clean this guy up */
1184 			V_nexpire[hash]--;
1185 
1186 			/* Free queued packets, but attempt to forward them first. */
1187 			while (!buf_ring_empty(rt->mfc_stall_ring)) {
1188 				rte = buf_ring_dequeue_mc(rt->mfc_stall_ring);
1189 				if (rte->ifp != NULL)
1190 					ip_mdq(rte->m, rte->ifp, rt, -1);
1191 				m_freem(rte->m);
1192 				free(rte, M_MRTABLE);
1193 			}
1194 		}
1195 	}
1196 	NET_EPOCH_EXIT(et);
1197 
1198 	/*
1199 	 * It is possible that an entry is being inserted without an upcall
1200 	 */
1201 	if (nstl == 0) {
1202 		CTR1(KTR_IPMF, "%s: adding mfc w/o upcall", __func__);
1203 		LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1204 			if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1205 			    in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp)) {
1206 				init_mfc_params(rt, mfccp);
1207 				if (rt->mfc_expire)
1208 					V_nexpire[hash]--;
1209 				rt->mfc_expire = 0;
1210 				break; /* XXX */
1211 			}
1212 		}
1213 
1214 		if (rt == NULL) {		/* no upcall, so make a new entry */
1215 			rt = mfc_alloc();
1216 			if (rt == NULL) {
1217 				MRW_WUNLOCK();
1218 				return (ENOBUFS);
1219 			}
1220 
1221 			init_mfc_params(rt, mfccp);
1222 
1223 			rt->mfc_expire     = 0;
1224 			rt->mfc_bw_meter_leq = NULL;
1225 			rt->mfc_bw_meter_geq = NULL;
1226 
1227 			/* insert new entry at head of hash chain */
1228 			LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1229 		}
1230 	}
1231 
1232 	MRW_WUNLOCK();
1233 
1234 	return (0);
1235 }
1236 
1237 /*
1238  * Delete an mfc entry
1239  */
1240 static int
1241 del_mfc(struct mfcctl2 *mfccp)
1242 {
1243 	struct in_addr origin;
1244 	struct in_addr mcastgrp;
1245 	struct mfc *rt;
1246 
1247 	origin = mfccp->mfcc_origin;
1248 	mcastgrp = mfccp->mfcc_mcastgrp;
1249 
1250 	CTR3(KTR_IPMF, "%s: delete mfc orig 0x%08x group %lx", __func__,
1251 			ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
1252 
1253 	MRW_WLOCK();
1254 
1255 	rt = mfc_find(&origin, &mcastgrp);
1256 	if (rt == NULL) {
1257 		MRW_WUNLOCK();
1258 		return EADDRNOTAVAIL;
1259 	}
1260 
1261 	/*
1262 	 * free the bw_meter entries
1263 	 */
1264 	free_bw_list(rt->mfc_bw_meter_leq);
1265 	rt->mfc_bw_meter_leq = NULL;
1266 	free_bw_list(rt->mfc_bw_meter_geq);
1267 	rt->mfc_bw_meter_geq = NULL;
1268 
1269 	LIST_REMOVE(rt, mfc_hash);
1270 	free(rt, M_MRTABLE);
1271 
1272 	MRW_WUNLOCK();
1273 
1274 	return (0);
1275 }
1276 
1277 /*
1278  * Send a message to the routing daemon on the multicast routing socket.
1279  */
1280 static int
1281 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1282 {
1283 	if (s) {
1284 		SOCKBUF_LOCK(&s->so_rcv);
1285 		if (sbappendaddr_locked(&s->so_rcv, (struct sockaddr *)src, mm,
1286 		    NULL) != 0) {
1287 			sorwakeup_locked(s);
1288 			return 0;
1289 		}
1290 		soroverflow_locked(s);
1291 	}
1292 	m_freem(mm);
1293 	return -1;
1294 }
1295 
1296 /*
1297  * IP multicast forwarding function. This function assumes that the packet
1298  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1299  * pointed to by "ifp", and the packet is to be relayed to other networks
1300  * that have members of the packet's destination IP multicast group.
1301  *
1302  * The packet is returned unscathed to the caller, unless it is
1303  * erroneous, in which case a non-zero return value tells the caller to
1304  * discard it.
1305  */
1306 
1307 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1308 
1309 static int
1310 X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1311     struct ip_moptions *imo)
1312 {
1313 	struct mfc *rt;
1314 	int error;
1315 	vifi_t vifi;
1316 	struct mbuf *mb0;
1317 	struct rtdetq *rte;
1318 	u_long hash;
1319 	int hlen;
1320 
1321 	CTR3(KTR_IPMF, "ip_mforward: delete mfc orig 0x%08x group %lx ifp %p",
1322 	    ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr), ifp);
1323 
1324 	if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1325 	    ((u_char *)(ip + 1))[1] != IPOPT_LSRR) {
1326 		/*
1327 		 * Packet arrived via a physical interface or
1328 		 * an encapsulated tunnel or a register_vif.
1329 		 */
1330 	} else {
1331 		/*
1332 		 * Packet arrived through a source-route tunnel.
1333 		 * Source-route tunnels are no longer supported.
1334 		 */
1335 		return (1);
1336 	}
1337 
1338 	/*
1339 	 * BEGIN: MCAST ROUTING HOT PATH
1340 	 */
1341 	MRW_RLOCK();
1342 	if (imo && ((vifi = imo->imo_multicast_vif) < V_numvifs)) {
1343 		if (ip->ip_ttl < MAXTTL)
1344 			ip->ip_ttl++; /* compensate for -1 in *_send routines */
1345 		error = ip_mdq(m, ifp, NULL, vifi);
1346 		MRW_RUNLOCK();
1347 		return error;
1348 	}
1349 
1350 	/*
1351 	 * Don't forward a packet with time-to-live of zero or one,
1352 	 * or a packet destined to a local-only group.
1353 	 */
1354 	if (ip->ip_ttl <= 1 || IN_LOCAL_GROUP(ntohl(ip->ip_dst.s_addr))) {
1355 		MRW_RUNLOCK();
1356 		return 0;
1357 	}
1358 
1359 mfc_find_retry:
1360 	/*
1361 	 * Determine forwarding vifs from the forwarding cache table
1362 	 */
1363 	MRTSTAT_INC(mrts_mfc_lookups);
1364 	rt = mfc_find(&ip->ip_src, &ip->ip_dst);
1365 
1366 	/* Entry exists, so forward if necessary */
1367 	if (rt != NULL) {
1368 		error = ip_mdq(m, ifp, rt, -1);
1369 		/* Generic unlock here as we might release R or W lock */
1370 		MRW_UNLOCK();
1371 		return error;
1372 	}
1373 
1374 	/*
1375 	 * END: MCAST ROUTING HOT PATH
1376 	 */
1377 
1378 	/* Further processing must be done with WLOCK taken */
1379 	if ((MRW_WOWNED() == 0) && (MRW_LOCK_TRY_UPGRADE() == 0)) {
1380 		MRW_RUNLOCK();
1381 		MRW_WLOCK();
1382 		goto mfc_find_retry;
1383 	}
1384 
1385 	/*
1386 	 * If we don't have a route for packet's origin,
1387 	 * Make a copy of the packet & send message to routing daemon
1388 	 */
1389 	hlen = ip->ip_hl << 2;
1390 
1391 	MRTSTAT_INC(mrts_mfc_misses);
1392 	MRTSTAT_INC(mrts_no_route);
1393 	CTR2(KTR_IPMF, "ip_mforward: no mfc for (0x%08x,%lx)",
1394 	    ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr));
1395 
1396 	/*
1397 	 * Allocate mbufs early so that we don't do extra work if we are
1398 	 * just going to fail anyway.  Make sure to pullup the header so
1399 	 * that other people can't step on it.
1400 	 */
1401 	rte = malloc((sizeof *rte), M_MRTABLE, M_NOWAIT|M_ZERO);
1402 	if (rte == NULL) {
1403 		MRW_WUNLOCK();
1404 		return ENOBUFS;
1405 	}
1406 
1407 	mb0 = m_copypacket(m, M_NOWAIT);
1408 	if (mb0 && (!M_WRITABLE(mb0) || mb0->m_len < hlen))
1409 		mb0 = m_pullup(mb0, hlen);
1410 	if (mb0 == NULL) {
1411 		free(rte, M_MRTABLE);
1412 		MRW_WUNLOCK();
1413 		return ENOBUFS;
1414 	}
1415 
1416 	/* is there an upcall waiting for this flow ? */
1417 	hash = MFCHASH(ip->ip_src, ip->ip_dst);
1418 	LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash)
1419 	{
1420 		if (in_hosteq(ip->ip_src, rt->mfc_origin) &&
1421 		    in_hosteq(ip->ip_dst, rt->mfc_mcastgrp) &&
1422 		    !buf_ring_empty(rt->mfc_stall_ring))
1423 			break;
1424 	}
1425 
1426 	if (rt == NULL) {
1427 		int i;
1428 		struct igmpmsg *im;
1429 		struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1430 		struct mbuf *mm;
1431 
1432 		/*
1433 		 * Locate the vifi for the incoming interface for this packet.
1434 		 * If none found, drop packet.
1435 		 */
1436 		for (vifi = 0; vifi < V_numvifs &&
1437 		    V_viftable[vifi].v_ifp != ifp; vifi++)
1438 			;
1439 		if (vifi >= V_numvifs) /* vif not found, drop packet */
1440 			goto non_fatal;
1441 
1442 		/* no upcall, so make a new entry */
1443 		rt = mfc_alloc();
1444 		if (rt == NULL)
1445 			goto fail;
1446 
1447 		/* Make a copy of the header to send to the user level process */
1448 		mm = m_copym(mb0, 0, hlen, M_NOWAIT);
1449 		if (mm == NULL)
1450 			goto fail1;
1451 
1452 		/*
1453 		 * Send message to routing daemon to install
1454 		 * a route into the kernel table
1455 		 */
1456 
1457 		im = mtod(mm, struct igmpmsg*);
1458 		im->im_msgtype = IGMPMSG_NOCACHE;
1459 		im->im_mbz = 0;
1460 		im->im_vif = vifi;
1461 
1462 		MRTSTAT_INC(mrts_upcalls);
1463 
1464 		k_igmpsrc.sin_addr = ip->ip_src;
1465 		if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1466 			CTR0(KTR_IPMF, "ip_mforward: socket queue full");
1467 			MRTSTAT_INC(mrts_upq_sockfull);
1468 			fail1: free(rt, M_MRTABLE);
1469 			fail: free(rte, M_MRTABLE);
1470 			m_freem(mb0);
1471 			MRW_WUNLOCK();
1472 			return ENOBUFS;
1473 		}
1474 
1475 		/* insert new entry at head of hash chain */
1476 		rt->mfc_origin.s_addr = ip->ip_src.s_addr;
1477 		rt->mfc_mcastgrp.s_addr = ip->ip_dst.s_addr;
1478 		rt->mfc_expire = UPCALL_EXPIRE;
1479 		V_nexpire[hash]++;
1480 		for (i = 0; i < V_numvifs; i++) {
1481 			rt->mfc_ttls[i] = 0;
1482 			rt->mfc_flags[i] = 0;
1483 		}
1484 		rt->mfc_parent = -1;
1485 
1486 		/* clear the RP address */
1487 		rt->mfc_rp.s_addr = INADDR_ANY;
1488 		rt->mfc_bw_meter_leq = NULL;
1489 		rt->mfc_bw_meter_geq = NULL;
1490 
1491 		/* initialize pkt counters per src-grp */
1492 		rt->mfc_pkt_cnt = 0;
1493 		rt->mfc_byte_cnt = 0;
1494 		rt->mfc_wrong_if = 0;
1495 		timevalclear(&rt->mfc_last_assert);
1496 
1497 		buf_ring_enqueue(rt->mfc_stall_ring, rte);
1498 
1499 		/* Add RT to hashtable as it didn't exist before */
1500 		LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1501 	} else {
1502 		/* determine if queue has overflowed */
1503 		if (buf_ring_full(rt->mfc_stall_ring)) {
1504 			MRTSTAT_INC(mrts_upq_ovflw);
1505 			non_fatal: free(rte, M_MRTABLE);
1506 			m_freem(mb0);
1507 			MRW_WUNLOCK();
1508 			return (0);
1509 		}
1510 
1511 		buf_ring_enqueue(rt->mfc_stall_ring, rte);
1512 	}
1513 
1514 	rte->m = mb0;
1515 	rte->ifp = ifp;
1516 
1517 	MRW_WUNLOCK();
1518 
1519 	return 0;
1520 }
1521 
1522 /*
1523  * Clean up the cache entry if upcall is not serviced
1524  */
1525 static void
1526 expire_upcalls(void *arg)
1527 {
1528 	u_long i;
1529 
1530 	CURVNET_SET((struct vnet *) arg);
1531 
1532 	/*This callout is always run with MRW_WLOCK taken. */
1533 
1534 	for (i = 0; i < mfchashsize; i++) {
1535 		struct mfc *rt, *nrt;
1536 
1537 		if (V_nexpire[i] == 0)
1538 			continue;
1539 
1540 		LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
1541 			if (buf_ring_empty(rt->mfc_stall_ring))
1542 				continue;
1543 
1544 			if (rt->mfc_expire == 0 || --rt->mfc_expire > 0)
1545 				continue;
1546 
1547 			MRTSTAT_INC(mrts_cache_cleanups);
1548 			CTR3(KTR_IPMF, "%s: expire (%lx, %lx)", __func__,
1549 			    (u_long)ntohl(rt->mfc_origin.s_addr),
1550 			    (u_long)ntohl(rt->mfc_mcastgrp.s_addr));
1551 
1552 			expire_mfc(rt);
1553 		}
1554 	}
1555 
1556 	callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
1557 	    curvnet);
1558 
1559 	CURVNET_RESTORE();
1560 }
1561 
1562 /*
1563  * Packet forwarding routine once entry in the cache is made
1564  */
1565 static int
1566 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1567 {
1568 	struct ip *ip = mtod(m, struct ip *);
1569 	vifi_t vifi;
1570 	int plen = ntohs(ip->ip_len);
1571 
1572 	MRW_LOCK_ASSERT();
1573 	NET_EPOCH_ASSERT();
1574 
1575 	/*
1576 	 * If xmt_vif is not -1, send on only the requested vif.
1577 	 *
1578 	 * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1579 	 */
1580 	if (xmt_vif < V_numvifs) {
1581 		if (V_viftable[xmt_vif].v_flags & VIFF_REGISTER)
1582 			pim_register_send(ip, V_viftable + xmt_vif, m, rt);
1583 		else
1584 			phyint_send(ip, V_viftable + xmt_vif, m);
1585 		return 1;
1586 	}
1587 
1588 	/*
1589 	 * Don't forward if it didn't arrive from the parent vif for its origin.
1590 	 */
1591 	vifi = rt->mfc_parent;
1592 	if ((vifi >= V_numvifs) || (V_viftable[vifi].v_ifp != ifp)) {
1593 		CTR4(KTR_IPMF, "%s: rx on wrong ifp %p (vifi %d, v_ifp %p)",
1594 				__func__, ifp, (int)vifi, V_viftable[vifi].v_ifp);
1595 		MRTSTAT_INC(mrts_wrong_if);
1596 		++rt->mfc_wrong_if;
1597 		/*
1598 		 * If we are doing PIM assert processing, send a message
1599 		 * to the routing daemon.
1600 		 *
1601 		 * XXX: A PIM-SM router needs the WRONGVIF detection so it
1602 		 * can complete the SPT switch, regardless of the type
1603 		 * of the iif (broadcast media, GRE tunnel, etc).
1604 		 */
1605 		if (V_pim_assert_enabled && (vifi < V_numvifs) &&
1606 		    V_viftable[vifi].v_ifp) {
1607 			if (ifp == V_multicast_register_if)
1608 				PIMSTAT_INC(pims_rcv_registers_wrongiif);
1609 
1610 			/* Get vifi for the incoming packet */
1611 			for (vifi = 0; vifi < V_numvifs && V_viftable[vifi].v_ifp != ifp; vifi++)
1612 				;
1613 			if (vifi >= V_numvifs)
1614 				return 0;	/* The iif is not found: ignore the packet. */
1615 
1616 			if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1617 				return 0;	/* WRONGVIF disabled: ignore the packet */
1618 
1619 			if (ratecheck(&rt->mfc_last_assert, &pim_assert_interval)) {
1620 				struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1621 				struct igmpmsg *im;
1622 				int hlen = ip->ip_hl << 2;
1623 				struct mbuf *mm = m_copym(m, 0, hlen, M_NOWAIT);
1624 
1625 				if (mm && (!M_WRITABLE(mm) || mm->m_len < hlen))
1626 					mm = m_pullup(mm, hlen);
1627 				if (mm == NULL)
1628 					return ENOBUFS;
1629 
1630 				im = mtod(mm, struct igmpmsg *);
1631 				im->im_msgtype = IGMPMSG_WRONGVIF;
1632 				im->im_mbz = 0;
1633 				im->im_vif = vifi;
1634 
1635 				MRTSTAT_INC(mrts_upcalls);
1636 
1637 				k_igmpsrc.sin_addr = im->im_src;
1638 				if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1639 					CTR1(KTR_IPMF, "%s: socket queue full", __func__);
1640 					MRTSTAT_INC(mrts_upq_sockfull);
1641 					return ENOBUFS;
1642 				}
1643 			}
1644 		}
1645 		return 0;
1646 	}
1647 
1648 	/* If I sourced this packet, it counts as output, else it was input. */
1649 	mtx_lock_spin(&V_viftable[vifi].v_spin);
1650 	if (in_hosteq(ip->ip_src, V_viftable[vifi].v_lcl_addr)) {
1651 		V_viftable[vifi].v_pkt_out++;
1652 		V_viftable[vifi].v_bytes_out += plen;
1653 	} else {
1654 		V_viftable[vifi].v_pkt_in++;
1655 		V_viftable[vifi].v_bytes_in += plen;
1656 	}
1657 	mtx_unlock_spin(&V_viftable[vifi].v_spin);
1658 
1659 	rt->mfc_pkt_cnt++;
1660 	rt->mfc_byte_cnt += plen;
1661 
1662 	/*
1663 	 * For each vif, decide if a copy of the packet should be forwarded.
1664 	 * Forward if:
1665 	 *		- the ttl exceeds the vif's threshold
1666 	 *		- there are group members downstream on interface
1667 	 */
1668 	for (vifi = 0; vifi < V_numvifs; vifi++)
1669 		if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1670 			V_viftable[vifi].v_pkt_out++;
1671 			V_viftable[vifi].v_bytes_out += plen;
1672 			if (V_viftable[vifi].v_flags & VIFF_REGISTER)
1673 				pim_register_send(ip, V_viftable + vifi, m, rt);
1674 			else
1675 				phyint_send(ip, V_viftable + vifi, m);
1676 		}
1677 
1678 	/*
1679 	 * Perform upcall-related bw measuring.
1680 	 */
1681 	if ((rt->mfc_bw_meter_geq != NULL) || (rt->mfc_bw_meter_leq != NULL)) {
1682 		struct bw_meter *x;
1683 		struct timeval now;
1684 
1685 		microtime(&now);
1686 		/* Process meters for Greater-or-EQual case */
1687 		for (x = rt->mfc_bw_meter_geq; x != NULL; x = x->bm_mfc_next)
1688 			bw_meter_geq_receive_packet(x, plen, &now);
1689 
1690 		/* Process meters for Lower-or-EQual case */
1691 		for (x = rt->mfc_bw_meter_leq; x != NULL; x = x->bm_mfc_next) {
1692 			/*
1693 			 * Record that a packet is received.
1694 			 * Spin lock has to be taken as callout context
1695 			 * (expire_bw_meter_leq) might modify these fields
1696 			 * as well
1697 			 */
1698 			mtx_lock_spin(&x->bm_spin);
1699 			x->bm_measured.b_packets++;
1700 			x->bm_measured.b_bytes += plen;
1701 			mtx_unlock_spin(&x->bm_spin);
1702 		}
1703 	}
1704 
1705 	return 0;
1706 }
1707 
1708 /*
1709  * Check if a vif number is legal/ok. This is used by in_mcast.c.
1710  */
1711 static int
1712 X_legal_vif_num(int vif)
1713 {
1714 	int ret;
1715 
1716 	ret = 0;
1717 	if (vif < 0)
1718 		return (ret);
1719 
1720 	MRW_RLOCK();
1721 	if (vif < V_numvifs)
1722 		ret = 1;
1723 	MRW_RUNLOCK();
1724 
1725 	return (ret);
1726 }
1727 
1728 /*
1729  * Return the local address used by this vif
1730  */
1731 static u_long
1732 X_ip_mcast_src(int vifi)
1733 {
1734 	in_addr_t addr;
1735 
1736 	addr = INADDR_ANY;
1737 	if (vifi < 0)
1738 		return (addr);
1739 
1740 	MRW_RLOCK();
1741 	if (vifi < V_numvifs)
1742 		addr = V_viftable[vifi].v_lcl_addr.s_addr;
1743 	MRW_RUNLOCK();
1744 
1745 	return (addr);
1746 }
1747 
1748 static void
1749 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1750 {
1751 	struct mbuf *mb_copy;
1752 	int hlen = ip->ip_hl << 2;
1753 
1754 	MRW_LOCK_ASSERT();
1755 
1756 	/*
1757 	 * Make a new reference to the packet; make sure that
1758 	 * the IP header is actually copied, not just referenced,
1759 	 * so that ip_output() only scribbles on the copy.
1760 	 */
1761 	mb_copy = m_copypacket(m, M_NOWAIT);
1762 	if (mb_copy && (!M_WRITABLE(mb_copy) || mb_copy->m_len < hlen))
1763 		mb_copy = m_pullup(mb_copy, hlen);
1764 	if (mb_copy == NULL)
1765 		return;
1766 
1767 	send_packet(vifp, mb_copy);
1768 }
1769 
1770 static void
1771 send_packet(struct vif *vifp, struct mbuf *m)
1772 {
1773 	struct ip_moptions imo;
1774 	int error __unused;
1775 
1776 	MRW_LOCK_ASSERT();
1777 	NET_EPOCH_ASSERT();
1778 
1779 	imo.imo_multicast_ifp  = vifp->v_ifp;
1780 	imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1781 	imo.imo_multicast_loop = !!in_mcast_loop;
1782 	imo.imo_multicast_vif  = -1;
1783 	STAILQ_INIT(&imo.imo_head);
1784 
1785 	/*
1786 	 * Re-entrancy should not be a problem here, because
1787 	 * the packets that we send out and are looped back at us
1788 	 * should get rejected because they appear to come from
1789 	 * the loopback interface, thus preventing looping.
1790 	 */
1791 	error = ip_output(m, NULL, NULL, IP_FORWARDING, &imo, NULL);
1792 	CTR3(KTR_IPMF, "%s: vif %td err %d", __func__,
1793 	    (ptrdiff_t)(vifp - V_viftable), error);
1794 }
1795 
1796 /*
1797  * Stubs for old RSVP socket shim implementation.
1798  */
1799 
1800 static int
1801 X_ip_rsvp_vif(struct socket *so __unused, struct sockopt *sopt __unused)
1802 {
1803 
1804 	return (EOPNOTSUPP);
1805 }
1806 
1807 static void
1808 X_ip_rsvp_force_done(struct socket *so __unused)
1809 {
1810 
1811 }
1812 
1813 static int
1814 X_rsvp_input(struct mbuf **mp, int *offp, int proto)
1815 {
1816 	struct mbuf *m;
1817 
1818 	m = *mp;
1819 	*mp = NULL;
1820 	if (!V_rsvp_on)
1821 		m_freem(m);
1822 	return (IPPROTO_DONE);
1823 }
1824 
1825 /*
1826  * Code for bandwidth monitors
1827  */
1828 
1829 /*
1830  * Define common interface for timeval-related methods
1831  */
1832 #define	BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
1833 #define	BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
1834 #define	BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
1835 
1836 static uint32_t
1837 compute_bw_meter_flags(struct bw_upcall *req)
1838 {
1839 	uint32_t flags = 0;
1840 
1841 	if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
1842 		flags |= BW_METER_UNIT_PACKETS;
1843 	if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
1844 		flags |= BW_METER_UNIT_BYTES;
1845 	if (req->bu_flags & BW_UPCALL_GEQ)
1846 		flags |= BW_METER_GEQ;
1847 	if (req->bu_flags & BW_UPCALL_LEQ)
1848 		flags |= BW_METER_LEQ;
1849 
1850 	return flags;
1851 }
1852 
1853 static void
1854 expire_bw_meter_leq(void *arg)
1855 {
1856 	struct bw_meter *x = arg;
1857 	struct timeval now;
1858 	/*
1859 	 * INFO:
1860 	 * callout is always executed with MRW_WLOCK taken
1861 	 */
1862 
1863 	CURVNET_SET((struct vnet *)x->arg);
1864 
1865 	microtime(&now);
1866 
1867 	/*
1868 	 * Test if we should deliver an upcall
1869 	 */
1870 	if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
1871 	    (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
1872 	    ((x->bm_flags & BW_METER_UNIT_BYTES) &&
1873 	    (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
1874 		/* Prepare an upcall for delivery */
1875 		bw_meter_prepare_upcall(x, &now);
1876 	}
1877 
1878 	/* Send all upcalls that are pending delivery */
1879 	taskqueue_enqueue(V_task_queue, &V_task);
1880 
1881 	/* Reset counters */
1882 	x->bm_start_time = now;
1883 	/* Spin lock has to be taken as ip_forward context
1884 	 * might modify these fields as well
1885 	 */
1886 	mtx_lock_spin(&x->bm_spin);
1887 	x->bm_measured.b_bytes = 0;
1888 	x->bm_measured.b_packets = 0;
1889 	mtx_unlock_spin(&x->bm_spin);
1890 
1891 	callout_schedule(&x->bm_meter_callout, tvtohz(&x->bm_threshold.b_time));
1892 
1893 	CURVNET_RESTORE();
1894 }
1895 
1896 /*
1897  * Add a bw_meter entry
1898  */
1899 static int
1900 add_bw_upcall(struct bw_upcall *req)
1901 {
1902 	struct mfc *mfc;
1903 	struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
1904 	BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
1905 	struct timeval now;
1906 	struct bw_meter *x, **bwm_ptr;
1907 	uint32_t flags;
1908 
1909 	if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
1910 		return EOPNOTSUPP;
1911 
1912 	/* Test if the flags are valid */
1913 	if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
1914 		return EINVAL;
1915 	if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
1916 		return EINVAL;
1917 	if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)) == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
1918 		return EINVAL;
1919 
1920 	/* Test if the threshold time interval is valid */
1921 	if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
1922 		return EINVAL;
1923 
1924 	flags = compute_bw_meter_flags(req);
1925 
1926 	/*
1927 	 * Find if we have already same bw_meter entry
1928 	 */
1929 	MRW_WLOCK();
1930 	mfc = mfc_find(&req->bu_src, &req->bu_dst);
1931 	if (mfc == NULL) {
1932 		MRW_WUNLOCK();
1933 		return EADDRNOTAVAIL;
1934 	}
1935 
1936 	/* Choose an appropriate bw_meter list */
1937 	if (req->bu_flags & BW_UPCALL_GEQ)
1938 		bwm_ptr = &mfc->mfc_bw_meter_geq;
1939 	else
1940 		bwm_ptr = &mfc->mfc_bw_meter_leq;
1941 
1942 	for (x = *bwm_ptr; x != NULL; x = x->bm_mfc_next) {
1943 		if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
1944 		    &req->bu_threshold.b_time, ==))
1945 		    && (x->bm_threshold.b_packets
1946 		    == req->bu_threshold.b_packets)
1947 		    && (x->bm_threshold.b_bytes
1948 		    == req->bu_threshold.b_bytes)
1949 		    && (x->bm_flags & BW_METER_USER_FLAGS)
1950 		    == flags) {
1951 			MRW_WUNLOCK();
1952 			return 0; /* XXX Already installed */
1953 		}
1954 	}
1955 
1956 	/* Allocate the new bw_meter entry */
1957 	x = malloc(sizeof(*x), M_BWMETER, M_ZERO | M_NOWAIT);
1958 	if (x == NULL) {
1959 		MRW_WUNLOCK();
1960 		return ENOBUFS;
1961 	}
1962 
1963 	/* Set the new bw_meter entry */
1964 	x->bm_threshold.b_time = req->bu_threshold.b_time;
1965 	microtime(&now);
1966 	x->bm_start_time = now;
1967 	x->bm_threshold.b_packets = req->bu_threshold.b_packets;
1968 	x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
1969 	x->bm_measured.b_packets = 0;
1970 	x->bm_measured.b_bytes = 0;
1971 	x->bm_flags = flags;
1972 	x->bm_time_next = NULL;
1973 	x->bm_mfc = mfc;
1974 	x->arg = curvnet;
1975 	sprintf(x->bm_spin_name, "BM spin %p", x);
1976 	mtx_init(&x->bm_spin, x->bm_spin_name, NULL, MTX_SPIN);
1977 
1978 	/* For LEQ case create periodic callout */
1979 	if (req->bu_flags & BW_UPCALL_LEQ) {
1980 		callout_init_rw(&x->bm_meter_callout, &mrouter_lock, CALLOUT_SHAREDLOCK);
1981 		callout_reset(&x->bm_meter_callout, tvtohz(&x->bm_threshold.b_time),
1982 		    expire_bw_meter_leq, x);
1983 	}
1984 
1985 	/* Add the new bw_meter entry to the front of entries for this MFC */
1986 	x->bm_mfc_next = *bwm_ptr;
1987 	*bwm_ptr = x;
1988 
1989 	MRW_WUNLOCK();
1990 
1991 	return 0;
1992 }
1993 
1994 static void
1995 free_bw_list(struct bw_meter *list)
1996 {
1997 	while (list != NULL) {
1998 		struct bw_meter *x = list;
1999 
2000 		/* MRW_WLOCK must be held here */
2001 		if (x->bm_flags & BW_METER_LEQ) {
2002 			callout_drain(&x->bm_meter_callout);
2003 			mtx_destroy(&x->bm_spin);
2004 		}
2005 
2006 		list = list->bm_mfc_next;
2007 		free(x, M_BWMETER);
2008 	}
2009 }
2010 
2011 /*
2012  * Delete one or multiple bw_meter entries
2013  */
2014 static int
2015 del_bw_upcall(struct bw_upcall *req)
2016 {
2017 	struct mfc *mfc;
2018 	struct bw_meter *x, **bwm_ptr;
2019 
2020 	if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
2021 		return EOPNOTSUPP;
2022 
2023 	MRW_WLOCK();
2024 
2025 	/* Find the corresponding MFC entry */
2026 	mfc = mfc_find(&req->bu_src, &req->bu_dst);
2027 	if (mfc == NULL) {
2028 		MRW_WUNLOCK();
2029 		return EADDRNOTAVAIL;
2030 	} else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2031 		/*
2032 		 * Delete all bw_meter entries for this mfc
2033 		 */
2034 		struct bw_meter *list;
2035 
2036 		/* Free LEQ list */
2037 		list = mfc->mfc_bw_meter_leq;
2038 		mfc->mfc_bw_meter_leq = NULL;
2039 		free_bw_list(list);
2040 
2041 		/* Free GEQ list */
2042 		list = mfc->mfc_bw_meter_geq;
2043 		mfc->mfc_bw_meter_geq = NULL;
2044 		free_bw_list(list);
2045 		MRW_WUNLOCK();
2046 		return 0;
2047 	} else {			/* Delete a single bw_meter entry */
2048 		struct bw_meter *prev;
2049 		uint32_t flags = 0;
2050 
2051 		flags = compute_bw_meter_flags(req);
2052 
2053 		/* Choose an appropriate bw_meter list */
2054 		if (req->bu_flags & BW_UPCALL_GEQ)
2055 			bwm_ptr = &mfc->mfc_bw_meter_geq;
2056 		else
2057 			bwm_ptr = &mfc->mfc_bw_meter_leq;
2058 
2059 		/* Find the bw_meter entry to delete */
2060 		for (prev = NULL, x = *bwm_ptr; x != NULL;
2061 				prev = x, x = x->bm_mfc_next) {
2062 			if ((BW_TIMEVALCMP(&x->bm_threshold.b_time, &req->bu_threshold.b_time, ==)) &&
2063 			    (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2064 			    (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2065 			    (x->bm_flags & BW_METER_USER_FLAGS) == flags)
2066 				break;
2067 		}
2068 		if (x != NULL) { /* Delete entry from the list for this MFC */
2069 			if (prev != NULL)
2070 				prev->bm_mfc_next = x->bm_mfc_next;	/* remove from middle*/
2071 			else
2072 				*bwm_ptr = x->bm_mfc_next;/* new head of list */
2073 
2074 			if (req->bu_flags & BW_UPCALL_LEQ)
2075 				callout_stop(&x->bm_meter_callout);
2076 
2077 			MRW_WUNLOCK();
2078 			/* Free the bw_meter entry */
2079 			free(x, M_BWMETER);
2080 			return 0;
2081 		} else {
2082 			MRW_WUNLOCK();
2083 			return EINVAL;
2084 		}
2085 	}
2086 	__assert_unreachable();
2087 }
2088 
2089 /*
2090  * Perform bandwidth measurement processing that may result in an upcall
2091  */
2092 static void
2093 bw_meter_geq_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2094 {
2095 	struct timeval delta;
2096 
2097 	MRW_LOCK_ASSERT();
2098 
2099 	delta = *nowp;
2100 	BW_TIMEVALDECR(&delta, &x->bm_start_time);
2101 
2102 	/*
2103 	 * Processing for ">=" type of bw_meter entry.
2104 	 * bm_spin does not have to be hold here as in GEQ
2105 	 * case this is the only context accessing bm_measured.
2106 	 */
2107 	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2108 	    /* Reset the bw_meter entry */
2109 	    x->bm_start_time = *nowp;
2110 	    x->bm_measured.b_packets = 0;
2111 	    x->bm_measured.b_bytes = 0;
2112 	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2113 	}
2114 
2115 	/* Record that a packet is received */
2116 	x->bm_measured.b_packets++;
2117 	x->bm_measured.b_bytes += plen;
2118 
2119 	/*
2120 	 * Test if we should deliver an upcall
2121 	 */
2122 	if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2123 		if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2124 		    (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2125 		    ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2126 		    (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2127 			/* Prepare an upcall for delivery */
2128 			bw_meter_prepare_upcall(x, nowp);
2129 			x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2130 		}
2131 	}
2132 }
2133 
2134 /*
2135  * Prepare a bandwidth-related upcall
2136  */
2137 static void
2138 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2139 {
2140 	struct timeval delta;
2141 	struct bw_upcall *u;
2142 
2143 	MRW_LOCK_ASSERT();
2144 
2145 	/*
2146 	 * Compute the measured time interval
2147 	 */
2148 	delta = *nowp;
2149 	BW_TIMEVALDECR(&delta, &x->bm_start_time);
2150 
2151 	/*
2152 	 * Set the bw_upcall entry
2153 	 */
2154 	u = malloc(sizeof(struct bw_upcall), M_MRTABLE, M_NOWAIT | M_ZERO);
2155 	if (!u) {
2156 		log(LOG_WARNING, "bw_meter_prepare_upcall: cannot allocate entry\n");
2157 		return;
2158 	}
2159 	u->bu_src = x->bm_mfc->mfc_origin;
2160 	u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2161 	u->bu_threshold.b_time = x->bm_threshold.b_time;
2162 	u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2163 	u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2164 	u->bu_measured.b_time = delta;
2165 	u->bu_measured.b_packets = x->bm_measured.b_packets;
2166 	u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2167 	u->bu_flags = 0;
2168 	if (x->bm_flags & BW_METER_UNIT_PACKETS)
2169 		u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2170 	if (x->bm_flags & BW_METER_UNIT_BYTES)
2171 		u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2172 	if (x->bm_flags & BW_METER_GEQ)
2173 		u->bu_flags |= BW_UPCALL_GEQ;
2174 	if (x->bm_flags & BW_METER_LEQ)
2175 		u->bu_flags |= BW_UPCALL_LEQ;
2176 
2177 	if (buf_ring_enqueue(V_bw_upcalls_ring, u))
2178 		log(LOG_WARNING, "bw_meter_prepare_upcall: cannot enqueue upcall\n");
2179 	if (buf_ring_count(V_bw_upcalls_ring) > (BW_UPCALLS_MAX / 2)) {
2180 		taskqueue_enqueue(V_task_queue, &V_task);
2181 	}
2182 }
2183 /*
2184  * Send the pending bandwidth-related upcalls
2185  */
2186 static void
2187 bw_upcalls_send(void)
2188 {
2189 	struct mbuf *m;
2190 	int len = 0;
2191 	struct bw_upcall *bu;
2192 	struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2193 	static struct igmpmsg igmpmsg = {
2194 		0,		/* unused1 */
2195 		0,		/* unused2 */
2196 		IGMPMSG_BW_UPCALL,/* im_msgtype */
2197 		0,		/* im_mbz  */
2198 		0,		/* im_vif  */
2199 		0,		/* unused3 */
2200 		{ 0 },		/* im_src  */
2201 		{ 0 }		/* im_dst  */
2202 	};
2203 
2204 	MRW_LOCK_ASSERT();
2205 
2206 	if (buf_ring_empty(V_bw_upcalls_ring))
2207 		return;
2208 
2209 	/*
2210 	 * Allocate a new mbuf, initialize it with the header and
2211 	 * the payload for the pending calls.
2212 	 */
2213 	m = m_gethdr(M_NOWAIT, MT_DATA);
2214 	if (m == NULL) {
2215 		log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2216 		return;
2217 	}
2218 
2219 	m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2220 	len += sizeof(struct igmpmsg);
2221 	while ((bu = buf_ring_dequeue_mc(V_bw_upcalls_ring)) != NULL) {
2222 		m_copyback(m, len, sizeof(struct bw_upcall), (caddr_t)bu);
2223 		len += sizeof(struct bw_upcall);
2224 		free(bu, M_MRTABLE);
2225 	}
2226 
2227 	/*
2228 	 * Send the upcalls
2229 	 * XXX do we need to set the address in k_igmpsrc ?
2230 	 */
2231 	MRTSTAT_INC(mrts_upcalls);
2232 	if (socket_send(V_ip_mrouter, m, &k_igmpsrc) < 0) {
2233 		log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2234 		MRTSTAT_INC(mrts_upq_sockfull);
2235 	}
2236 }
2237 
2238 /*
2239  * A periodic function for sending all upcalls that are pending delivery
2240  */
2241 static void
2242 expire_bw_upcalls_send(void *arg)
2243 {
2244 	CURVNET_SET((struct vnet *) arg);
2245 
2246 	/* This callout is run with MRW_RLOCK taken */
2247 
2248 	bw_upcalls_send();
2249 
2250 	callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
2251 	    curvnet);
2252 	CURVNET_RESTORE();
2253 }
2254 
2255 /*
2256  * End of bandwidth monitoring code
2257  */
2258 
2259 /*
2260  * Send the packet up to the user daemon, or eventually do kernel encapsulation
2261  *
2262  */
2263 static int
2264 pim_register_send(struct ip *ip, struct vif *vifp, struct mbuf *m,
2265     struct mfc *rt)
2266 {
2267 	struct mbuf *mb_copy, *mm;
2268 
2269 	/*
2270 	 * Do not send IGMP_WHOLEPKT notifications to userland, if the
2271 	 * rendezvous point was unspecified, and we were told not to.
2272 	 */
2273 	if (pim_squelch_wholepkt != 0 && (V_mrt_api_config & MRT_MFC_RP) &&
2274 	    in_nullhost(rt->mfc_rp))
2275 		return 0;
2276 
2277 	mb_copy = pim_register_prepare(ip, m);
2278 	if (mb_copy == NULL)
2279 		return ENOBUFS;
2280 
2281 	/*
2282 	 * Send all the fragments. Note that the mbuf for each fragment
2283 	 * is freed by the sending machinery.
2284 	 */
2285 	for (mm = mb_copy; mm; mm = mb_copy) {
2286 		mb_copy = mm->m_nextpkt;
2287 		mm->m_nextpkt = 0;
2288 		mm = m_pullup(mm, sizeof(struct ip));
2289 		if (mm != NULL) {
2290 			ip = mtod(mm, struct ip *);
2291 			if ((V_mrt_api_config & MRT_MFC_RP) && !in_nullhost(rt->mfc_rp)) {
2292 				pim_register_send_rp(ip, vifp, mm, rt);
2293 			} else {
2294 				pim_register_send_upcall(ip, vifp, mm, rt);
2295 			}
2296 		}
2297 	}
2298 
2299 	return 0;
2300 }
2301 
2302 /*
2303  * Return a copy of the data packet that is ready for PIM Register
2304  * encapsulation.
2305  * XXX: Note that in the returned copy the IP header is a valid one.
2306  */
2307 static struct mbuf *
2308 pim_register_prepare(struct ip *ip, struct mbuf *m)
2309 {
2310 	struct mbuf *mb_copy = NULL;
2311 	int mtu;
2312 
2313 	/* Take care of delayed checksums */
2314 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2315 		in_delayed_cksum(m);
2316 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2317 	}
2318 
2319 	/*
2320 	 * Copy the old packet & pullup its IP header into the
2321 	 * new mbuf so we can modify it.
2322 	 */
2323 	mb_copy = m_copypacket(m, M_NOWAIT);
2324 	if (mb_copy == NULL)
2325 		return NULL;
2326 	mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2327 	if (mb_copy == NULL)
2328 		return NULL;
2329 
2330 	/* take care of the TTL */
2331 	ip = mtod(mb_copy, struct ip *);
2332 	--ip->ip_ttl;
2333 
2334 	/* Compute the MTU after the PIM Register encapsulation */
2335 	mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2336 
2337 	if (ntohs(ip->ip_len) <= mtu) {
2338 		/* Turn the IP header into a valid one */
2339 		ip->ip_sum = 0;
2340 		ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2341 	} else {
2342 		/* Fragment the packet */
2343 		mb_copy->m_pkthdr.csum_flags |= CSUM_IP;
2344 		if (ip_fragment(ip, &mb_copy, mtu, 0) != 0) {
2345 			m_freem(mb_copy);
2346 			return NULL;
2347 		}
2348 	}
2349 	return mb_copy;
2350 }
2351 
2352 /*
2353  * Send an upcall with the data packet to the user-level process.
2354  */
2355 static int
2356 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2357     struct mbuf *mb_copy, struct mfc *rt)
2358 {
2359 	struct mbuf *mb_first;
2360 	int len = ntohs(ip->ip_len);
2361 	struct igmpmsg *im;
2362 	struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2363 
2364 	MRW_LOCK_ASSERT();
2365 
2366 	/*
2367 	 * Add a new mbuf with an upcall header
2368 	 */
2369 	mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2370 	if (mb_first == NULL) {
2371 		m_freem(mb_copy);
2372 		return ENOBUFS;
2373 	}
2374 	mb_first->m_data += max_linkhdr;
2375 	mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2376 	mb_first->m_len = sizeof(struct igmpmsg);
2377 	mb_first->m_next = mb_copy;
2378 
2379 	/* Send message to routing daemon */
2380 	im = mtod(mb_first, struct igmpmsg *);
2381 	im->im_msgtype	= IGMPMSG_WHOLEPKT;
2382 	im->im_mbz		= 0;
2383 	im->im_vif		= vifp - V_viftable;
2384 	im->im_src		= ip->ip_src;
2385 	im->im_dst		= ip->ip_dst;
2386 
2387 	k_igmpsrc.sin_addr	= ip->ip_src;
2388 
2389 	MRTSTAT_INC(mrts_upcalls);
2390 
2391 	if (socket_send(V_ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2392 		CTR1(KTR_IPMF, "%s: socket queue full", __func__);
2393 		MRTSTAT_INC(mrts_upq_sockfull);
2394 		return ENOBUFS;
2395 	}
2396 
2397 	/* Keep statistics */
2398 	PIMSTAT_INC(pims_snd_registers_msgs);
2399 	PIMSTAT_ADD(pims_snd_registers_bytes, len);
2400 
2401 	return 0;
2402 }
2403 
2404 /*
2405  * Encapsulate the data packet in PIM Register message and send it to the RP.
2406  */
2407 static int
2408 pim_register_send_rp(struct ip *ip, struct vif *vifp, struct mbuf *mb_copy,
2409     struct mfc *rt)
2410 {
2411 	struct mbuf *mb_first;
2412 	struct ip *ip_outer;
2413 	struct pim_encap_pimhdr *pimhdr;
2414 	int len = ntohs(ip->ip_len);
2415 	vifi_t vifi = rt->mfc_parent;
2416 
2417 	MRW_LOCK_ASSERT();
2418 
2419 	if ((vifi >= V_numvifs) || in_nullhost(V_viftable[vifi].v_lcl_addr)) {
2420 		m_freem(mb_copy);
2421 		return EADDRNOTAVAIL;		/* The iif vif is invalid */
2422 	}
2423 
2424 	/*
2425 	 * Add a new mbuf with the encapsulating header
2426 	 */
2427 	mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2428 	if (mb_first == NULL) {
2429 		m_freem(mb_copy);
2430 		return ENOBUFS;
2431 	}
2432 	mb_first->m_data += max_linkhdr;
2433 	mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2434 	mb_first->m_next = mb_copy;
2435 
2436 	mb_first->m_pkthdr.len = len + mb_first->m_len;
2437 
2438 	/*
2439 	 * Fill in the encapsulating IP and PIM header
2440 	 */
2441 	ip_outer = mtod(mb_first, struct ip *);
2442 	*ip_outer = pim_encap_iphdr;
2443 	ip_outer->ip_len = htons(len + sizeof(pim_encap_iphdr) +
2444 			sizeof(pim_encap_pimhdr));
2445 	ip_outer->ip_src = V_viftable[vifi].v_lcl_addr;
2446 	ip_outer->ip_dst = rt->mfc_rp;
2447 	/*
2448 	 * Copy the inner header TOS to the outer header, and take care of the
2449 	 * IP_DF bit.
2450 	 */
2451 	ip_outer->ip_tos = ip->ip_tos;
2452 	if (ip->ip_off & htons(IP_DF))
2453 		ip_outer->ip_off |= htons(IP_DF);
2454 	ip_fillid(ip_outer);
2455 	pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2456 			+ sizeof(pim_encap_iphdr));
2457 	*pimhdr = pim_encap_pimhdr;
2458 	/* If the iif crosses a border, set the Border-bit */
2459 	if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & V_mrt_api_config)
2460 		pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
2461 
2462 	mb_first->m_data += sizeof(pim_encap_iphdr);
2463 	pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
2464 	mb_first->m_data -= sizeof(pim_encap_iphdr);
2465 
2466 	send_packet(vifp, mb_first);
2467 
2468 	/* Keep statistics */
2469 	PIMSTAT_INC(pims_snd_registers_msgs);
2470 	PIMSTAT_ADD(pims_snd_registers_bytes, len);
2471 
2472 	return 0;
2473 }
2474 
2475 /*
2476  * pim_encapcheck() is called by the encap4_input() path at runtime to
2477  * determine if a packet is for PIM; allowing PIM to be dynamically loaded
2478  * into the kernel.
2479  */
2480 static int
2481 pim_encapcheck(const struct mbuf *m __unused, int off __unused,
2482     int proto __unused, void *arg __unused)
2483 {
2484 
2485 	KASSERT(proto == IPPROTO_PIM, ("not for IPPROTO_PIM"));
2486 	return (8);		/* claim the datagram. */
2487 }
2488 
2489 /*
2490  * PIM-SMv2 and PIM-DM messages processing.
2491  * Receives and verifies the PIM control messages, and passes them
2492  * up to the listening socket, using rip_input().
2493  * The only message with special processing is the PIM_REGISTER message
2494  * (used by PIM-SM): the PIM header is stripped off, and the inner packet
2495  * is passed to if_simloop().
2496  */
2497 static int
2498 pim_input(struct mbuf *m, int off, int proto, void *arg __unused)
2499 {
2500 	struct ip *ip = mtod(m, struct ip *);
2501 	struct pim *pim;
2502 	int iphlen = off;
2503 	int minlen;
2504 	int datalen = ntohs(ip->ip_len) - iphlen;
2505 	int ip_tos;
2506 
2507 	/* Keep statistics */
2508 	PIMSTAT_INC(pims_rcv_total_msgs);
2509 	PIMSTAT_ADD(pims_rcv_total_bytes, datalen);
2510 
2511 	/*
2512 	 * Validate lengths
2513 	 */
2514 	if (datalen < PIM_MINLEN) {
2515 		PIMSTAT_INC(pims_rcv_tooshort);
2516 		CTR3(KTR_IPMF, "%s: short packet (%d) from 0x%08x",
2517 		    __func__, datalen, ntohl(ip->ip_src.s_addr));
2518 		m_freem(m);
2519 		return (IPPROTO_DONE);
2520 	}
2521 
2522 	/*
2523 	 * If the packet is at least as big as a REGISTER, go agead
2524 	 * and grab the PIM REGISTER header size, to avoid another
2525 	 * possible m_pullup() later.
2526 	 *
2527 	 * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
2528 	 * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
2529 	 */
2530 	minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
2531 	/*
2532 	 * Get the IP and PIM headers in contiguous memory, and
2533 	 * possibly the PIM REGISTER header.
2534 	 */
2535 	if (m->m_len < minlen && (m = m_pullup(m, minlen)) == NULL) {
2536 		CTR1(KTR_IPMF, "%s: m_pullup() failed", __func__);
2537 		return (IPPROTO_DONE);
2538 	}
2539 
2540 	/* m_pullup() may have given us a new mbuf so reset ip. */
2541 	ip = mtod(m, struct ip *);
2542 	ip_tos = ip->ip_tos;
2543 
2544 	/* adjust mbuf to point to the PIM header */
2545 	m->m_data += iphlen;
2546 	m->m_len  -= iphlen;
2547 	pim = mtod(m, struct pim *);
2548 
2549 	/*
2550 	 * Validate checksum. If PIM REGISTER, exclude the data packet.
2551 	 *
2552 	 * XXX: some older PIMv2 implementations don't make this distinction,
2553 	 * so for compatibility reason perform the checksum over part of the
2554 	 * message, and if error, then over the whole message.
2555 	 */
2556 	if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
2557 		/* do nothing, checksum okay */
2558 	} else if (in_cksum(m, datalen)) {
2559 		PIMSTAT_INC(pims_rcv_badsum);
2560 		CTR1(KTR_IPMF, "%s: invalid checksum", __func__);
2561 		m_freem(m);
2562 		return (IPPROTO_DONE);
2563 	}
2564 
2565 	/* PIM version check */
2566 	if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
2567 		PIMSTAT_INC(pims_rcv_badversion);
2568 		CTR3(KTR_IPMF, "%s: bad version %d expect %d", __func__,
2569 		    (int)PIM_VT_V(pim->pim_vt), PIM_VERSION);
2570 		m_freem(m);
2571 		return (IPPROTO_DONE);
2572 	}
2573 
2574 	/* restore mbuf back to the outer IP */
2575 	m->m_data -= iphlen;
2576 	m->m_len  += iphlen;
2577 
2578 	if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
2579 		/*
2580 		 * Since this is a REGISTER, we'll make a copy of the register
2581 		 * headers ip + pim + u_int32 + encap_ip, to be passed up to the
2582 		 * routing daemon.
2583 		 */
2584 		struct sockaddr_in dst = { sizeof(dst), AF_INET };
2585 		struct mbuf *mcp;
2586 		struct ip *encap_ip;
2587 		u_int32_t *reghdr;
2588 		struct ifnet *vifp;
2589 
2590 		MRW_RLOCK();
2591 		if ((V_reg_vif_num >= V_numvifs) || (V_reg_vif_num == VIFI_INVALID)) {
2592 			MRW_RUNLOCK();
2593 			CTR2(KTR_IPMF, "%s: register vif not set: %d", __func__,
2594 			    (int)V_reg_vif_num);
2595 			m_freem(m);
2596 			return (IPPROTO_DONE);
2597 		}
2598 		/* XXX need refcnt? */
2599 		vifp = V_viftable[V_reg_vif_num].v_ifp;
2600 		MRW_RUNLOCK();
2601 
2602 		/*
2603 		 * Validate length
2604 		 */
2605 		if (datalen < PIM_REG_MINLEN) {
2606 			PIMSTAT_INC(pims_rcv_tooshort);
2607 			PIMSTAT_INC(pims_rcv_badregisters);
2608 			CTR1(KTR_IPMF, "%s: register packet size too small", __func__);
2609 			m_freem(m);
2610 			return (IPPROTO_DONE);
2611 		}
2612 
2613 		reghdr = (u_int32_t *)(pim + 1);
2614 		encap_ip = (struct ip *)(reghdr + 1);
2615 
2616 		CTR3(KTR_IPMF, "%s: register: encap ip src 0x%08x len %d",
2617 		    __func__, ntohl(encap_ip->ip_src.s_addr),
2618 		    ntohs(encap_ip->ip_len));
2619 
2620 		/* verify the version number of the inner packet */
2621 		if (encap_ip->ip_v != IPVERSION) {
2622 			PIMSTAT_INC(pims_rcv_badregisters);
2623 			CTR1(KTR_IPMF, "%s: bad encap ip version", __func__);
2624 			m_freem(m);
2625 			return (IPPROTO_DONE);
2626 		}
2627 
2628 		/* verify the inner packet is destined to a mcast group */
2629 		if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
2630 			PIMSTAT_INC(pims_rcv_badregisters);
2631 			CTR2(KTR_IPMF, "%s: bad encap ip dest 0x%08x", __func__,
2632 			    ntohl(encap_ip->ip_dst.s_addr));
2633 			m_freem(m);
2634 			return (IPPROTO_DONE);
2635 		}
2636 
2637 		/* If a NULL_REGISTER, pass it to the daemon */
2638 		if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
2639 			goto pim_input_to_daemon;
2640 
2641 		/*
2642 		 * Copy the TOS from the outer IP header to the inner IP header.
2643 		 */
2644 		if (encap_ip->ip_tos != ip_tos) {
2645 			/* Outer TOS -> inner TOS */
2646 			encap_ip->ip_tos = ip_tos;
2647 			/* Recompute the inner header checksum. Sigh... */
2648 
2649 			/* adjust mbuf to point to the inner IP header */
2650 			m->m_data += (iphlen + PIM_MINLEN);
2651 			m->m_len  -= (iphlen + PIM_MINLEN);
2652 
2653 			encap_ip->ip_sum = 0;
2654 			encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
2655 
2656 			/* restore mbuf to point back to the outer IP header */
2657 			m->m_data -= (iphlen + PIM_MINLEN);
2658 			m->m_len  += (iphlen + PIM_MINLEN);
2659 		}
2660 
2661 		/*
2662 		 * Decapsulate the inner IP packet and loopback to forward it
2663 		 * as a normal multicast packet. Also, make a copy of the
2664 		 *     outer_iphdr + pimhdr + reghdr + encap_iphdr
2665 		 * to pass to the daemon later, so it can take the appropriate
2666 		 * actions (e.g., send back PIM_REGISTER_STOP).
2667 		 * XXX: here m->m_data points to the outer IP header.
2668 		 */
2669 		mcp = m_copym(m, 0, iphlen + PIM_REG_MINLEN, M_NOWAIT);
2670 		if (mcp == NULL) {
2671 			CTR1(KTR_IPMF, "%s: m_copym() failed", __func__);
2672 			m_freem(m);
2673 			return (IPPROTO_DONE);
2674 		}
2675 
2676 		/* Keep statistics */
2677 		/* XXX: registers_bytes include only the encap. mcast pkt */
2678 		PIMSTAT_INC(pims_rcv_registers_msgs);
2679 		PIMSTAT_ADD(pims_rcv_registers_bytes, ntohs(encap_ip->ip_len));
2680 
2681 		/*
2682 		 * forward the inner ip packet; point m_data at the inner ip.
2683 		 */
2684 		m_adj(m, iphlen + PIM_MINLEN);
2685 
2686 		CTR4(KTR_IPMF,
2687 		    "%s: forward decap'd REGISTER: src %lx dst %lx vif %d",
2688 		    __func__,
2689 		    (u_long)ntohl(encap_ip->ip_src.s_addr),
2690 		    (u_long)ntohl(encap_ip->ip_dst.s_addr),
2691 		    (int)V_reg_vif_num);
2692 
2693 		/* NB: vifp was collected above; can it change on us? */
2694 		if_simloop(vifp, m, dst.sin_family, 0);
2695 
2696 		/* prepare the register head to send to the mrouting daemon */
2697 		m = mcp;
2698 	}
2699 
2700 pim_input_to_daemon:
2701 	/*
2702 	 * Pass the PIM message up to the daemon; if it is a Register message,
2703 	 * pass the 'head' only up to the daemon. This includes the
2704 	 * outer IP header, PIM header, PIM-Register header and the
2705 	 * inner IP header.
2706 	 * XXX: the outer IP header pkt size of a Register is not adjust to
2707 	 * reflect the fact that the inner multicast data is truncated.
2708 	 */
2709 	return (rip_input(&m, &off, proto));
2710 }
2711 
2712 static int
2713 sysctl_mfctable(SYSCTL_HANDLER_ARGS)
2714 {
2715 	struct mfc	*rt;
2716 	int		 error, i;
2717 
2718 	if (req->newptr)
2719 		return (EPERM);
2720 	if (V_mfchashtbl == NULL)	/* XXX unlocked */
2721 		return (0);
2722 	error = sysctl_wire_old_buffer(req, 0);
2723 	if (error)
2724 		return (error);
2725 
2726 	MRW_RLOCK();
2727 	for (i = 0; i < mfchashsize; i++) {
2728 		LIST_FOREACH(rt, &V_mfchashtbl[i], mfc_hash) {
2729 			error = SYSCTL_OUT(req, rt, sizeof(struct mfc));
2730 			if (error)
2731 				goto out_locked;
2732 		}
2733 	}
2734 out_locked:
2735 	MRW_RUNLOCK();
2736 	return (error);
2737 }
2738 
2739 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, mfctable,
2740     CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_mfctable,
2741     "IPv4 Multicast Forwarding Table "
2742     "(struct *mfc[mfchashsize], netinet/ip_mroute.h)");
2743 
2744 static int
2745 sysctl_viflist(SYSCTL_HANDLER_ARGS)
2746 {
2747 	int error, i;
2748 
2749 	if (req->newptr)
2750 		return (EPERM);
2751 	if (V_viftable == NULL)		/* XXX unlocked */
2752 		return (0);
2753 	error = sysctl_wire_old_buffer(req, MROUTE_VIF_SYSCTL_LEN * MAXVIFS);
2754 	if (error)
2755 		return (error);
2756 
2757 	MRW_RLOCK();
2758 	/* Copy out user-visible portion of vif entry. */
2759 	for (i = 0; i < MAXVIFS; i++) {
2760 		error = SYSCTL_OUT(req, &V_viftable[i], MROUTE_VIF_SYSCTL_LEN);
2761 		if (error)
2762 			break;
2763 	}
2764 	MRW_RUNLOCK();
2765 	return (error);
2766 }
2767 
2768 SYSCTL_PROC(_net_inet_ip, OID_AUTO, viftable,
2769     CTLTYPE_OPAQUE | CTLFLAG_VNET | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2770     sysctl_viflist, "S,vif[MAXVIFS]",
2771     "IPv4 Multicast Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
2772 
2773 static void
2774 vnet_mroute_init(const void *unused __unused)
2775 {
2776 
2777 	V_nexpire = malloc(mfchashsize, M_MRTABLE, M_WAITOK|M_ZERO);
2778 
2779 	V_viftable = mallocarray(MAXVIFS, sizeof(*V_viftable),
2780 	    M_MRTABLE, M_WAITOK|M_ZERO);
2781 
2782 	callout_init_rw(&V_expire_upcalls_ch, &mrouter_lock, 0);
2783 	callout_init_rw(&V_bw_upcalls_ch, &mrouter_lock, 0);
2784 
2785 	/* Prepare taskqueue */
2786 	V_task_queue = taskqueue_create_fast("ip_mroute_tskq", M_NOWAIT,
2787 		    taskqueue_thread_enqueue, &V_task_queue);
2788 	taskqueue_start_threads(&V_task_queue, 1, PI_NET, "ip_mroute_tskq task");
2789 }
2790 
2791 VNET_SYSINIT(vnet_mroute_init, SI_SUB_PROTO_MC, SI_ORDER_ANY, vnet_mroute_init,
2792 	NULL);
2793 
2794 static void
2795 vnet_mroute_uninit(const void *unused __unused)
2796 {
2797 
2798 	/* Taskqueue should be cancelled and drained before freeing */
2799 	taskqueue_free(V_task_queue);
2800 
2801 	free(V_viftable, M_MRTABLE);
2802 	free(V_nexpire, M_MRTABLE);
2803 	V_nexpire = NULL;
2804 }
2805 
2806 VNET_SYSUNINIT(vnet_mroute_uninit, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE,
2807     vnet_mroute_uninit, NULL);
2808 
2809 static int
2810 ip_mroute_modevent(module_t mod, int type, void *unused)
2811 {
2812 
2813 	switch (type) {
2814 	case MOD_LOAD:
2815 		MRW_LOCK_INIT();
2816 
2817 		if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
2818 		    if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
2819 		if (if_detach_event_tag == NULL) {
2820 			printf("ip_mroute: unable to register "
2821 					"ifnet_departure_event handler\n");
2822 			MRW_LOCK_DESTROY();
2823 			return (EINVAL);
2824 		}
2825 
2826 		if (!powerof2(mfchashsize)) {
2827 			printf("WARNING: %s not a power of 2; using default\n",
2828 					"net.inet.ip.mfchashsize");
2829 			mfchashsize = MFCHASHSIZE;
2830 		}
2831 
2832 		pim_encap_cookie = ip_encap_attach(&ipv4_encap_cfg, NULL, M_WAITOK);
2833 
2834 		ip_mcast_src = X_ip_mcast_src;
2835 		ip_mforward = X_ip_mforward;
2836 		ip_mrouter_done = X_ip_mrouter_done;
2837 		ip_mrouter_get = X_ip_mrouter_get;
2838 		ip_mrouter_set = X_ip_mrouter_set;
2839 
2840 		ip_rsvp_force_done = X_ip_rsvp_force_done;
2841 		ip_rsvp_vif = X_ip_rsvp_vif;
2842 
2843 		legal_vif_num = X_legal_vif_num;
2844 		mrt_ioctl = X_mrt_ioctl;
2845 		rsvp_input_p = X_rsvp_input;
2846 		break;
2847 
2848 	case MOD_UNLOAD:
2849 		/*
2850 		 * Typically module unload happens after the user-level
2851 		 * process has shutdown the kernel services (the check
2852 		 * below insures someone can't just yank the module out
2853 		 * from under a running process).  But if the module is
2854 		 * just loaded and then unloaded w/o starting up a user
2855 		 * process we still need to cleanup.
2856 		 */
2857 		MRW_WLOCK();
2858 		if (ip_mrouter_cnt != 0) {
2859 			MRW_WUNLOCK();
2860 			return (EINVAL);
2861 		}
2862 		ip_mrouter_unloading = 1;
2863 		MRW_WUNLOCK();
2864 
2865 		EVENTHANDLER_DEREGISTER(ifnet_departure_event, if_detach_event_tag);
2866 
2867 		if (pim_encap_cookie) {
2868 			ip_encap_detach(pim_encap_cookie);
2869 			pim_encap_cookie = NULL;
2870 		}
2871 
2872 		ip_mcast_src = NULL;
2873 		ip_mforward = NULL;
2874 		ip_mrouter_done = NULL;
2875 		ip_mrouter_get = NULL;
2876 		ip_mrouter_set = NULL;
2877 
2878 		ip_rsvp_force_done = NULL;
2879 		ip_rsvp_vif = NULL;
2880 
2881 		legal_vif_num = NULL;
2882 		mrt_ioctl = NULL;
2883 		rsvp_input_p = NULL;
2884 
2885 		MRW_LOCK_DESTROY();
2886 		break;
2887 
2888 	default:
2889 		return EOPNOTSUPP;
2890 	}
2891 	return 0;
2892 }
2893 
2894 static moduledata_t ip_mroutemod = {
2895 	"ip_mroute",
2896 	ip_mroute_modevent,
2897 	0
2898 };
2899 
2900 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);
2901