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