xref: /freebsd/sys/netinet/ip_mroute.c (revision 5e3190f700637fcfc1a52daeaa4a031fdd2557c7)
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 
712 	/* Create upcall ring */
713 	mtx_init(&V_bw_upcalls_ring_mtx, "mroute upcall buf_ring mtx", NULL, MTX_DEF);
714 	V_bw_upcalls_ring = buf_ring_alloc(BW_UPCALLS_MAX, M_MRTABLE,
715 	    M_NOWAIT, &V_bw_upcalls_ring_mtx);
716 	if (!V_bw_upcalls_ring) {
717 		MRW_WUNLOCK();
718 		return (ENOMEM);
719 	}
720 
721 	TASK_INIT(&V_task, 0, ip_mrouter_upcall_thread, curvnet);
722 	taskqueue_cancel(V_task_queue, &V_task, NULL);
723 	taskqueue_unblock(V_task_queue);
724 
725 	callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
726 	    curvnet);
727 	callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
728 	    curvnet);
729 
730 	V_ip_mrouter = so;
731 	atomic_add_int(&ip_mrouter_cnt, 1);
732 
733 	/* This is a mutex required by buf_ring init, but not used internally */
734 	mtx_init(&V_buf_ring_mtx, "mroute buf_ring mtx", NULL, MTX_DEF);
735 
736 	MRW_WUNLOCK();
737 
738 	CTR1(KTR_IPMF, "%s: done", __func__);
739 
740 	return 0;
741 }
742 
743 /*
744  * Disable multicast forwarding.
745  */
746 static int
747 X_ip_mrouter_done(void)
748 {
749 	struct ifnet **ifps;
750 	int nifp;
751 	u_long i;
752 	vifi_t vifi;
753 	struct bw_upcall *bu;
754 
755 	if (V_ip_mrouter == NULL)
756 		return (EINVAL);
757 
758 	/*
759 	 * Detach/disable hooks to the reset of the system.
760 	 */
761 	V_ip_mrouter = NULL;
762 	atomic_subtract_int(&ip_mrouter_cnt, 1);
763 	V_mrt_api_config = 0;
764 
765 	/*
766 	 * Wait for all epoch sections to complete to ensure
767 	 * V_ip_mrouter = NULL is visible to others.
768 	 */
769 	epoch_wait_preempt(net_epoch_preempt);
770 
771 	/* Stop and drain task queue */
772 	taskqueue_block(V_task_queue);
773 	while (taskqueue_cancel(V_task_queue, &V_task, NULL)) {
774 		taskqueue_drain(V_task_queue, &V_task);
775 	}
776 
777 	ifps = malloc(MAXVIFS * sizeof(*ifps), M_TEMP, M_WAITOK);
778 
779 	MRW_WLOCK();
780 	taskqueue_cancel(V_task_queue, &V_task, NULL);
781 
782 	/* Destroy upcall ring */
783 	while ((bu = buf_ring_dequeue_mc(V_bw_upcalls_ring)) != NULL) {
784 		free(bu, M_MRTABLE);
785 	}
786 	buf_ring_free(V_bw_upcalls_ring, M_MRTABLE);
787 	mtx_destroy(&V_bw_upcalls_ring_mtx);
788 
789 	/*
790 	 * For each phyint in use, prepare to disable promiscuous reception
791 	 * of all IP multicasts.  Defer the actual call until the lock is released;
792 	 * just record the list of interfaces while locked.  Some interfaces use
793 	 * sx locks in their ioctl routines, which is not allowed while holding
794 	 * a non-sleepable lock.
795 	 */
796 	KASSERT(V_numvifs <= MAXVIFS, ("More vifs than possible"));
797 	for (vifi = 0, nifp = 0; vifi < V_numvifs; vifi++) {
798 		if (!in_nullhost(V_viftable[vifi].v_lcl_addr) &&
799 		    !(V_viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
800 			ifps[nifp++] = V_viftable[vifi].v_ifp;
801 		}
802 	}
803 	bzero((caddr_t)V_viftable, sizeof(*V_viftable) * MAXVIFS);
804 	V_numvifs = 0;
805 	V_pim_assert_enabled = 0;
806 
807 	callout_stop(&V_expire_upcalls_ch);
808 	callout_stop(&V_bw_upcalls_ch);
809 
810 	/*
811 	 * Free all multicast forwarding cache entries.
812 	 * Do not use hashdestroy(), as we must perform other cleanup.
813 	 */
814 	for (i = 0; i < mfchashsize; i++) {
815 		struct mfc *rt, *nrt;
816 
817 		LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
818 			expire_mfc(rt);
819 		}
820 	}
821 	free(V_mfchashtbl, M_MRTABLE);
822 	V_mfchashtbl = NULL;
823 
824 	bzero(V_nexpire, sizeof(V_nexpire[0]) * mfchashsize);
825 
826 	V_reg_vif_num = VIFI_INVALID;
827 
828 	mtx_destroy(&V_buf_ring_mtx);
829 
830 	MRW_WUNLOCK();
831 
832 	/*
833 	 * Now drop our claim on promiscuous multicast on the interfaces recorded
834 	 * above.  This is safe to do now because ALLMULTI is reference counted.
835 	 */
836 	for (vifi = 0; vifi < nifp; vifi++)
837 		if_allmulti(ifps[vifi], 0);
838 	free(ifps, M_TEMP);
839 
840 	CTR1(KTR_IPMF, "%s: done", __func__);
841 
842 	return 0;
843 }
844 
845 /*
846  * Set PIM assert processing global
847  */
848 static int
849 set_assert(int i)
850 {
851 	if ((i != 1) && (i != 0))
852 		return EINVAL;
853 
854 	V_pim_assert_enabled = i;
855 
856 	return 0;
857 }
858 
859 /*
860  * Configure API capabilities
861  */
862 int
863 set_api_config(uint32_t *apival)
864 {
865 	u_long i;
866 
867 	/*
868 	 * We can set the API capabilities only if it is the first operation
869 	 * after MRT_INIT. I.e.:
870 	 *  - there are no vifs installed
871 	 *  - pim_assert is not enabled
872 	 *  - the MFC table is empty
873 	 */
874 	if (V_numvifs > 0) {
875 		*apival = 0;
876 		return EPERM;
877 	}
878 	if (V_pim_assert_enabled) {
879 		*apival = 0;
880 		return EPERM;
881 	}
882 
883 	MRW_RLOCK();
884 
885 	for (i = 0; i < mfchashsize; i++) {
886 		if (LIST_FIRST(&V_mfchashtbl[i]) != NULL) {
887 			MRW_RUNLOCK();
888 			*apival = 0;
889 			return EPERM;
890 		}
891 	}
892 
893 	MRW_RUNLOCK();
894 
895 	V_mrt_api_config = *apival & mrt_api_support;
896 	*apival = V_mrt_api_config;
897 
898 	return 0;
899 }
900 
901 /*
902  * Add a vif to the vif table
903  */
904 static int
905 add_vif(struct vifctl *vifcp)
906 {
907 	struct vif *vifp = V_viftable + vifcp->vifc_vifi;
908 	struct sockaddr_in sin = {sizeof sin, AF_INET};
909 	struct ifaddr *ifa;
910 	struct ifnet *ifp;
911 	int error;
912 
913 	if (vifcp->vifc_vifi >= MAXVIFS)
914 		return EINVAL;
915 	/* rate limiting is no longer supported by this code */
916 	if (vifcp->vifc_rate_limit != 0) {
917 		log(LOG_ERR, "rate limiting is no longer supported\n");
918 		return EINVAL;
919 	}
920 
921 	if (in_nullhost(vifcp->vifc_lcl_addr))
922 		return EADDRNOTAVAIL;
923 
924 	/* Find the interface with an address in AF_INET family */
925 	if (vifcp->vifc_flags & VIFF_REGISTER) {
926 		/*
927 		 * XXX: Because VIFF_REGISTER does not really need a valid
928 		 * local interface (e.g. it could be 127.0.0.2), we don't
929 		 * check its address.
930 		 */
931 		ifp = NULL;
932 	} else {
933 		struct epoch_tracker et;
934 
935 		sin.sin_addr = vifcp->vifc_lcl_addr;
936 		NET_EPOCH_ENTER(et);
937 		ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
938 		if (ifa == NULL) {
939 			NET_EPOCH_EXIT(et);
940 			return EADDRNOTAVAIL;
941 		}
942 		ifp = ifa->ifa_ifp;
943 		/* XXX FIXME we need to take a ref on ifp and cleanup properly! */
944 		NET_EPOCH_EXIT(et);
945 	}
946 
947 	if ((vifcp->vifc_flags & VIFF_TUNNEL) != 0) {
948 		CTR1(KTR_IPMF, "%s: tunnels are no longer supported", __func__);
949 		return EOPNOTSUPP;
950 	} else if (vifcp->vifc_flags & VIFF_REGISTER) {
951 		ifp = V_multicast_register_if = if_alloc(IFT_LOOP);
952 		CTR2(KTR_IPMF, "%s: add register vif for ifp %p", __func__, ifp);
953 		if (V_reg_vif_num == VIFI_INVALID) {
954 			if_initname(V_multicast_register_if, "register_vif", 0);
955 			V_reg_vif_num = vifcp->vifc_vifi;
956 		}
957 	} else {		/* Make sure the interface supports multicast */
958 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
959 			return EOPNOTSUPP;
960 
961 		/* Enable promiscuous reception of all IP multicasts from the if */
962 		error = if_allmulti(ifp, 1);
963 		if (error)
964 			return error;
965 	}
966 
967 	MRW_WLOCK();
968 
969 	if (!in_nullhost(vifp->v_lcl_addr)) {
970 		if (ifp)
971 			V_multicast_register_if = NULL;
972 		MRW_WUNLOCK();
973 		if (ifp)
974 			if_free(ifp);
975 		return EADDRINUSE;
976 	}
977 
978 	vifp->v_flags     = vifcp->vifc_flags;
979 	vifp->v_threshold = vifcp->vifc_threshold;
980 	vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
981 	vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
982 	vifp->v_ifp       = ifp;
983 	/* initialize per vif pkt counters */
984 	vifp->v_pkt_in    = 0;
985 	vifp->v_pkt_out   = 0;
986 	vifp->v_bytes_in  = 0;
987 	vifp->v_bytes_out = 0;
988 	sprintf(vifp->v_spin_name, "BM[%d] spin", vifcp->vifc_vifi);
989 	mtx_init(&vifp->v_spin, vifp->v_spin_name, NULL, MTX_SPIN);
990 
991 	/* Adjust numvifs up if the vifi is higher than numvifs */
992 	if (V_numvifs <= vifcp->vifc_vifi)
993 		V_numvifs = vifcp->vifc_vifi + 1;
994 
995 	MRW_WUNLOCK();
996 
997 	CTR4(KTR_IPMF, "%s: add vif %d laddr 0x%08x thresh %x", __func__,
998 	    (int)vifcp->vifc_vifi, ntohl(vifcp->vifc_lcl_addr.s_addr),
999 	    (int)vifcp->vifc_threshold);
1000 
1001 	return 0;
1002 }
1003 
1004 /*
1005  * Delete a vif from the vif table
1006  */
1007 static int
1008 del_vif_locked(vifi_t vifi, struct ifnet **ifp_multi_leave, struct ifnet **ifp_free)
1009 {
1010 	struct vif *vifp;
1011 
1012 	*ifp_free = NULL;
1013 	*ifp_multi_leave = NULL;
1014 
1015 	MRW_WLOCK_ASSERT();
1016 
1017 	if (vifi >= V_numvifs) {
1018 		return EINVAL;
1019 	}
1020 	vifp = &V_viftable[vifi];
1021 	if (in_nullhost(vifp->v_lcl_addr)) {
1022 		return EADDRNOTAVAIL;
1023 	}
1024 
1025 	if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
1026 		*ifp_multi_leave = vifp->v_ifp;
1027 
1028 	if (vifp->v_flags & VIFF_REGISTER) {
1029 		V_reg_vif_num = VIFI_INVALID;
1030 		if (vifp->v_ifp) {
1031 			if (vifp->v_ifp == V_multicast_register_if)
1032 				V_multicast_register_if = NULL;
1033 			*ifp_free = vifp->v_ifp;
1034 		}
1035 	}
1036 
1037 	mtx_destroy(&vifp->v_spin);
1038 
1039 	bzero((caddr_t)vifp, sizeof (*vifp));
1040 
1041 	CTR2(KTR_IPMF, "%s: delete vif %d", __func__, (int)vifi);
1042 
1043 	/* Adjust numvifs down */
1044 	for (vifi = V_numvifs; vifi > 0; vifi--)
1045 		if (!in_nullhost(V_viftable[vifi-1].v_lcl_addr))
1046 			break;
1047 	V_numvifs = vifi;
1048 
1049 	return 0;
1050 }
1051 
1052 static int
1053 del_vif(vifi_t vifi)
1054 {
1055 	int cc;
1056 	struct ifnet *free_ptr, *multi_leave;
1057 
1058 	MRW_WLOCK();
1059 	cc = del_vif_locked(vifi, &multi_leave, &free_ptr);
1060 	MRW_WUNLOCK();
1061 
1062 	if (multi_leave)
1063 		if_allmulti(multi_leave, 0);
1064 	if (free_ptr) {
1065 		if_free(free_ptr);
1066 	}
1067 
1068 	return cc;
1069 }
1070 
1071 /*
1072  * update an mfc entry without resetting counters and S,G addresses.
1073  */
1074 static void
1075 update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1076 {
1077 	int i;
1078 
1079 	rt->mfc_parent = mfccp->mfcc_parent;
1080 	for (i = 0; i < V_numvifs; i++) {
1081 		rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1082 		rt->mfc_flags[i] = mfccp->mfcc_flags[i] & V_mrt_api_config &
1083 			MRT_MFC_FLAGS_ALL;
1084 	}
1085 	/* set the RP address */
1086 	if (V_mrt_api_config & MRT_MFC_RP)
1087 		rt->mfc_rp = mfccp->mfcc_rp;
1088 	else
1089 		rt->mfc_rp.s_addr = INADDR_ANY;
1090 }
1091 
1092 /*
1093  * fully initialize an mfc entry from the parameter.
1094  */
1095 static void
1096 init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1097 {
1098 	rt->mfc_origin     = mfccp->mfcc_origin;
1099 	rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
1100 
1101 	update_mfc_params(rt, mfccp);
1102 
1103 	/* initialize pkt counters per src-grp */
1104 	rt->mfc_pkt_cnt    = 0;
1105 	rt->mfc_byte_cnt   = 0;
1106 	rt->mfc_wrong_if   = 0;
1107 	timevalclear(&rt->mfc_last_assert);
1108 }
1109 
1110 static void
1111 expire_mfc(struct mfc *rt)
1112 {
1113 	struct rtdetq *rte;
1114 
1115 	MRW_WLOCK_ASSERT();
1116 
1117 	free_bw_list(rt->mfc_bw_meter_leq);
1118 	free_bw_list(rt->mfc_bw_meter_geq);
1119 
1120 	while (!buf_ring_empty(rt->mfc_stall_ring)) {
1121 		rte = buf_ring_dequeue_mc(rt->mfc_stall_ring);
1122 		if (rte) {
1123 			m_freem(rte->m);
1124 			free(rte, M_MRTABLE);
1125 		}
1126 	}
1127 	buf_ring_free(rt->mfc_stall_ring, M_MRTABLE);
1128 
1129 	LIST_REMOVE(rt, mfc_hash);
1130 	free(rt, M_MRTABLE);
1131 }
1132 
1133 /*
1134  * Add an mfc entry
1135  */
1136 static int
1137 add_mfc(struct mfcctl2 *mfccp)
1138 {
1139 	struct mfc *rt;
1140 	struct rtdetq *rte;
1141 	u_long hash = 0;
1142 	u_short nstl;
1143 	struct epoch_tracker et;
1144 
1145 	MRW_WLOCK();
1146 	rt = mfc_find(&mfccp->mfcc_origin, &mfccp->mfcc_mcastgrp);
1147 
1148 	/* If an entry already exists, just update the fields */
1149 	if (rt) {
1150 		CTR4(KTR_IPMF, "%s: update mfc orig 0x%08x group %lx parent %x",
1151 		    __func__, ntohl(mfccp->mfcc_origin.s_addr),
1152 		    (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1153 		    mfccp->mfcc_parent);
1154 		update_mfc_params(rt, mfccp);
1155 		MRW_WUNLOCK();
1156 		return (0);
1157 	}
1158 
1159 	/*
1160 	 * Find the entry for which the upcall was made and update
1161 	 */
1162 	nstl = 0;
1163 	hash = MFCHASH(mfccp->mfcc_origin, mfccp->mfcc_mcastgrp);
1164 	NET_EPOCH_ENTER(et);
1165 	LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1166 		if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1167 		    in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp) &&
1168 		    !buf_ring_empty(rt->mfc_stall_ring)) {
1169 			CTR5(KTR_IPMF,
1170 			   "%s: add mfc orig 0x%08x group %lx parent %x qh %p",
1171 			    __func__, ntohl(mfccp->mfcc_origin.s_addr),
1172 			    (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1173 			    mfccp->mfcc_parent,
1174 			    rt->mfc_stall_ring);
1175 			if (nstl++)
1176 				CTR1(KTR_IPMF, "%s: multiple matches", __func__);
1177 
1178 			init_mfc_params(rt, mfccp);
1179 			rt->mfc_expire = 0;	/* Don't clean this guy up */
1180 			V_nexpire[hash]--;
1181 
1182 			/* Free queued packets, but attempt to forward them first. */
1183 			while (!buf_ring_empty(rt->mfc_stall_ring)) {
1184 				rte = buf_ring_dequeue_mc(rt->mfc_stall_ring);
1185 				if (rte->ifp != NULL)
1186 					ip_mdq(rte->m, rte->ifp, rt, -1);
1187 				m_freem(rte->m);
1188 				free(rte, M_MRTABLE);
1189 			}
1190 		}
1191 	}
1192 	NET_EPOCH_EXIT(et);
1193 
1194 	/*
1195 	 * It is possible that an entry is being inserted without an upcall
1196 	 */
1197 	if (nstl == 0) {
1198 		CTR1(KTR_IPMF, "%s: adding mfc w/o upcall", __func__);
1199 		LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1200 			if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1201 			    in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp)) {
1202 				init_mfc_params(rt, mfccp);
1203 				if (rt->mfc_expire)
1204 					V_nexpire[hash]--;
1205 				rt->mfc_expire = 0;
1206 				break; /* XXX */
1207 			}
1208 		}
1209 
1210 		if (rt == NULL) {		/* no upcall, so make a new entry */
1211 			rt = mfc_alloc();
1212 			if (rt == NULL) {
1213 				MRW_WUNLOCK();
1214 				return (ENOBUFS);
1215 			}
1216 
1217 			init_mfc_params(rt, mfccp);
1218 
1219 			rt->mfc_expire     = 0;
1220 			rt->mfc_bw_meter_leq = NULL;
1221 			rt->mfc_bw_meter_geq = NULL;
1222 
1223 			/* insert new entry at head of hash chain */
1224 			LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1225 		}
1226 	}
1227 
1228 	MRW_WUNLOCK();
1229 
1230 	return (0);
1231 }
1232 
1233 /*
1234  * Delete an mfc entry
1235  */
1236 static int
1237 del_mfc(struct mfcctl2 *mfccp)
1238 {
1239 	struct in_addr origin;
1240 	struct in_addr mcastgrp;
1241 	struct mfc *rt;
1242 
1243 	origin = mfccp->mfcc_origin;
1244 	mcastgrp = mfccp->mfcc_mcastgrp;
1245 
1246 	CTR3(KTR_IPMF, "%s: delete mfc orig 0x%08x group %lx", __func__,
1247 			ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
1248 
1249 	MRW_WLOCK();
1250 
1251 	rt = mfc_find(&origin, &mcastgrp);
1252 	if (rt == NULL) {
1253 		MRW_WUNLOCK();
1254 		return EADDRNOTAVAIL;
1255 	}
1256 
1257 	/*
1258 	 * free the bw_meter entries
1259 	 */
1260 	free_bw_list(rt->mfc_bw_meter_leq);
1261 	rt->mfc_bw_meter_leq = NULL;
1262 	free_bw_list(rt->mfc_bw_meter_geq);
1263 	rt->mfc_bw_meter_geq = NULL;
1264 
1265 	LIST_REMOVE(rt, mfc_hash);
1266 	free(rt, M_MRTABLE);
1267 
1268 	MRW_WUNLOCK();
1269 
1270 	return (0);
1271 }
1272 
1273 /*
1274  * Send a message to the routing daemon on the multicast routing socket.
1275  */
1276 static int
1277 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1278 {
1279 	if (s) {
1280 		SOCKBUF_LOCK(&s->so_rcv);
1281 		if (sbappendaddr_locked(&s->so_rcv, (struct sockaddr *)src, mm,
1282 		    NULL) != 0) {
1283 			sorwakeup_locked(s);
1284 			return 0;
1285 		}
1286 		soroverflow_locked(s);
1287 	}
1288 	m_freem(mm);
1289 	return -1;
1290 }
1291 
1292 /*
1293  * IP multicast forwarding function. This function assumes that the packet
1294  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1295  * pointed to by "ifp", and the packet is to be relayed to other networks
1296  * that have members of the packet's destination IP multicast group.
1297  *
1298  * The packet is returned unscathed to the caller, unless it is
1299  * erroneous, in which case a non-zero return value tells the caller to
1300  * discard it.
1301  */
1302 
1303 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1304 
1305 static int
1306 X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1307     struct ip_moptions *imo)
1308 {
1309 	struct mfc *rt;
1310 	int error;
1311 	vifi_t vifi;
1312 	struct mbuf *mb0;
1313 	struct rtdetq *rte;
1314 	u_long hash;
1315 	int hlen;
1316 
1317 	CTR3(KTR_IPMF, "ip_mforward: delete mfc orig 0x%08x group %lx ifp %p",
1318 	    ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr), ifp);
1319 
1320 	if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1321 	    ((u_char *)(ip + 1))[1] != IPOPT_LSRR) {
1322 		/*
1323 		 * Packet arrived via a physical interface or
1324 		 * an encapsulated tunnel or a register_vif.
1325 		 */
1326 	} else {
1327 		/*
1328 		 * Packet arrived through a source-route tunnel.
1329 		 * Source-route tunnels are no longer supported.
1330 		 */
1331 		return (1);
1332 	}
1333 
1334 	/*
1335 	 * BEGIN: MCAST ROUTING HOT PATH
1336 	 */
1337 	MRW_RLOCK();
1338 	if (imo && ((vifi = imo->imo_multicast_vif) < V_numvifs)) {
1339 		if (ip->ip_ttl < MAXTTL)
1340 			ip->ip_ttl++; /* compensate for -1 in *_send routines */
1341 		error = ip_mdq(m, ifp, NULL, vifi);
1342 		MRW_RUNLOCK();
1343 		return error;
1344 	}
1345 
1346 	/*
1347 	 * Don't forward a packet with time-to-live of zero or one,
1348 	 * or a packet destined to a local-only group.
1349 	 */
1350 	if (ip->ip_ttl <= 1 || IN_LOCAL_GROUP(ntohl(ip->ip_dst.s_addr))) {
1351 		MRW_RUNLOCK();
1352 		return 0;
1353 	}
1354 
1355 mfc_find_retry:
1356 	/*
1357 	 * Determine forwarding vifs from the forwarding cache table
1358 	 */
1359 	MRTSTAT_INC(mrts_mfc_lookups);
1360 	rt = mfc_find(&ip->ip_src, &ip->ip_dst);
1361 
1362 	/* Entry exists, so forward if necessary */
1363 	if (rt != NULL) {
1364 		error = ip_mdq(m, ifp, rt, -1);
1365 		/* Generic unlock here as we might release R or W lock */
1366 		MRW_UNLOCK();
1367 		return error;
1368 	}
1369 
1370 	/*
1371 	 * END: MCAST ROUTING HOT PATH
1372 	 */
1373 
1374 	/* Further processing must be done with WLOCK taken */
1375 	if ((MRW_WOWNED() == 0) && (MRW_LOCK_TRY_UPGRADE() == 0)) {
1376 		MRW_RUNLOCK();
1377 		MRW_WLOCK();
1378 		goto mfc_find_retry;
1379 	}
1380 
1381 	/*
1382 	 * If we don't have a route for packet's origin,
1383 	 * Make a copy of the packet & send message to routing daemon
1384 	 */
1385 	hlen = ip->ip_hl << 2;
1386 
1387 	MRTSTAT_INC(mrts_mfc_misses);
1388 	MRTSTAT_INC(mrts_no_route);
1389 	CTR2(KTR_IPMF, "ip_mforward: no mfc for (0x%08x,%lx)",
1390 	    ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr));
1391 
1392 	/*
1393 	 * Allocate mbufs early so that we don't do extra work if we are
1394 	 * just going to fail anyway.  Make sure to pullup the header so
1395 	 * that other people can't step on it.
1396 	 */
1397 	rte = malloc((sizeof *rte), M_MRTABLE, M_NOWAIT|M_ZERO);
1398 	if (rte == NULL) {
1399 		MRW_WUNLOCK();
1400 		return ENOBUFS;
1401 	}
1402 
1403 	mb0 = m_copypacket(m, M_NOWAIT);
1404 	if (mb0 && (!M_WRITABLE(mb0) || mb0->m_len < hlen))
1405 		mb0 = m_pullup(mb0, hlen);
1406 	if (mb0 == NULL) {
1407 		free(rte, M_MRTABLE);
1408 		MRW_WUNLOCK();
1409 		return ENOBUFS;
1410 	}
1411 
1412 	/* is there an upcall waiting for this flow ? */
1413 	hash = MFCHASH(ip->ip_src, ip->ip_dst);
1414 	LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash)
1415 	{
1416 		if (in_hosteq(ip->ip_src, rt->mfc_origin) &&
1417 		    in_hosteq(ip->ip_dst, rt->mfc_mcastgrp) &&
1418 		    !buf_ring_empty(rt->mfc_stall_ring))
1419 			break;
1420 	}
1421 
1422 	if (rt == NULL) {
1423 		int i;
1424 		struct igmpmsg *im;
1425 		struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1426 		struct mbuf *mm;
1427 
1428 		/*
1429 		 * Locate the vifi for the incoming interface for this packet.
1430 		 * If none found, drop packet.
1431 		 */
1432 		for (vifi = 0; vifi < V_numvifs &&
1433 		    V_viftable[vifi].v_ifp != ifp; vifi++)
1434 			;
1435 		if (vifi >= V_numvifs) /* vif not found, drop packet */
1436 			goto non_fatal;
1437 
1438 		/* no upcall, so make a new entry */
1439 		rt = mfc_alloc();
1440 		if (rt == NULL)
1441 			goto fail;
1442 
1443 		/* Make a copy of the header to send to the user level process */
1444 		mm = m_copym(mb0, 0, hlen, M_NOWAIT);
1445 		if (mm == NULL)
1446 			goto fail1;
1447 
1448 		/*
1449 		 * Send message to routing daemon to install
1450 		 * a route into the kernel table
1451 		 */
1452 
1453 		im = mtod(mm, struct igmpmsg*);
1454 		im->im_msgtype = IGMPMSG_NOCACHE;
1455 		im->im_mbz = 0;
1456 		im->im_vif = vifi;
1457 
1458 		MRTSTAT_INC(mrts_upcalls);
1459 
1460 		k_igmpsrc.sin_addr = ip->ip_src;
1461 		if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1462 			CTR0(KTR_IPMF, "ip_mforward: socket queue full");
1463 			MRTSTAT_INC(mrts_upq_sockfull);
1464 			fail1: free(rt, M_MRTABLE);
1465 			fail: free(rte, M_MRTABLE);
1466 			m_freem(mb0);
1467 			MRW_WUNLOCK();
1468 			return ENOBUFS;
1469 		}
1470 
1471 		/* insert new entry at head of hash chain */
1472 		rt->mfc_origin.s_addr = ip->ip_src.s_addr;
1473 		rt->mfc_mcastgrp.s_addr = ip->ip_dst.s_addr;
1474 		rt->mfc_expire = UPCALL_EXPIRE;
1475 		V_nexpire[hash]++;
1476 		for (i = 0; i < V_numvifs; i++) {
1477 			rt->mfc_ttls[i] = 0;
1478 			rt->mfc_flags[i] = 0;
1479 		}
1480 		rt->mfc_parent = -1;
1481 
1482 		/* clear the RP address */
1483 		rt->mfc_rp.s_addr = INADDR_ANY;
1484 		rt->mfc_bw_meter_leq = NULL;
1485 		rt->mfc_bw_meter_geq = NULL;
1486 
1487 		/* initialize pkt counters per src-grp */
1488 		rt->mfc_pkt_cnt = 0;
1489 		rt->mfc_byte_cnt = 0;
1490 		rt->mfc_wrong_if = 0;
1491 		timevalclear(&rt->mfc_last_assert);
1492 
1493 		buf_ring_enqueue(rt->mfc_stall_ring, rte);
1494 
1495 		/* Add RT to hashtable as it didn't exist before */
1496 		LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1497 	} else {
1498 		/* determine if queue has overflowed */
1499 		if (buf_ring_full(rt->mfc_stall_ring)) {
1500 			MRTSTAT_INC(mrts_upq_ovflw);
1501 			non_fatal: free(rte, M_MRTABLE);
1502 			m_freem(mb0);
1503 			MRW_WUNLOCK();
1504 			return (0);
1505 		}
1506 
1507 		buf_ring_enqueue(rt->mfc_stall_ring, rte);
1508 	}
1509 
1510 	rte->m = mb0;
1511 	rte->ifp = ifp;
1512 
1513 	MRW_WUNLOCK();
1514 
1515 	return 0;
1516 }
1517 
1518 /*
1519  * Clean up the cache entry if upcall is not serviced
1520  */
1521 static void
1522 expire_upcalls(void *arg)
1523 {
1524 	u_long i;
1525 
1526 	CURVNET_SET((struct vnet *) arg);
1527 
1528 	/*This callout is always run with MRW_WLOCK taken. */
1529 
1530 	for (i = 0; i < mfchashsize; i++) {
1531 		struct mfc *rt, *nrt;
1532 
1533 		if (V_nexpire[i] == 0)
1534 			continue;
1535 
1536 		LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
1537 			if (buf_ring_empty(rt->mfc_stall_ring))
1538 				continue;
1539 
1540 			if (rt->mfc_expire == 0 || --rt->mfc_expire > 0)
1541 				continue;
1542 
1543 			MRTSTAT_INC(mrts_cache_cleanups);
1544 			CTR3(KTR_IPMF, "%s: expire (%lx, %lx)", __func__,
1545 			    (u_long)ntohl(rt->mfc_origin.s_addr),
1546 			    (u_long)ntohl(rt->mfc_mcastgrp.s_addr));
1547 
1548 			expire_mfc(rt);
1549 		}
1550 	}
1551 
1552 	callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
1553 	    curvnet);
1554 
1555 	CURVNET_RESTORE();
1556 }
1557 
1558 /*
1559  * Packet forwarding routine once entry in the cache is made
1560  */
1561 static int
1562 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1563 {
1564 	struct ip *ip = mtod(m, struct ip *);
1565 	vifi_t vifi;
1566 	int plen = ntohs(ip->ip_len);
1567 
1568 	MRW_LOCK_ASSERT();
1569 	NET_EPOCH_ASSERT();
1570 
1571 	/*
1572 	 * If xmt_vif is not -1, send on only the requested vif.
1573 	 *
1574 	 * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1575 	 */
1576 	if (xmt_vif < V_numvifs) {
1577 		if (V_viftable[xmt_vif].v_flags & VIFF_REGISTER)
1578 			pim_register_send(ip, V_viftable + xmt_vif, m, rt);
1579 		else
1580 			phyint_send(ip, V_viftable + xmt_vif, m);
1581 		return 1;
1582 	}
1583 
1584 	/*
1585 	 * Don't forward if it didn't arrive from the parent vif for its origin.
1586 	 */
1587 	vifi = rt->mfc_parent;
1588 	if ((vifi >= V_numvifs) || (V_viftable[vifi].v_ifp != ifp)) {
1589 		CTR4(KTR_IPMF, "%s: rx on wrong ifp %p (vifi %d, v_ifp %p)",
1590 				__func__, ifp, (int)vifi, V_viftable[vifi].v_ifp);
1591 		MRTSTAT_INC(mrts_wrong_if);
1592 		++rt->mfc_wrong_if;
1593 		/*
1594 		 * If we are doing PIM assert processing, send a message
1595 		 * to the routing daemon.
1596 		 *
1597 		 * XXX: A PIM-SM router needs the WRONGVIF detection so it
1598 		 * can complete the SPT switch, regardless of the type
1599 		 * of the iif (broadcast media, GRE tunnel, etc).
1600 		 */
1601 		if (V_pim_assert_enabled && (vifi < V_numvifs) &&
1602 		    V_viftable[vifi].v_ifp) {
1603 			if (ifp == V_multicast_register_if)
1604 				PIMSTAT_INC(pims_rcv_registers_wrongiif);
1605 
1606 			/* Get vifi for the incoming packet */
1607 			for (vifi = 0; vifi < V_numvifs && V_viftable[vifi].v_ifp != ifp; vifi++)
1608 				;
1609 			if (vifi >= V_numvifs)
1610 				return 0;	/* The iif is not found: ignore the packet. */
1611 
1612 			if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1613 				return 0;	/* WRONGVIF disabled: ignore the packet */
1614 
1615 			if (ratecheck(&rt->mfc_last_assert, &pim_assert_interval)) {
1616 				struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1617 				struct igmpmsg *im;
1618 				int hlen = ip->ip_hl << 2;
1619 				struct mbuf *mm = m_copym(m, 0, hlen, M_NOWAIT);
1620 
1621 				if (mm && (!M_WRITABLE(mm) || mm->m_len < hlen))
1622 					mm = m_pullup(mm, hlen);
1623 				if (mm == NULL)
1624 					return ENOBUFS;
1625 
1626 				im = mtod(mm, struct igmpmsg *);
1627 				im->im_msgtype = IGMPMSG_WRONGVIF;
1628 				im->im_mbz = 0;
1629 				im->im_vif = vifi;
1630 
1631 				MRTSTAT_INC(mrts_upcalls);
1632 
1633 				k_igmpsrc.sin_addr = im->im_src;
1634 				if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1635 					CTR1(KTR_IPMF, "%s: socket queue full", __func__);
1636 					MRTSTAT_INC(mrts_upq_sockfull);
1637 					return ENOBUFS;
1638 				}
1639 			}
1640 		}
1641 		return 0;
1642 	}
1643 
1644 	/* If I sourced this packet, it counts as output, else it was input. */
1645 	mtx_lock_spin(&V_viftable[vifi].v_spin);
1646 	if (in_hosteq(ip->ip_src, V_viftable[vifi].v_lcl_addr)) {
1647 		V_viftable[vifi].v_pkt_out++;
1648 		V_viftable[vifi].v_bytes_out += plen;
1649 	} else {
1650 		V_viftable[vifi].v_pkt_in++;
1651 		V_viftable[vifi].v_bytes_in += plen;
1652 	}
1653 	mtx_unlock_spin(&V_viftable[vifi].v_spin);
1654 
1655 	rt->mfc_pkt_cnt++;
1656 	rt->mfc_byte_cnt += plen;
1657 
1658 	/*
1659 	 * For each vif, decide if a copy of the packet should be forwarded.
1660 	 * Forward if:
1661 	 *		- the ttl exceeds the vif's threshold
1662 	 *		- there are group members downstream on interface
1663 	 */
1664 	for (vifi = 0; vifi < V_numvifs; vifi++)
1665 		if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1666 			V_viftable[vifi].v_pkt_out++;
1667 			V_viftable[vifi].v_bytes_out += plen;
1668 			if (V_viftable[vifi].v_flags & VIFF_REGISTER)
1669 				pim_register_send(ip, V_viftable + vifi, m, rt);
1670 			else
1671 				phyint_send(ip, V_viftable + vifi, m);
1672 		}
1673 
1674 	/*
1675 	 * Perform upcall-related bw measuring.
1676 	 */
1677 	if ((rt->mfc_bw_meter_geq != NULL) || (rt->mfc_bw_meter_leq != NULL)) {
1678 		struct bw_meter *x;
1679 		struct timeval now;
1680 
1681 		microtime(&now);
1682 		/* Process meters for Greater-or-EQual case */
1683 		for (x = rt->mfc_bw_meter_geq; x != NULL; x = x->bm_mfc_next)
1684 			bw_meter_geq_receive_packet(x, plen, &now);
1685 
1686 		/* Process meters for Lower-or-EQual case */
1687 		for (x = rt->mfc_bw_meter_leq; x != NULL; x = x->bm_mfc_next) {
1688 			/*
1689 			 * Record that a packet is received.
1690 			 * Spin lock has to be taken as callout context
1691 			 * (expire_bw_meter_leq) might modify these fields
1692 			 * as well
1693 			 */
1694 			mtx_lock_spin(&x->bm_spin);
1695 			x->bm_measured.b_packets++;
1696 			x->bm_measured.b_bytes += plen;
1697 			mtx_unlock_spin(&x->bm_spin);
1698 		}
1699 	}
1700 
1701 	return 0;
1702 }
1703 
1704 /*
1705  * Check if a vif number is legal/ok. This is used by in_mcast.c.
1706  */
1707 static int
1708 X_legal_vif_num(int vif)
1709 {
1710 	int ret;
1711 
1712 	ret = 0;
1713 	if (vif < 0)
1714 		return (ret);
1715 
1716 	MRW_RLOCK();
1717 	if (vif < V_numvifs)
1718 		ret = 1;
1719 	MRW_RUNLOCK();
1720 
1721 	return (ret);
1722 }
1723 
1724 /*
1725  * Return the local address used by this vif
1726  */
1727 static u_long
1728 X_ip_mcast_src(int vifi)
1729 {
1730 	in_addr_t addr;
1731 
1732 	addr = INADDR_ANY;
1733 	if (vifi < 0)
1734 		return (addr);
1735 
1736 	MRW_RLOCK();
1737 	if (vifi < V_numvifs)
1738 		addr = V_viftable[vifi].v_lcl_addr.s_addr;
1739 	MRW_RUNLOCK();
1740 
1741 	return (addr);
1742 }
1743 
1744 static void
1745 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1746 {
1747 	struct mbuf *mb_copy;
1748 	int hlen = ip->ip_hl << 2;
1749 
1750 	MRW_LOCK_ASSERT();
1751 
1752 	/*
1753 	 * Make a new reference to the packet; make sure that
1754 	 * the IP header is actually copied, not just referenced,
1755 	 * so that ip_output() only scribbles on the copy.
1756 	 */
1757 	mb_copy = m_copypacket(m, M_NOWAIT);
1758 	if (mb_copy && (!M_WRITABLE(mb_copy) || mb_copy->m_len < hlen))
1759 		mb_copy = m_pullup(mb_copy, hlen);
1760 	if (mb_copy == NULL)
1761 		return;
1762 
1763 	send_packet(vifp, mb_copy);
1764 }
1765 
1766 static void
1767 send_packet(struct vif *vifp, struct mbuf *m)
1768 {
1769 	struct ip_moptions imo;
1770 	int error __unused;
1771 
1772 	MRW_LOCK_ASSERT();
1773 	NET_EPOCH_ASSERT();
1774 
1775 	imo.imo_multicast_ifp  = vifp->v_ifp;
1776 	imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1777 	imo.imo_multicast_loop = !!in_mcast_loop;
1778 	imo.imo_multicast_vif  = -1;
1779 	STAILQ_INIT(&imo.imo_head);
1780 
1781 	/*
1782 	 * Re-entrancy should not be a problem here, because
1783 	 * the packets that we send out and are looped back at us
1784 	 * should get rejected because they appear to come from
1785 	 * the loopback interface, thus preventing looping.
1786 	 */
1787 	error = ip_output(m, NULL, NULL, IP_FORWARDING, &imo, NULL);
1788 	CTR3(KTR_IPMF, "%s: vif %td err %d", __func__,
1789 	    (ptrdiff_t)(vifp - V_viftable), error);
1790 }
1791 
1792 /*
1793  * Stubs for old RSVP socket shim implementation.
1794  */
1795 
1796 static int
1797 X_ip_rsvp_vif(struct socket *so __unused, struct sockopt *sopt __unused)
1798 {
1799 
1800 	return (EOPNOTSUPP);
1801 }
1802 
1803 static void
1804 X_ip_rsvp_force_done(struct socket *so __unused)
1805 {
1806 
1807 }
1808 
1809 static int
1810 X_rsvp_input(struct mbuf **mp, int *offp, int proto)
1811 {
1812 	struct mbuf *m;
1813 
1814 	m = *mp;
1815 	*mp = NULL;
1816 	if (!V_rsvp_on)
1817 		m_freem(m);
1818 	return (IPPROTO_DONE);
1819 }
1820 
1821 /*
1822  * Code for bandwidth monitors
1823  */
1824 
1825 /*
1826  * Define common interface for timeval-related methods
1827  */
1828 #define	BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
1829 #define	BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
1830 #define	BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
1831 
1832 static uint32_t
1833 compute_bw_meter_flags(struct bw_upcall *req)
1834 {
1835 	uint32_t flags = 0;
1836 
1837 	if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
1838 		flags |= BW_METER_UNIT_PACKETS;
1839 	if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
1840 		flags |= BW_METER_UNIT_BYTES;
1841 	if (req->bu_flags & BW_UPCALL_GEQ)
1842 		flags |= BW_METER_GEQ;
1843 	if (req->bu_flags & BW_UPCALL_LEQ)
1844 		flags |= BW_METER_LEQ;
1845 
1846 	return flags;
1847 }
1848 
1849 static void
1850 expire_bw_meter_leq(void *arg)
1851 {
1852 	struct bw_meter *x = arg;
1853 	struct timeval now;
1854 	/*
1855 	 * INFO:
1856 	 * callout is always executed with MRW_WLOCK taken
1857 	 */
1858 
1859 	CURVNET_SET((struct vnet *)x->arg);
1860 
1861 	microtime(&now);
1862 
1863 	/*
1864 	 * Test if we should deliver an upcall
1865 	 */
1866 	if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
1867 	    (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
1868 	    ((x->bm_flags & BW_METER_UNIT_BYTES) &&
1869 	    (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
1870 		/* Prepare an upcall for delivery */
1871 		bw_meter_prepare_upcall(x, &now);
1872 	}
1873 
1874 	/* Send all upcalls that are pending delivery */
1875 	taskqueue_enqueue(V_task_queue, &V_task);
1876 
1877 	/* Reset counters */
1878 	x->bm_start_time = now;
1879 	/* Spin lock has to be taken as ip_forward context
1880 	 * might modify these fields as well
1881 	 */
1882 	mtx_lock_spin(&x->bm_spin);
1883 	x->bm_measured.b_bytes = 0;
1884 	x->bm_measured.b_packets = 0;
1885 	mtx_unlock_spin(&x->bm_spin);
1886 
1887 	callout_schedule(&x->bm_meter_callout, tvtohz(&x->bm_threshold.b_time));
1888 
1889 	CURVNET_RESTORE();
1890 }
1891 
1892 /*
1893  * Add a bw_meter entry
1894  */
1895 static int
1896 add_bw_upcall(struct bw_upcall *req)
1897 {
1898 	struct mfc *mfc;
1899 	struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
1900 	BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
1901 	struct timeval now;
1902 	struct bw_meter *x, **bwm_ptr;
1903 	uint32_t flags;
1904 
1905 	if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
1906 		return EOPNOTSUPP;
1907 
1908 	/* Test if the flags are valid */
1909 	if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
1910 		return EINVAL;
1911 	if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
1912 		return EINVAL;
1913 	if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)) == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
1914 		return EINVAL;
1915 
1916 	/* Test if the threshold time interval is valid */
1917 	if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
1918 		return EINVAL;
1919 
1920 	flags = compute_bw_meter_flags(req);
1921 
1922 	/*
1923 	 * Find if we have already same bw_meter entry
1924 	 */
1925 	MRW_WLOCK();
1926 	mfc = mfc_find(&req->bu_src, &req->bu_dst);
1927 	if (mfc == NULL) {
1928 		MRW_WUNLOCK();
1929 		return EADDRNOTAVAIL;
1930 	}
1931 
1932 	/* Choose an appropriate bw_meter list */
1933 	if (req->bu_flags & BW_UPCALL_GEQ)
1934 		bwm_ptr = &mfc->mfc_bw_meter_geq;
1935 	else
1936 		bwm_ptr = &mfc->mfc_bw_meter_leq;
1937 
1938 	for (x = *bwm_ptr; x != NULL; x = x->bm_mfc_next) {
1939 		if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
1940 		    &req->bu_threshold.b_time, ==))
1941 		    && (x->bm_threshold.b_packets
1942 		    == req->bu_threshold.b_packets)
1943 		    && (x->bm_threshold.b_bytes
1944 		    == req->bu_threshold.b_bytes)
1945 		    && (x->bm_flags & BW_METER_USER_FLAGS)
1946 		    == flags) {
1947 			MRW_WUNLOCK();
1948 			return 0; /* XXX Already installed */
1949 		}
1950 	}
1951 
1952 	/* Allocate the new bw_meter entry */
1953 	x = malloc(sizeof(*x), M_BWMETER, M_ZERO | M_NOWAIT);
1954 	if (x == NULL) {
1955 		MRW_WUNLOCK();
1956 		return ENOBUFS;
1957 	}
1958 
1959 	/* Set the new bw_meter entry */
1960 	x->bm_threshold.b_time = req->bu_threshold.b_time;
1961 	microtime(&now);
1962 	x->bm_start_time = now;
1963 	x->bm_threshold.b_packets = req->bu_threshold.b_packets;
1964 	x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
1965 	x->bm_measured.b_packets = 0;
1966 	x->bm_measured.b_bytes = 0;
1967 	x->bm_flags = flags;
1968 	x->bm_time_next = NULL;
1969 	x->bm_mfc = mfc;
1970 	x->arg = curvnet;
1971 	sprintf(x->bm_spin_name, "BM spin %p", x);
1972 	mtx_init(&x->bm_spin, x->bm_spin_name, NULL, MTX_SPIN);
1973 
1974 	/* For LEQ case create periodic callout */
1975 	if (req->bu_flags & BW_UPCALL_LEQ) {
1976 		callout_init_rw(&x->bm_meter_callout, &mrouter_lock, CALLOUT_SHAREDLOCK);
1977 		callout_reset(&x->bm_meter_callout, tvtohz(&x->bm_threshold.b_time),
1978 		    expire_bw_meter_leq, x);
1979 	}
1980 
1981 	/* Add the new bw_meter entry to the front of entries for this MFC */
1982 	x->bm_mfc_next = *bwm_ptr;
1983 	*bwm_ptr = x;
1984 
1985 	MRW_WUNLOCK();
1986 
1987 	return 0;
1988 }
1989 
1990 static void
1991 free_bw_list(struct bw_meter *list)
1992 {
1993 	while (list != NULL) {
1994 		struct bw_meter *x = list;
1995 
1996 		/* MRW_WLOCK must be held here */
1997 		if (x->bm_flags & BW_METER_LEQ) {
1998 			callout_drain(&x->bm_meter_callout);
1999 			mtx_destroy(&x->bm_spin);
2000 		}
2001 
2002 		list = list->bm_mfc_next;
2003 		free(x, M_BWMETER);
2004 	}
2005 }
2006 
2007 /*
2008  * Delete one or multiple bw_meter entries
2009  */
2010 static int
2011 del_bw_upcall(struct bw_upcall *req)
2012 {
2013 	struct mfc *mfc;
2014 	struct bw_meter *x, **bwm_ptr;
2015 
2016 	if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
2017 		return EOPNOTSUPP;
2018 
2019 	MRW_WLOCK();
2020 
2021 	/* Find the corresponding MFC entry */
2022 	mfc = mfc_find(&req->bu_src, &req->bu_dst);
2023 	if (mfc == NULL) {
2024 		MRW_WUNLOCK();
2025 		return EADDRNOTAVAIL;
2026 	} else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2027 		/*
2028 		 * Delete all bw_meter entries for this mfc
2029 		 */
2030 		struct bw_meter *list;
2031 
2032 		/* Free LEQ list */
2033 		list = mfc->mfc_bw_meter_leq;
2034 		mfc->mfc_bw_meter_leq = NULL;
2035 		free_bw_list(list);
2036 
2037 		/* Free GEQ list */
2038 		list = mfc->mfc_bw_meter_geq;
2039 		mfc->mfc_bw_meter_geq = NULL;
2040 		free_bw_list(list);
2041 		MRW_WUNLOCK();
2042 		return 0;
2043 	} else {			/* Delete a single bw_meter entry */
2044 		struct bw_meter *prev;
2045 		uint32_t flags = 0;
2046 
2047 		flags = compute_bw_meter_flags(req);
2048 
2049 		/* Choose an appropriate bw_meter list */
2050 		if (req->bu_flags & BW_UPCALL_GEQ)
2051 			bwm_ptr = &mfc->mfc_bw_meter_geq;
2052 		else
2053 			bwm_ptr = &mfc->mfc_bw_meter_leq;
2054 
2055 		/* Find the bw_meter entry to delete */
2056 		for (prev = NULL, x = *bwm_ptr; x != NULL;
2057 				prev = x, x = x->bm_mfc_next) {
2058 			if ((BW_TIMEVALCMP(&x->bm_threshold.b_time, &req->bu_threshold.b_time, ==)) &&
2059 			    (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2060 			    (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2061 			    (x->bm_flags & BW_METER_USER_FLAGS) == flags)
2062 				break;
2063 		}
2064 		if (x != NULL) { /* Delete entry from the list for this MFC */
2065 			if (prev != NULL)
2066 				prev->bm_mfc_next = x->bm_mfc_next;	/* remove from middle*/
2067 			else
2068 				*bwm_ptr = x->bm_mfc_next;/* new head of list */
2069 
2070 			if (req->bu_flags & BW_UPCALL_LEQ)
2071 				callout_stop(&x->bm_meter_callout);
2072 
2073 			MRW_WUNLOCK();
2074 			/* Free the bw_meter entry */
2075 			free(x, M_BWMETER);
2076 			return 0;
2077 		} else {
2078 			MRW_WUNLOCK();
2079 			return EINVAL;
2080 		}
2081 	}
2082 	__assert_unreachable();
2083 }
2084 
2085 /*
2086  * Perform bandwidth measurement processing that may result in an upcall
2087  */
2088 static void
2089 bw_meter_geq_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2090 {
2091 	struct timeval delta;
2092 
2093 	MRW_LOCK_ASSERT();
2094 
2095 	delta = *nowp;
2096 	BW_TIMEVALDECR(&delta, &x->bm_start_time);
2097 
2098 	/*
2099 	 * Processing for ">=" type of bw_meter entry.
2100 	 * bm_spin does not have to be hold here as in GEQ
2101 	 * case this is the only context accessing bm_measured.
2102 	 */
2103 	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2104 	    /* Reset the bw_meter entry */
2105 	    x->bm_start_time = *nowp;
2106 	    x->bm_measured.b_packets = 0;
2107 	    x->bm_measured.b_bytes = 0;
2108 	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2109 	}
2110 
2111 	/* Record that a packet is received */
2112 	x->bm_measured.b_packets++;
2113 	x->bm_measured.b_bytes += plen;
2114 
2115 	/*
2116 	 * Test if we should deliver an upcall
2117 	 */
2118 	if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2119 		if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2120 		    (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2121 		    ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2122 		    (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2123 			/* Prepare an upcall for delivery */
2124 			bw_meter_prepare_upcall(x, nowp);
2125 			x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2126 		}
2127 	}
2128 }
2129 
2130 /*
2131  * Prepare a bandwidth-related upcall
2132  */
2133 static void
2134 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2135 {
2136 	struct timeval delta;
2137 	struct bw_upcall *u;
2138 
2139 	MRW_LOCK_ASSERT();
2140 
2141 	/*
2142 	 * Compute the measured time interval
2143 	 */
2144 	delta = *nowp;
2145 	BW_TIMEVALDECR(&delta, &x->bm_start_time);
2146 
2147 	/*
2148 	 * Set the bw_upcall entry
2149 	 */
2150 	u = malloc(sizeof(struct bw_upcall), M_MRTABLE, M_NOWAIT | M_ZERO);
2151 	if (!u) {
2152 		log(LOG_WARNING, "bw_meter_prepare_upcall: cannot allocate entry\n");
2153 		return;
2154 	}
2155 	u->bu_src = x->bm_mfc->mfc_origin;
2156 	u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2157 	u->bu_threshold.b_time = x->bm_threshold.b_time;
2158 	u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2159 	u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2160 	u->bu_measured.b_time = delta;
2161 	u->bu_measured.b_packets = x->bm_measured.b_packets;
2162 	u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2163 	u->bu_flags = 0;
2164 	if (x->bm_flags & BW_METER_UNIT_PACKETS)
2165 		u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2166 	if (x->bm_flags & BW_METER_UNIT_BYTES)
2167 		u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2168 	if (x->bm_flags & BW_METER_GEQ)
2169 		u->bu_flags |= BW_UPCALL_GEQ;
2170 	if (x->bm_flags & BW_METER_LEQ)
2171 		u->bu_flags |= BW_UPCALL_LEQ;
2172 
2173 	if (buf_ring_enqueue(V_bw_upcalls_ring, u))
2174 		log(LOG_WARNING, "bw_meter_prepare_upcall: cannot enqueue upcall\n");
2175 	if (buf_ring_count(V_bw_upcalls_ring) > (BW_UPCALLS_MAX / 2)) {
2176 		taskqueue_enqueue(V_task_queue, &V_task);
2177 	}
2178 }
2179 /*
2180  * Send the pending bandwidth-related upcalls
2181  */
2182 static void
2183 bw_upcalls_send(void)
2184 {
2185 	struct mbuf *m;
2186 	int len = 0;
2187 	struct bw_upcall *bu;
2188 	struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2189 	static struct igmpmsg igmpmsg = {
2190 		0,		/* unused1 */
2191 		0,		/* unused2 */
2192 		IGMPMSG_BW_UPCALL,/* im_msgtype */
2193 		0,		/* im_mbz  */
2194 		0,		/* im_vif  */
2195 		0,		/* unused3 */
2196 		{ 0 },		/* im_src  */
2197 		{ 0 }		/* im_dst  */
2198 	};
2199 
2200 	MRW_LOCK_ASSERT();
2201 
2202 	if (buf_ring_empty(V_bw_upcalls_ring))
2203 		return;
2204 
2205 	/*
2206 	 * Allocate a new mbuf, initialize it with the header and
2207 	 * the payload for the pending calls.
2208 	 */
2209 	m = m_gethdr(M_NOWAIT, MT_DATA);
2210 	if (m == NULL) {
2211 		log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2212 		return;
2213 	}
2214 
2215 	m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2216 	len += sizeof(struct igmpmsg);
2217 	while ((bu = buf_ring_dequeue_mc(V_bw_upcalls_ring)) != NULL) {
2218 		m_copyback(m, len, sizeof(struct bw_upcall), (caddr_t)bu);
2219 		len += sizeof(struct bw_upcall);
2220 		free(bu, M_MRTABLE);
2221 	}
2222 
2223 	/*
2224 	 * Send the upcalls
2225 	 * XXX do we need to set the address in k_igmpsrc ?
2226 	 */
2227 	MRTSTAT_INC(mrts_upcalls);
2228 	if (socket_send(V_ip_mrouter, m, &k_igmpsrc) < 0) {
2229 		log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2230 		MRTSTAT_INC(mrts_upq_sockfull);
2231 	}
2232 }
2233 
2234 /*
2235  * A periodic function for sending all upcalls that are pending delivery
2236  */
2237 static void
2238 expire_bw_upcalls_send(void *arg)
2239 {
2240 	CURVNET_SET((struct vnet *) arg);
2241 
2242 	/* This callout is run with MRW_RLOCK taken */
2243 
2244 	bw_upcalls_send();
2245 
2246 	callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
2247 	    curvnet);
2248 	CURVNET_RESTORE();
2249 }
2250 
2251 /*
2252  * End of bandwidth monitoring code
2253  */
2254 
2255 /*
2256  * Send the packet up to the user daemon, or eventually do kernel encapsulation
2257  *
2258  */
2259 static int
2260 pim_register_send(struct ip *ip, struct vif *vifp, struct mbuf *m,
2261     struct mfc *rt)
2262 {
2263 	struct mbuf *mb_copy, *mm;
2264 
2265 	/*
2266 	 * Do not send IGMP_WHOLEPKT notifications to userland, if the
2267 	 * rendezvous point was unspecified, and we were told not to.
2268 	 */
2269 	if (pim_squelch_wholepkt != 0 && (V_mrt_api_config & MRT_MFC_RP) &&
2270 	    in_nullhost(rt->mfc_rp))
2271 		return 0;
2272 
2273 	mb_copy = pim_register_prepare(ip, m);
2274 	if (mb_copy == NULL)
2275 		return ENOBUFS;
2276 
2277 	/*
2278 	 * Send all the fragments. Note that the mbuf for each fragment
2279 	 * is freed by the sending machinery.
2280 	 */
2281 	for (mm = mb_copy; mm; mm = mb_copy) {
2282 		mb_copy = mm->m_nextpkt;
2283 		mm->m_nextpkt = 0;
2284 		mm = m_pullup(mm, sizeof(struct ip));
2285 		if (mm != NULL) {
2286 			ip = mtod(mm, struct ip *);
2287 			if ((V_mrt_api_config & MRT_MFC_RP) && !in_nullhost(rt->mfc_rp)) {
2288 				pim_register_send_rp(ip, vifp, mm, rt);
2289 			} else {
2290 				pim_register_send_upcall(ip, vifp, mm, rt);
2291 			}
2292 		}
2293 	}
2294 
2295 	return 0;
2296 }
2297 
2298 /*
2299  * Return a copy of the data packet that is ready for PIM Register
2300  * encapsulation.
2301  * XXX: Note that in the returned copy the IP header is a valid one.
2302  */
2303 static struct mbuf *
2304 pim_register_prepare(struct ip *ip, struct mbuf *m)
2305 {
2306 	struct mbuf *mb_copy = NULL;
2307 	int mtu;
2308 
2309 	/* Take care of delayed checksums */
2310 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2311 		in_delayed_cksum(m);
2312 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2313 	}
2314 
2315 	/*
2316 	 * Copy the old packet & pullup its IP header into the
2317 	 * new mbuf so we can modify it.
2318 	 */
2319 	mb_copy = m_copypacket(m, M_NOWAIT);
2320 	if (mb_copy == NULL)
2321 		return NULL;
2322 	mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2323 	if (mb_copy == NULL)
2324 		return NULL;
2325 
2326 	/* take care of the TTL */
2327 	ip = mtod(mb_copy, struct ip *);
2328 	--ip->ip_ttl;
2329 
2330 	/* Compute the MTU after the PIM Register encapsulation */
2331 	mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2332 
2333 	if (ntohs(ip->ip_len) <= mtu) {
2334 		/* Turn the IP header into a valid one */
2335 		ip->ip_sum = 0;
2336 		ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2337 	} else {
2338 		/* Fragment the packet */
2339 		mb_copy->m_pkthdr.csum_flags |= CSUM_IP;
2340 		if (ip_fragment(ip, &mb_copy, mtu, 0) != 0) {
2341 			m_freem(mb_copy);
2342 			return NULL;
2343 		}
2344 	}
2345 	return mb_copy;
2346 }
2347 
2348 /*
2349  * Send an upcall with the data packet to the user-level process.
2350  */
2351 static int
2352 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2353     struct mbuf *mb_copy, struct mfc *rt)
2354 {
2355 	struct mbuf *mb_first;
2356 	int len = ntohs(ip->ip_len);
2357 	struct igmpmsg *im;
2358 	struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2359 
2360 	MRW_LOCK_ASSERT();
2361 
2362 	/*
2363 	 * Add a new mbuf with an upcall header
2364 	 */
2365 	mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2366 	if (mb_first == NULL) {
2367 		m_freem(mb_copy);
2368 		return ENOBUFS;
2369 	}
2370 	mb_first->m_data += max_linkhdr;
2371 	mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2372 	mb_first->m_len = sizeof(struct igmpmsg);
2373 	mb_first->m_next = mb_copy;
2374 
2375 	/* Send message to routing daemon */
2376 	im = mtod(mb_first, struct igmpmsg *);
2377 	im->im_msgtype	= IGMPMSG_WHOLEPKT;
2378 	im->im_mbz		= 0;
2379 	im->im_vif		= vifp - V_viftable;
2380 	im->im_src		= ip->ip_src;
2381 	im->im_dst		= ip->ip_dst;
2382 
2383 	k_igmpsrc.sin_addr	= ip->ip_src;
2384 
2385 	MRTSTAT_INC(mrts_upcalls);
2386 
2387 	if (socket_send(V_ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2388 		CTR1(KTR_IPMF, "%s: socket queue full", __func__);
2389 		MRTSTAT_INC(mrts_upq_sockfull);
2390 		return ENOBUFS;
2391 	}
2392 
2393 	/* Keep statistics */
2394 	PIMSTAT_INC(pims_snd_registers_msgs);
2395 	PIMSTAT_ADD(pims_snd_registers_bytes, len);
2396 
2397 	return 0;
2398 }
2399 
2400 /*
2401  * Encapsulate the data packet in PIM Register message and send it to the RP.
2402  */
2403 static int
2404 pim_register_send_rp(struct ip *ip, struct vif *vifp, struct mbuf *mb_copy,
2405     struct mfc *rt)
2406 {
2407 	struct mbuf *mb_first;
2408 	struct ip *ip_outer;
2409 	struct pim_encap_pimhdr *pimhdr;
2410 	int len = ntohs(ip->ip_len);
2411 	vifi_t vifi = rt->mfc_parent;
2412 
2413 	MRW_LOCK_ASSERT();
2414 
2415 	if ((vifi >= V_numvifs) || in_nullhost(V_viftable[vifi].v_lcl_addr)) {
2416 		m_freem(mb_copy);
2417 		return EADDRNOTAVAIL;		/* The iif vif is invalid */
2418 	}
2419 
2420 	/*
2421 	 * Add a new mbuf with the encapsulating header
2422 	 */
2423 	mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2424 	if (mb_first == NULL) {
2425 		m_freem(mb_copy);
2426 		return ENOBUFS;
2427 	}
2428 	mb_first->m_data += max_linkhdr;
2429 	mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2430 	mb_first->m_next = mb_copy;
2431 
2432 	mb_first->m_pkthdr.len = len + mb_first->m_len;
2433 
2434 	/*
2435 	 * Fill in the encapsulating IP and PIM header
2436 	 */
2437 	ip_outer = mtod(mb_first, struct ip *);
2438 	*ip_outer = pim_encap_iphdr;
2439 	ip_outer->ip_len = htons(len + sizeof(pim_encap_iphdr) +
2440 			sizeof(pim_encap_pimhdr));
2441 	ip_outer->ip_src = V_viftable[vifi].v_lcl_addr;
2442 	ip_outer->ip_dst = rt->mfc_rp;
2443 	/*
2444 	 * Copy the inner header TOS to the outer header, and take care of the
2445 	 * IP_DF bit.
2446 	 */
2447 	ip_outer->ip_tos = ip->ip_tos;
2448 	if (ip->ip_off & htons(IP_DF))
2449 		ip_outer->ip_off |= htons(IP_DF);
2450 	ip_fillid(ip_outer);
2451 	pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2452 			+ sizeof(pim_encap_iphdr));
2453 	*pimhdr = pim_encap_pimhdr;
2454 	/* If the iif crosses a border, set the Border-bit */
2455 	if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & V_mrt_api_config)
2456 		pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
2457 
2458 	mb_first->m_data += sizeof(pim_encap_iphdr);
2459 	pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
2460 	mb_first->m_data -= sizeof(pim_encap_iphdr);
2461 
2462 	send_packet(vifp, mb_first);
2463 
2464 	/* Keep statistics */
2465 	PIMSTAT_INC(pims_snd_registers_msgs);
2466 	PIMSTAT_ADD(pims_snd_registers_bytes, len);
2467 
2468 	return 0;
2469 }
2470 
2471 /*
2472  * pim_encapcheck() is called by the encap4_input() path at runtime to
2473  * determine if a packet is for PIM; allowing PIM to be dynamically loaded
2474  * into the kernel.
2475  */
2476 static int
2477 pim_encapcheck(const struct mbuf *m __unused, int off __unused,
2478     int proto __unused, void *arg __unused)
2479 {
2480 
2481 	KASSERT(proto == IPPROTO_PIM, ("not for IPPROTO_PIM"));
2482 	return (8);		/* claim the datagram. */
2483 }
2484 
2485 /*
2486  * PIM-SMv2 and PIM-DM messages processing.
2487  * Receives and verifies the PIM control messages, and passes them
2488  * up to the listening socket, using rip_input().
2489  * The only message with special processing is the PIM_REGISTER message
2490  * (used by PIM-SM): the PIM header is stripped off, and the inner packet
2491  * is passed to if_simloop().
2492  */
2493 static int
2494 pim_input(struct mbuf *m, int off, int proto, void *arg __unused)
2495 {
2496 	struct ip *ip = mtod(m, struct ip *);
2497 	struct pim *pim;
2498 	int iphlen = off;
2499 	int minlen;
2500 	int datalen = ntohs(ip->ip_len) - iphlen;
2501 	int ip_tos;
2502 
2503 	/* Keep statistics */
2504 	PIMSTAT_INC(pims_rcv_total_msgs);
2505 	PIMSTAT_ADD(pims_rcv_total_bytes, datalen);
2506 
2507 	/*
2508 	 * Validate lengths
2509 	 */
2510 	if (datalen < PIM_MINLEN) {
2511 		PIMSTAT_INC(pims_rcv_tooshort);
2512 		CTR3(KTR_IPMF, "%s: short packet (%d) from 0x%08x",
2513 		    __func__, datalen, ntohl(ip->ip_src.s_addr));
2514 		m_freem(m);
2515 		return (IPPROTO_DONE);
2516 	}
2517 
2518 	/*
2519 	 * If the packet is at least as big as a REGISTER, go agead
2520 	 * and grab the PIM REGISTER header size, to avoid another
2521 	 * possible m_pullup() later.
2522 	 *
2523 	 * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
2524 	 * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
2525 	 */
2526 	minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
2527 	/*
2528 	 * Get the IP and PIM headers in contiguous memory, and
2529 	 * possibly the PIM REGISTER header.
2530 	 */
2531 	if (m->m_len < minlen && (m = m_pullup(m, minlen)) == NULL) {
2532 		CTR1(KTR_IPMF, "%s: m_pullup() failed", __func__);
2533 		return (IPPROTO_DONE);
2534 	}
2535 
2536 	/* m_pullup() may have given us a new mbuf so reset ip. */
2537 	ip = mtod(m, struct ip *);
2538 	ip_tos = ip->ip_tos;
2539 
2540 	/* adjust mbuf to point to the PIM header */
2541 	m->m_data += iphlen;
2542 	m->m_len  -= iphlen;
2543 	pim = mtod(m, struct pim *);
2544 
2545 	/*
2546 	 * Validate checksum. If PIM REGISTER, exclude the data packet.
2547 	 *
2548 	 * XXX: some older PIMv2 implementations don't make this distinction,
2549 	 * so for compatibility reason perform the checksum over part of the
2550 	 * message, and if error, then over the whole message.
2551 	 */
2552 	if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
2553 		/* do nothing, checksum okay */
2554 	} else if (in_cksum(m, datalen)) {
2555 		PIMSTAT_INC(pims_rcv_badsum);
2556 		CTR1(KTR_IPMF, "%s: invalid checksum", __func__);
2557 		m_freem(m);
2558 		return (IPPROTO_DONE);
2559 	}
2560 
2561 	/* PIM version check */
2562 	if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
2563 		PIMSTAT_INC(pims_rcv_badversion);
2564 		CTR3(KTR_IPMF, "%s: bad version %d expect %d", __func__,
2565 		    (int)PIM_VT_V(pim->pim_vt), PIM_VERSION);
2566 		m_freem(m);
2567 		return (IPPROTO_DONE);
2568 	}
2569 
2570 	/* restore mbuf back to the outer IP */
2571 	m->m_data -= iphlen;
2572 	m->m_len  += iphlen;
2573 
2574 	if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
2575 		/*
2576 		 * Since this is a REGISTER, we'll make a copy of the register
2577 		 * headers ip + pim + u_int32 + encap_ip, to be passed up to the
2578 		 * routing daemon.
2579 		 */
2580 		struct sockaddr_in dst = { sizeof(dst), AF_INET };
2581 		struct mbuf *mcp;
2582 		struct ip *encap_ip;
2583 		u_int32_t *reghdr;
2584 		struct ifnet *vifp;
2585 
2586 		MRW_RLOCK();
2587 		if ((V_reg_vif_num >= V_numvifs) || (V_reg_vif_num == VIFI_INVALID)) {
2588 			MRW_RUNLOCK();
2589 			CTR2(KTR_IPMF, "%s: register vif not set: %d", __func__,
2590 			    (int)V_reg_vif_num);
2591 			m_freem(m);
2592 			return (IPPROTO_DONE);
2593 		}
2594 		/* XXX need refcnt? */
2595 		vifp = V_viftable[V_reg_vif_num].v_ifp;
2596 		MRW_RUNLOCK();
2597 
2598 		/*
2599 		 * Validate length
2600 		 */
2601 		if (datalen < PIM_REG_MINLEN) {
2602 			PIMSTAT_INC(pims_rcv_tooshort);
2603 			PIMSTAT_INC(pims_rcv_badregisters);
2604 			CTR1(KTR_IPMF, "%s: register packet size too small", __func__);
2605 			m_freem(m);
2606 			return (IPPROTO_DONE);
2607 		}
2608 
2609 		reghdr = (u_int32_t *)(pim + 1);
2610 		encap_ip = (struct ip *)(reghdr + 1);
2611 
2612 		CTR3(KTR_IPMF, "%s: register: encap ip src 0x%08x len %d",
2613 		    __func__, ntohl(encap_ip->ip_src.s_addr),
2614 		    ntohs(encap_ip->ip_len));
2615 
2616 		/* verify the version number of the inner packet */
2617 		if (encap_ip->ip_v != IPVERSION) {
2618 			PIMSTAT_INC(pims_rcv_badregisters);
2619 			CTR1(KTR_IPMF, "%s: bad encap ip version", __func__);
2620 			m_freem(m);
2621 			return (IPPROTO_DONE);
2622 		}
2623 
2624 		/* verify the inner packet is destined to a mcast group */
2625 		if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
2626 			PIMSTAT_INC(pims_rcv_badregisters);
2627 			CTR2(KTR_IPMF, "%s: bad encap ip dest 0x%08x", __func__,
2628 			    ntohl(encap_ip->ip_dst.s_addr));
2629 			m_freem(m);
2630 			return (IPPROTO_DONE);
2631 		}
2632 
2633 		/* If a NULL_REGISTER, pass it to the daemon */
2634 		if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
2635 			goto pim_input_to_daemon;
2636 
2637 		/*
2638 		 * Copy the TOS from the outer IP header to the inner IP header.
2639 		 */
2640 		if (encap_ip->ip_tos != ip_tos) {
2641 			/* Outer TOS -> inner TOS */
2642 			encap_ip->ip_tos = ip_tos;
2643 			/* Recompute the inner header checksum. Sigh... */
2644 
2645 			/* adjust mbuf to point to the inner IP header */
2646 			m->m_data += (iphlen + PIM_MINLEN);
2647 			m->m_len  -= (iphlen + PIM_MINLEN);
2648 
2649 			encap_ip->ip_sum = 0;
2650 			encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
2651 
2652 			/* restore mbuf to point back to the outer IP header */
2653 			m->m_data -= (iphlen + PIM_MINLEN);
2654 			m->m_len  += (iphlen + PIM_MINLEN);
2655 		}
2656 
2657 		/*
2658 		 * Decapsulate the inner IP packet and loopback to forward it
2659 		 * as a normal multicast packet. Also, make a copy of the
2660 		 *     outer_iphdr + pimhdr + reghdr + encap_iphdr
2661 		 * to pass to the daemon later, so it can take the appropriate
2662 		 * actions (e.g., send back PIM_REGISTER_STOP).
2663 		 * XXX: here m->m_data points to the outer IP header.
2664 		 */
2665 		mcp = m_copym(m, 0, iphlen + PIM_REG_MINLEN, M_NOWAIT);
2666 		if (mcp == NULL) {
2667 			CTR1(KTR_IPMF, "%s: m_copym() failed", __func__);
2668 			m_freem(m);
2669 			return (IPPROTO_DONE);
2670 		}
2671 
2672 		/* Keep statistics */
2673 		/* XXX: registers_bytes include only the encap. mcast pkt */
2674 		PIMSTAT_INC(pims_rcv_registers_msgs);
2675 		PIMSTAT_ADD(pims_rcv_registers_bytes, ntohs(encap_ip->ip_len));
2676 
2677 		/*
2678 		 * forward the inner ip packet; point m_data at the inner ip.
2679 		 */
2680 		m_adj(m, iphlen + PIM_MINLEN);
2681 
2682 		CTR4(KTR_IPMF,
2683 		    "%s: forward decap'd REGISTER: src %lx dst %lx vif %d",
2684 		    __func__,
2685 		    (u_long)ntohl(encap_ip->ip_src.s_addr),
2686 		    (u_long)ntohl(encap_ip->ip_dst.s_addr),
2687 		    (int)V_reg_vif_num);
2688 
2689 		/* NB: vifp was collected above; can it change on us? */
2690 		if_simloop(vifp, m, dst.sin_family, 0);
2691 
2692 		/* prepare the register head to send to the mrouting daemon */
2693 		m = mcp;
2694 	}
2695 
2696 pim_input_to_daemon:
2697 	/*
2698 	 * Pass the PIM message up to the daemon; if it is a Register message,
2699 	 * pass the 'head' only up to the daemon. This includes the
2700 	 * outer IP header, PIM header, PIM-Register header and the
2701 	 * inner IP header.
2702 	 * XXX: the outer IP header pkt size of a Register is not adjust to
2703 	 * reflect the fact that the inner multicast data is truncated.
2704 	 */
2705 	return (rip_input(&m, &off, proto));
2706 }
2707 
2708 static int
2709 sysctl_mfctable(SYSCTL_HANDLER_ARGS)
2710 {
2711 	struct mfc	*rt;
2712 	int		 error, i;
2713 
2714 	if (req->newptr)
2715 		return (EPERM);
2716 	if (V_mfchashtbl == NULL)	/* XXX unlocked */
2717 		return (0);
2718 	error = sysctl_wire_old_buffer(req, 0);
2719 	if (error)
2720 		return (error);
2721 
2722 	MRW_RLOCK();
2723 	for (i = 0; i < mfchashsize; i++) {
2724 		LIST_FOREACH(rt, &V_mfchashtbl[i], mfc_hash) {
2725 			error = SYSCTL_OUT(req, rt, sizeof(struct mfc));
2726 			if (error)
2727 				goto out_locked;
2728 		}
2729 	}
2730 out_locked:
2731 	MRW_RUNLOCK();
2732 	return (error);
2733 }
2734 
2735 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, mfctable,
2736     CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_mfctable,
2737     "IPv4 Multicast Forwarding Table "
2738     "(struct *mfc[mfchashsize], netinet/ip_mroute.h)");
2739 
2740 static int
2741 sysctl_viflist(SYSCTL_HANDLER_ARGS)
2742 {
2743 	int error, i;
2744 
2745 	if (req->newptr)
2746 		return (EPERM);
2747 	if (V_viftable == NULL)		/* XXX unlocked */
2748 		return (0);
2749 	error = sysctl_wire_old_buffer(req, MROUTE_VIF_SYSCTL_LEN * MAXVIFS);
2750 	if (error)
2751 		return (error);
2752 
2753 	MRW_RLOCK();
2754 	/* Copy out user-visible portion of vif entry. */
2755 	for (i = 0; i < MAXVIFS; i++) {
2756 		error = SYSCTL_OUT(req, &V_viftable[i], MROUTE_VIF_SYSCTL_LEN);
2757 		if (error)
2758 			break;
2759 	}
2760 	MRW_RUNLOCK();
2761 	return (error);
2762 }
2763 
2764 SYSCTL_PROC(_net_inet_ip, OID_AUTO, viftable,
2765     CTLTYPE_OPAQUE | CTLFLAG_VNET | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2766     sysctl_viflist, "S,vif[MAXVIFS]",
2767     "IPv4 Multicast Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
2768 
2769 static void
2770 vnet_mroute_init(const void *unused __unused)
2771 {
2772 
2773 	V_nexpire = malloc(mfchashsize, M_MRTABLE, M_WAITOK|M_ZERO);
2774 
2775 	V_viftable = mallocarray(MAXVIFS, sizeof(*V_viftable),
2776 	    M_MRTABLE, M_WAITOK|M_ZERO);
2777 
2778 	callout_init_rw(&V_expire_upcalls_ch, &mrouter_lock, 0);
2779 	callout_init_rw(&V_bw_upcalls_ch, &mrouter_lock, 0);
2780 
2781 	/* Prepare taskqueue */
2782 	V_task_queue = taskqueue_create_fast("ip_mroute_tskq", M_NOWAIT,
2783 		    taskqueue_thread_enqueue, &V_task_queue);
2784 	taskqueue_start_threads(&V_task_queue, 1, PI_NET, "ip_mroute_tskq task");
2785 }
2786 
2787 VNET_SYSINIT(vnet_mroute_init, SI_SUB_PROTO_MC, SI_ORDER_ANY, vnet_mroute_init,
2788 	NULL);
2789 
2790 static void
2791 vnet_mroute_uninit(const void *unused __unused)
2792 {
2793 
2794 	/* Taskqueue should be cancelled and drained before freeing */
2795 	taskqueue_free(V_task_queue);
2796 
2797 	free(V_viftable, M_MRTABLE);
2798 	free(V_nexpire, M_MRTABLE);
2799 	V_nexpire = NULL;
2800 }
2801 
2802 VNET_SYSUNINIT(vnet_mroute_uninit, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE,
2803     vnet_mroute_uninit, NULL);
2804 
2805 static int
2806 ip_mroute_modevent(module_t mod, int type, void *unused)
2807 {
2808 
2809 	switch (type) {
2810 	case MOD_LOAD:
2811 		MRW_LOCK_INIT();
2812 
2813 		if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
2814 		    if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
2815 		if (if_detach_event_tag == NULL) {
2816 			printf("ip_mroute: unable to register "
2817 					"ifnet_departure_event handler\n");
2818 			MRW_LOCK_DESTROY();
2819 			return (EINVAL);
2820 		}
2821 
2822 		if (!powerof2(mfchashsize)) {
2823 			printf("WARNING: %s not a power of 2; using default\n",
2824 					"net.inet.ip.mfchashsize");
2825 			mfchashsize = MFCHASHSIZE;
2826 		}
2827 
2828 		pim_encap_cookie = ip_encap_attach(&ipv4_encap_cfg, NULL, M_WAITOK);
2829 
2830 		ip_mcast_src = X_ip_mcast_src;
2831 		ip_mforward = X_ip_mforward;
2832 		ip_mrouter_done = X_ip_mrouter_done;
2833 		ip_mrouter_get = X_ip_mrouter_get;
2834 		ip_mrouter_set = X_ip_mrouter_set;
2835 
2836 		ip_rsvp_force_done = X_ip_rsvp_force_done;
2837 		ip_rsvp_vif = X_ip_rsvp_vif;
2838 
2839 		legal_vif_num = X_legal_vif_num;
2840 		mrt_ioctl = X_mrt_ioctl;
2841 		rsvp_input_p = X_rsvp_input;
2842 		break;
2843 
2844 	case MOD_UNLOAD:
2845 		/*
2846 		 * Typically module unload happens after the user-level
2847 		 * process has shutdown the kernel services (the check
2848 		 * below insures someone can't just yank the module out
2849 		 * from under a running process).  But if the module is
2850 		 * just loaded and then unloaded w/o starting up a user
2851 		 * process we still need to cleanup.
2852 		 */
2853 		MRW_WLOCK();
2854 		if (ip_mrouter_cnt != 0) {
2855 			MRW_WUNLOCK();
2856 			return (EINVAL);
2857 		}
2858 		ip_mrouter_unloading = 1;
2859 		MRW_WUNLOCK();
2860 
2861 		EVENTHANDLER_DEREGISTER(ifnet_departure_event, if_detach_event_tag);
2862 
2863 		if (pim_encap_cookie) {
2864 			ip_encap_detach(pim_encap_cookie);
2865 			pim_encap_cookie = NULL;
2866 		}
2867 
2868 		ip_mcast_src = NULL;
2869 		ip_mforward = NULL;
2870 		ip_mrouter_done = NULL;
2871 		ip_mrouter_get = NULL;
2872 		ip_mrouter_set = NULL;
2873 
2874 		ip_rsvp_force_done = NULL;
2875 		ip_rsvp_vif = NULL;
2876 
2877 		legal_vif_num = NULL;
2878 		mrt_ioctl = NULL;
2879 		rsvp_input_p = NULL;
2880 
2881 		MRW_LOCK_DESTROY();
2882 		break;
2883 
2884 	default:
2885 		return EOPNOTSUPP;
2886 	}
2887 	return 0;
2888 }
2889 
2890 static moduledata_t ip_mroutemod = {
2891 	"ip_mroute",
2892 	ip_mroute_modevent,
2893 	0
2894 };
2895 
2896 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);
2897