xref: /freebsd/sys/netinet/ip_mroute.c (revision 3494f7c0)
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 	rt = mfc_find(&origin, &mcastgrp);
1254 	if (rt == NULL) {
1255 		MRW_WUNLOCK();
1256 		return EADDRNOTAVAIL;
1257 	}
1258 
1259 	/*
1260 	 * free the bw_meter entries
1261 	 */
1262 	free_bw_list(rt->mfc_bw_meter_leq);
1263 	rt->mfc_bw_meter_leq = NULL;
1264 	free_bw_list(rt->mfc_bw_meter_geq);
1265 	rt->mfc_bw_meter_geq = NULL;
1266 
1267 	LIST_REMOVE(rt, mfc_hash);
1268 	free(rt, M_MRTABLE);
1269 
1270 	MRW_WUNLOCK();
1271 
1272 	return (0);
1273 }
1274 
1275 /*
1276  * Send a message to the routing daemon on the multicast routing socket.
1277  */
1278 static int
1279 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1280 {
1281 	if (s) {
1282 		SOCKBUF_LOCK(&s->so_rcv);
1283 		if (sbappendaddr_locked(&s->so_rcv, (struct sockaddr *)src, mm,
1284 		    NULL) != 0) {
1285 			sorwakeup_locked(s);
1286 			return 0;
1287 		}
1288 		soroverflow_locked(s);
1289 	}
1290 	m_freem(mm);
1291 	return -1;
1292 }
1293 
1294 /*
1295  * IP multicast forwarding function. This function assumes that the packet
1296  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1297  * pointed to by "ifp", and the packet is to be relayed to other networks
1298  * that have members of the packet's destination IP multicast group.
1299  *
1300  * The packet is returned unscathed to the caller, unless it is
1301  * erroneous, in which case a non-zero return value tells the caller to
1302  * discard it.
1303  */
1304 
1305 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1306 
1307 static int
1308 X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1309     struct ip_moptions *imo)
1310 {
1311 	struct mfc *rt;
1312 	int error;
1313 	vifi_t vifi;
1314 	struct mbuf *mb0;
1315 	struct rtdetq *rte;
1316 	u_long hash;
1317 	int hlen;
1318 
1319 	CTR3(KTR_IPMF, "ip_mforward: delete mfc orig 0x%08x group %lx ifp %p",
1320 	    ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr), ifp);
1321 
1322 	if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1323 	    ((u_char *)(ip + 1))[1] != IPOPT_LSRR) {
1324 		/*
1325 		 * Packet arrived via a physical interface or
1326 		 * an encapsulated tunnel or a register_vif.
1327 		 */
1328 	} else {
1329 		/*
1330 		 * Packet arrived through a source-route tunnel.
1331 		 * Source-route tunnels are no longer supported.
1332 		 */
1333 		return (1);
1334 	}
1335 
1336 	/*
1337 	 * BEGIN: MCAST ROUTING HOT PATH
1338 	 */
1339 	MRW_RLOCK();
1340 	if (imo && ((vifi = imo->imo_multicast_vif) < V_numvifs)) {
1341 		if (ip->ip_ttl < MAXTTL)
1342 			ip->ip_ttl++; /* compensate for -1 in *_send routines */
1343 		error = ip_mdq(m, ifp, NULL, vifi);
1344 		MRW_RUNLOCK();
1345 		return error;
1346 	}
1347 
1348 	/*
1349 	 * Don't forward a packet with time-to-live of zero or one,
1350 	 * or a packet destined to a local-only group.
1351 	 */
1352 	if (ip->ip_ttl <= 1 || IN_LOCAL_GROUP(ntohl(ip->ip_dst.s_addr))) {
1353 		MRW_RUNLOCK();
1354 		return 0;
1355 	}
1356 
1357 mfc_find_retry:
1358 	/*
1359 	 * Determine forwarding vifs from the forwarding cache table
1360 	 */
1361 	MRTSTAT_INC(mrts_mfc_lookups);
1362 	rt = mfc_find(&ip->ip_src, &ip->ip_dst);
1363 
1364 	/* Entry exists, so forward if necessary */
1365 	if (rt != NULL) {
1366 		error = ip_mdq(m, ifp, rt, -1);
1367 		/* Generic unlock here as we might release R or W lock */
1368 		MRW_UNLOCK();
1369 		return error;
1370 	}
1371 
1372 	/*
1373 	 * END: MCAST ROUTING HOT PATH
1374 	 */
1375 
1376 	/* Further processing must be done with WLOCK taken */
1377 	if ((MRW_WOWNED() == 0) && (MRW_LOCK_TRY_UPGRADE() == 0)) {
1378 		MRW_RUNLOCK();
1379 		MRW_WLOCK();
1380 		goto mfc_find_retry;
1381 	}
1382 
1383 	/*
1384 	 * If we don't have a route for packet's origin,
1385 	 * Make a copy of the packet & send message to routing daemon
1386 	 */
1387 	hlen = ip->ip_hl << 2;
1388 
1389 	MRTSTAT_INC(mrts_mfc_misses);
1390 	MRTSTAT_INC(mrts_no_route);
1391 	CTR2(KTR_IPMF, "ip_mforward: no mfc for (0x%08x,%lx)",
1392 	    ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr));
1393 
1394 	/*
1395 	 * Allocate mbufs early so that we don't do extra work if we are
1396 	 * just going to fail anyway.  Make sure to pullup the header so
1397 	 * that other people can't step on it.
1398 	 */
1399 	rte = malloc((sizeof *rte), M_MRTABLE, M_NOWAIT|M_ZERO);
1400 	if (rte == NULL) {
1401 		MRW_WUNLOCK();
1402 		return ENOBUFS;
1403 	}
1404 
1405 	mb0 = m_copypacket(m, M_NOWAIT);
1406 	if (mb0 && (!M_WRITABLE(mb0) || mb0->m_len < hlen))
1407 		mb0 = m_pullup(mb0, hlen);
1408 	if (mb0 == NULL) {
1409 		free(rte, M_MRTABLE);
1410 		MRW_WUNLOCK();
1411 		return ENOBUFS;
1412 	}
1413 
1414 	/* is there an upcall waiting for this flow ? */
1415 	hash = MFCHASH(ip->ip_src, ip->ip_dst);
1416 	LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash)
1417 	{
1418 		if (in_hosteq(ip->ip_src, rt->mfc_origin) &&
1419 		    in_hosteq(ip->ip_dst, rt->mfc_mcastgrp) &&
1420 		    !buf_ring_empty(rt->mfc_stall_ring))
1421 			break;
1422 	}
1423 
1424 	if (rt == NULL) {
1425 		int i;
1426 		struct igmpmsg *im;
1427 		struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1428 		struct mbuf *mm;
1429 
1430 		/*
1431 		 * Locate the vifi for the incoming interface for this packet.
1432 		 * If none found, drop packet.
1433 		 */
1434 		for (vifi = 0; vifi < V_numvifs &&
1435 		    V_viftable[vifi].v_ifp != ifp; vifi++)
1436 			;
1437 		if (vifi >= V_numvifs) /* vif not found, drop packet */
1438 			goto non_fatal;
1439 
1440 		/* no upcall, so make a new entry */
1441 		rt = mfc_alloc();
1442 		if (rt == NULL)
1443 			goto fail;
1444 
1445 		/* Make a copy of the header to send to the user level process */
1446 		mm = m_copym(mb0, 0, hlen, M_NOWAIT);
1447 		if (mm == NULL)
1448 			goto fail1;
1449 
1450 		/*
1451 		 * Send message to routing daemon to install
1452 		 * a route into the kernel table
1453 		 */
1454 
1455 		im = mtod(mm, struct igmpmsg*);
1456 		im->im_msgtype = IGMPMSG_NOCACHE;
1457 		im->im_mbz = 0;
1458 		im->im_vif = vifi;
1459 
1460 		MRTSTAT_INC(mrts_upcalls);
1461 
1462 		k_igmpsrc.sin_addr = ip->ip_src;
1463 		if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1464 			CTR0(KTR_IPMF, "ip_mforward: socket queue full");
1465 			MRTSTAT_INC(mrts_upq_sockfull);
1466 			fail1: free(rt, M_MRTABLE);
1467 			fail: free(rte, M_MRTABLE);
1468 			m_freem(mb0);
1469 			MRW_WUNLOCK();
1470 			return ENOBUFS;
1471 		}
1472 
1473 		/* insert new entry at head of hash chain */
1474 		rt->mfc_origin.s_addr = ip->ip_src.s_addr;
1475 		rt->mfc_mcastgrp.s_addr = ip->ip_dst.s_addr;
1476 		rt->mfc_expire = UPCALL_EXPIRE;
1477 		V_nexpire[hash]++;
1478 		for (i = 0; i < V_numvifs; i++) {
1479 			rt->mfc_ttls[i] = 0;
1480 			rt->mfc_flags[i] = 0;
1481 		}
1482 		rt->mfc_parent = -1;
1483 
1484 		/* clear the RP address */
1485 		rt->mfc_rp.s_addr = INADDR_ANY;
1486 		rt->mfc_bw_meter_leq = NULL;
1487 		rt->mfc_bw_meter_geq = NULL;
1488 
1489 		/* initialize pkt counters per src-grp */
1490 		rt->mfc_pkt_cnt = 0;
1491 		rt->mfc_byte_cnt = 0;
1492 		rt->mfc_wrong_if = 0;
1493 		timevalclear(&rt->mfc_last_assert);
1494 
1495 		buf_ring_enqueue(rt->mfc_stall_ring, rte);
1496 
1497 		/* Add RT to hashtable as it didn't exist before */
1498 		LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1499 	} else {
1500 		/* determine if queue has overflowed */
1501 		if (buf_ring_full(rt->mfc_stall_ring)) {
1502 			MRTSTAT_INC(mrts_upq_ovflw);
1503 			non_fatal: free(rte, M_MRTABLE);
1504 			m_freem(mb0);
1505 			MRW_WUNLOCK();
1506 			return (0);
1507 		}
1508 
1509 		buf_ring_enqueue(rt->mfc_stall_ring, rte);
1510 	}
1511 
1512 	rte->m = mb0;
1513 	rte->ifp = ifp;
1514 
1515 	MRW_WUNLOCK();
1516 
1517 	return 0;
1518 }
1519 
1520 /*
1521  * Clean up the cache entry if upcall is not serviced
1522  */
1523 static void
1524 expire_upcalls(void *arg)
1525 {
1526 	u_long i;
1527 
1528 	CURVNET_SET((struct vnet *) arg);
1529 
1530 	/*This callout is always run with MRW_WLOCK taken. */
1531 
1532 	for (i = 0; i < mfchashsize; i++) {
1533 		struct mfc *rt, *nrt;
1534 
1535 		if (V_nexpire[i] == 0)
1536 			continue;
1537 
1538 		LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
1539 			if (buf_ring_empty(rt->mfc_stall_ring))
1540 				continue;
1541 
1542 			if (rt->mfc_expire == 0 || --rt->mfc_expire > 0)
1543 				continue;
1544 
1545 			MRTSTAT_INC(mrts_cache_cleanups);
1546 			CTR3(KTR_IPMF, "%s: expire (%lx, %lx)", __func__,
1547 			    (u_long)ntohl(rt->mfc_origin.s_addr),
1548 			    (u_long)ntohl(rt->mfc_mcastgrp.s_addr));
1549 
1550 			expire_mfc(rt);
1551 		}
1552 	}
1553 
1554 	callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
1555 	    curvnet);
1556 
1557 	CURVNET_RESTORE();
1558 }
1559 
1560 /*
1561  * Packet forwarding routine once entry in the cache is made
1562  */
1563 static int
1564 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1565 {
1566 	struct ip *ip = mtod(m, struct ip *);
1567 	vifi_t vifi;
1568 	int plen = ntohs(ip->ip_len);
1569 
1570 	MRW_LOCK_ASSERT();
1571 	NET_EPOCH_ASSERT();
1572 
1573 	/*
1574 	 * If xmt_vif is not -1, send on only the requested vif.
1575 	 *
1576 	 * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1577 	 */
1578 	if (xmt_vif < V_numvifs) {
1579 		if (V_viftable[xmt_vif].v_flags & VIFF_REGISTER)
1580 			pim_register_send(ip, V_viftable + xmt_vif, m, rt);
1581 		else
1582 			phyint_send(ip, V_viftable + xmt_vif, m);
1583 		return 1;
1584 	}
1585 
1586 	/*
1587 	 * Don't forward if it didn't arrive from the parent vif for its origin.
1588 	 */
1589 	vifi = rt->mfc_parent;
1590 	if ((vifi >= V_numvifs) || (V_viftable[vifi].v_ifp != ifp)) {
1591 		CTR4(KTR_IPMF, "%s: rx on wrong ifp %p (vifi %d, v_ifp %p)",
1592 				__func__, ifp, (int)vifi, V_viftable[vifi].v_ifp);
1593 		MRTSTAT_INC(mrts_wrong_if);
1594 		++rt->mfc_wrong_if;
1595 		/*
1596 		 * If we are doing PIM assert processing, send a message
1597 		 * to the routing daemon.
1598 		 *
1599 		 * XXX: A PIM-SM router needs the WRONGVIF detection so it
1600 		 * can complete the SPT switch, regardless of the type
1601 		 * of the iif (broadcast media, GRE tunnel, etc).
1602 		 */
1603 		if (V_pim_assert_enabled && (vifi < V_numvifs) &&
1604 		    V_viftable[vifi].v_ifp) {
1605 			if (ifp == V_multicast_register_if)
1606 				PIMSTAT_INC(pims_rcv_registers_wrongiif);
1607 
1608 			/* Get vifi for the incoming packet */
1609 			for (vifi = 0; vifi < V_numvifs && V_viftable[vifi].v_ifp != ifp; vifi++)
1610 				;
1611 			if (vifi >= V_numvifs)
1612 				return 0;	/* The iif is not found: ignore the packet. */
1613 
1614 			if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1615 				return 0;	/* WRONGVIF disabled: ignore the packet */
1616 
1617 			if (ratecheck(&rt->mfc_last_assert, &pim_assert_interval)) {
1618 				struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1619 				struct igmpmsg *im;
1620 				int hlen = ip->ip_hl << 2;
1621 				struct mbuf *mm = m_copym(m, 0, hlen, M_NOWAIT);
1622 
1623 				if (mm && (!M_WRITABLE(mm) || mm->m_len < hlen))
1624 					mm = m_pullup(mm, hlen);
1625 				if (mm == NULL)
1626 					return ENOBUFS;
1627 
1628 				im = mtod(mm, struct igmpmsg *);
1629 				im->im_msgtype = IGMPMSG_WRONGVIF;
1630 				im->im_mbz = 0;
1631 				im->im_vif = vifi;
1632 
1633 				MRTSTAT_INC(mrts_upcalls);
1634 
1635 				k_igmpsrc.sin_addr = im->im_src;
1636 				if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1637 					CTR1(KTR_IPMF, "%s: socket queue full", __func__);
1638 					MRTSTAT_INC(mrts_upq_sockfull);
1639 					return ENOBUFS;
1640 				}
1641 			}
1642 		}
1643 		return 0;
1644 	}
1645 
1646 	/* If I sourced this packet, it counts as output, else it was input. */
1647 	mtx_lock_spin(&V_viftable[vifi].v_spin);
1648 	if (in_hosteq(ip->ip_src, V_viftable[vifi].v_lcl_addr)) {
1649 		V_viftable[vifi].v_pkt_out++;
1650 		V_viftable[vifi].v_bytes_out += plen;
1651 	} else {
1652 		V_viftable[vifi].v_pkt_in++;
1653 		V_viftable[vifi].v_bytes_in += plen;
1654 	}
1655 	mtx_unlock_spin(&V_viftable[vifi].v_spin);
1656 
1657 	rt->mfc_pkt_cnt++;
1658 	rt->mfc_byte_cnt += plen;
1659 
1660 	/*
1661 	 * For each vif, decide if a copy of the packet should be forwarded.
1662 	 * Forward if:
1663 	 *		- the ttl exceeds the vif's threshold
1664 	 *		- there are group members downstream on interface
1665 	 */
1666 	for (vifi = 0; vifi < V_numvifs; vifi++)
1667 		if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1668 			V_viftable[vifi].v_pkt_out++;
1669 			V_viftable[vifi].v_bytes_out += plen;
1670 			if (V_viftable[vifi].v_flags & VIFF_REGISTER)
1671 				pim_register_send(ip, V_viftable + vifi, m, rt);
1672 			else
1673 				phyint_send(ip, V_viftable + vifi, m);
1674 		}
1675 
1676 	/*
1677 	 * Perform upcall-related bw measuring.
1678 	 */
1679 	if ((rt->mfc_bw_meter_geq != NULL) || (rt->mfc_bw_meter_leq != NULL)) {
1680 		struct bw_meter *x;
1681 		struct timeval now;
1682 
1683 		microtime(&now);
1684 		/* Process meters for Greater-or-EQual case */
1685 		for (x = rt->mfc_bw_meter_geq; x != NULL; x = x->bm_mfc_next)
1686 			bw_meter_geq_receive_packet(x, plen, &now);
1687 
1688 		/* Process meters for Lower-or-EQual case */
1689 		for (x = rt->mfc_bw_meter_leq; x != NULL; x = x->bm_mfc_next) {
1690 			/*
1691 			 * Record that a packet is received.
1692 			 * Spin lock has to be taken as callout context
1693 			 * (expire_bw_meter_leq) might modify these fields
1694 			 * as well
1695 			 */
1696 			mtx_lock_spin(&x->bm_spin);
1697 			x->bm_measured.b_packets++;
1698 			x->bm_measured.b_bytes += plen;
1699 			mtx_unlock_spin(&x->bm_spin);
1700 		}
1701 	}
1702 
1703 	return 0;
1704 }
1705 
1706 /*
1707  * Check if a vif number is legal/ok. This is used by in_mcast.c.
1708  */
1709 static int
1710 X_legal_vif_num(int vif)
1711 {
1712 	int ret;
1713 
1714 	ret = 0;
1715 	if (vif < 0)
1716 		return (ret);
1717 
1718 	MRW_RLOCK();
1719 	if (vif < V_numvifs)
1720 		ret = 1;
1721 	MRW_RUNLOCK();
1722 
1723 	return (ret);
1724 }
1725 
1726 /*
1727  * Return the local address used by this vif
1728  */
1729 static u_long
1730 X_ip_mcast_src(int vifi)
1731 {
1732 	in_addr_t addr;
1733 
1734 	addr = INADDR_ANY;
1735 	if (vifi < 0)
1736 		return (addr);
1737 
1738 	MRW_RLOCK();
1739 	if (vifi < V_numvifs)
1740 		addr = V_viftable[vifi].v_lcl_addr.s_addr;
1741 	MRW_RUNLOCK();
1742 
1743 	return (addr);
1744 }
1745 
1746 static void
1747 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1748 {
1749 	struct mbuf *mb_copy;
1750 	int hlen = ip->ip_hl << 2;
1751 
1752 	MRW_LOCK_ASSERT();
1753 
1754 	/*
1755 	 * Make a new reference to the packet; make sure that
1756 	 * the IP header is actually copied, not just referenced,
1757 	 * so that ip_output() only scribbles on the copy.
1758 	 */
1759 	mb_copy = m_copypacket(m, M_NOWAIT);
1760 	if (mb_copy && (!M_WRITABLE(mb_copy) || mb_copy->m_len < hlen))
1761 		mb_copy = m_pullup(mb_copy, hlen);
1762 	if (mb_copy == NULL)
1763 		return;
1764 
1765 	send_packet(vifp, mb_copy);
1766 }
1767 
1768 static void
1769 send_packet(struct vif *vifp, struct mbuf *m)
1770 {
1771 	struct ip_moptions imo;
1772 	int error __unused;
1773 
1774 	MRW_LOCK_ASSERT();
1775 	NET_EPOCH_ASSERT();
1776 
1777 	imo.imo_multicast_ifp  = vifp->v_ifp;
1778 	imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1779 	imo.imo_multicast_loop = !!in_mcast_loop;
1780 	imo.imo_multicast_vif  = -1;
1781 	STAILQ_INIT(&imo.imo_head);
1782 
1783 	/*
1784 	 * Re-entrancy should not be a problem here, because
1785 	 * the packets that we send out and are looped back at us
1786 	 * should get rejected because they appear to come from
1787 	 * the loopback interface, thus preventing looping.
1788 	 */
1789 	error = ip_output(m, NULL, NULL, IP_FORWARDING, &imo, NULL);
1790 	CTR3(KTR_IPMF, "%s: vif %td err %d", __func__,
1791 	    (ptrdiff_t)(vifp - V_viftable), error);
1792 }
1793 
1794 /*
1795  * Stubs for old RSVP socket shim implementation.
1796  */
1797 
1798 static int
1799 X_ip_rsvp_vif(struct socket *so __unused, struct sockopt *sopt __unused)
1800 {
1801 
1802 	return (EOPNOTSUPP);
1803 }
1804 
1805 static void
1806 X_ip_rsvp_force_done(struct socket *so __unused)
1807 {
1808 
1809 }
1810 
1811 static int
1812 X_rsvp_input(struct mbuf **mp, int *offp, int proto)
1813 {
1814 	struct mbuf *m;
1815 
1816 	m = *mp;
1817 	*mp = NULL;
1818 	if (!V_rsvp_on)
1819 		m_freem(m);
1820 	return (IPPROTO_DONE);
1821 }
1822 
1823 /*
1824  * Code for bandwidth monitors
1825  */
1826 
1827 /*
1828  * Define common interface for timeval-related methods
1829  */
1830 #define	BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
1831 #define	BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
1832 #define	BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
1833 
1834 static uint32_t
1835 compute_bw_meter_flags(struct bw_upcall *req)
1836 {
1837 	uint32_t flags = 0;
1838 
1839 	if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
1840 		flags |= BW_METER_UNIT_PACKETS;
1841 	if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
1842 		flags |= BW_METER_UNIT_BYTES;
1843 	if (req->bu_flags & BW_UPCALL_GEQ)
1844 		flags |= BW_METER_GEQ;
1845 	if (req->bu_flags & BW_UPCALL_LEQ)
1846 		flags |= BW_METER_LEQ;
1847 
1848 	return flags;
1849 }
1850 
1851 static void
1852 expire_bw_meter_leq(void *arg)
1853 {
1854 	struct bw_meter *x = arg;
1855 	struct timeval now;
1856 	/*
1857 	 * INFO:
1858 	 * callout is always executed with MRW_WLOCK taken
1859 	 */
1860 
1861 	CURVNET_SET((struct vnet *)x->arg);
1862 
1863 	microtime(&now);
1864 
1865 	/*
1866 	 * Test if we should deliver an upcall
1867 	 */
1868 	if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
1869 	    (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
1870 	    ((x->bm_flags & BW_METER_UNIT_BYTES) &&
1871 	    (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
1872 		/* Prepare an upcall for delivery */
1873 		bw_meter_prepare_upcall(x, &now);
1874 	}
1875 
1876 	/* Send all upcalls that are pending delivery */
1877 	taskqueue_enqueue(V_task_queue, &V_task);
1878 
1879 	/* Reset counters */
1880 	x->bm_start_time = now;
1881 	/* Spin lock has to be taken as ip_forward context
1882 	 * might modify these fields as well
1883 	 */
1884 	mtx_lock_spin(&x->bm_spin);
1885 	x->bm_measured.b_bytes = 0;
1886 	x->bm_measured.b_packets = 0;
1887 	mtx_unlock_spin(&x->bm_spin);
1888 
1889 	callout_schedule(&x->bm_meter_callout, tvtohz(&x->bm_threshold.b_time));
1890 
1891 	CURVNET_RESTORE();
1892 }
1893 
1894 /*
1895  * Add a bw_meter entry
1896  */
1897 static int
1898 add_bw_upcall(struct bw_upcall *req)
1899 {
1900 	struct mfc *mfc;
1901 	struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
1902 	BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
1903 	struct timeval now;
1904 	struct bw_meter *x, **bwm_ptr;
1905 	uint32_t flags;
1906 
1907 	if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
1908 		return EOPNOTSUPP;
1909 
1910 	/* Test if the flags are valid */
1911 	if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
1912 		return EINVAL;
1913 	if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
1914 		return EINVAL;
1915 	if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)) == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
1916 		return EINVAL;
1917 
1918 	/* Test if the threshold time interval is valid */
1919 	if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
1920 		return EINVAL;
1921 
1922 	flags = compute_bw_meter_flags(req);
1923 
1924 	/*
1925 	 * Find if we have already same bw_meter entry
1926 	 */
1927 	MRW_WLOCK();
1928 	mfc = mfc_find(&req->bu_src, &req->bu_dst);
1929 	if (mfc == NULL) {
1930 		MRW_WUNLOCK();
1931 		return EADDRNOTAVAIL;
1932 	}
1933 
1934 	/* Choose an appropriate bw_meter list */
1935 	if (req->bu_flags & BW_UPCALL_GEQ)
1936 		bwm_ptr = &mfc->mfc_bw_meter_geq;
1937 	else
1938 		bwm_ptr = &mfc->mfc_bw_meter_leq;
1939 
1940 	for (x = *bwm_ptr; x != NULL; x = x->bm_mfc_next) {
1941 		if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
1942 		    &req->bu_threshold.b_time, ==))
1943 		    && (x->bm_threshold.b_packets
1944 		    == req->bu_threshold.b_packets)
1945 		    && (x->bm_threshold.b_bytes
1946 		    == req->bu_threshold.b_bytes)
1947 		    && (x->bm_flags & BW_METER_USER_FLAGS)
1948 		    == flags) {
1949 			MRW_WUNLOCK();
1950 			return 0; /* XXX Already installed */
1951 		}
1952 	}
1953 
1954 	/* Allocate the new bw_meter entry */
1955 	x = malloc(sizeof(*x), M_BWMETER, M_ZERO | M_NOWAIT);
1956 	if (x == NULL) {
1957 		MRW_WUNLOCK();
1958 		return ENOBUFS;
1959 	}
1960 
1961 	/* Set the new bw_meter entry */
1962 	x->bm_threshold.b_time = req->bu_threshold.b_time;
1963 	microtime(&now);
1964 	x->bm_start_time = now;
1965 	x->bm_threshold.b_packets = req->bu_threshold.b_packets;
1966 	x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
1967 	x->bm_measured.b_packets = 0;
1968 	x->bm_measured.b_bytes = 0;
1969 	x->bm_flags = flags;
1970 	x->bm_time_next = NULL;
1971 	x->bm_mfc = mfc;
1972 	x->arg = curvnet;
1973 	sprintf(x->bm_spin_name, "BM spin %p", x);
1974 	mtx_init(&x->bm_spin, x->bm_spin_name, NULL, MTX_SPIN);
1975 
1976 	/* For LEQ case create periodic callout */
1977 	if (req->bu_flags & BW_UPCALL_LEQ) {
1978 		callout_init_rw(&x->bm_meter_callout, &mrouter_lock, CALLOUT_SHAREDLOCK);
1979 		callout_reset(&x->bm_meter_callout, tvtohz(&x->bm_threshold.b_time),
1980 		    expire_bw_meter_leq, x);
1981 	}
1982 
1983 	/* Add the new bw_meter entry to the front of entries for this MFC */
1984 	x->bm_mfc_next = *bwm_ptr;
1985 	*bwm_ptr = x;
1986 
1987 	MRW_WUNLOCK();
1988 
1989 	return 0;
1990 }
1991 
1992 static void
1993 free_bw_list(struct bw_meter *list)
1994 {
1995 	while (list != NULL) {
1996 		struct bw_meter *x = list;
1997 
1998 		/* MRW_WLOCK must be held here */
1999 		if (x->bm_flags & BW_METER_LEQ) {
2000 			callout_drain(&x->bm_meter_callout);
2001 			mtx_destroy(&x->bm_spin);
2002 		}
2003 
2004 		list = list->bm_mfc_next;
2005 		free(x, M_BWMETER);
2006 	}
2007 }
2008 
2009 /*
2010  * Delete one or multiple bw_meter entries
2011  */
2012 static int
2013 del_bw_upcall(struct bw_upcall *req)
2014 {
2015 	struct mfc *mfc;
2016 	struct bw_meter *x, **bwm_ptr;
2017 
2018 	if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
2019 		return EOPNOTSUPP;
2020 
2021 	MRW_WLOCK();
2022 
2023 	/* Find the corresponding MFC entry */
2024 	mfc = mfc_find(&req->bu_src, &req->bu_dst);
2025 	if (mfc == NULL) {
2026 		MRW_WUNLOCK();
2027 		return EADDRNOTAVAIL;
2028 	} else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2029 		/*
2030 		 * Delete all bw_meter entries for this mfc
2031 		 */
2032 		struct bw_meter *list;
2033 
2034 		/* Free LEQ list */
2035 		list = mfc->mfc_bw_meter_leq;
2036 		mfc->mfc_bw_meter_leq = NULL;
2037 		free_bw_list(list);
2038 
2039 		/* Free GEQ list */
2040 		list = mfc->mfc_bw_meter_geq;
2041 		mfc->mfc_bw_meter_geq = NULL;
2042 		free_bw_list(list);
2043 		MRW_WUNLOCK();
2044 		return 0;
2045 	} else {			/* Delete a single bw_meter entry */
2046 		struct bw_meter *prev;
2047 		uint32_t flags = 0;
2048 
2049 		flags = compute_bw_meter_flags(req);
2050 
2051 		/* Choose an appropriate bw_meter list */
2052 		if (req->bu_flags & BW_UPCALL_GEQ)
2053 			bwm_ptr = &mfc->mfc_bw_meter_geq;
2054 		else
2055 			bwm_ptr = &mfc->mfc_bw_meter_leq;
2056 
2057 		/* Find the bw_meter entry to delete */
2058 		for (prev = NULL, x = *bwm_ptr; x != NULL;
2059 				prev = x, x = x->bm_mfc_next) {
2060 			if ((BW_TIMEVALCMP(&x->bm_threshold.b_time, &req->bu_threshold.b_time, ==)) &&
2061 			    (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2062 			    (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2063 			    (x->bm_flags & BW_METER_USER_FLAGS) == flags)
2064 				break;
2065 		}
2066 		if (x != NULL) { /* Delete entry from the list for this MFC */
2067 			if (prev != NULL)
2068 				prev->bm_mfc_next = x->bm_mfc_next;	/* remove from middle*/
2069 			else
2070 				*bwm_ptr = x->bm_mfc_next;/* new head of list */
2071 
2072 			if (req->bu_flags & BW_UPCALL_LEQ)
2073 				callout_stop(&x->bm_meter_callout);
2074 
2075 			MRW_WUNLOCK();
2076 			/* Free the bw_meter entry */
2077 			free(x, M_BWMETER);
2078 			return 0;
2079 		} else {
2080 			MRW_WUNLOCK();
2081 			return EINVAL;
2082 		}
2083 	}
2084 	__assert_unreachable();
2085 }
2086 
2087 /*
2088  * Perform bandwidth measurement processing that may result in an upcall
2089  */
2090 static void
2091 bw_meter_geq_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2092 {
2093 	struct timeval delta;
2094 
2095 	MRW_LOCK_ASSERT();
2096 
2097 	delta = *nowp;
2098 	BW_TIMEVALDECR(&delta, &x->bm_start_time);
2099 
2100 	/*
2101 	 * Processing for ">=" type of bw_meter entry.
2102 	 * bm_spin does not have to be hold here as in GEQ
2103 	 * case this is the only context accessing bm_measured.
2104 	 */
2105 	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2106 	    /* Reset the bw_meter entry */
2107 	    x->bm_start_time = *nowp;
2108 	    x->bm_measured.b_packets = 0;
2109 	    x->bm_measured.b_bytes = 0;
2110 	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2111 	}
2112 
2113 	/* Record that a packet is received */
2114 	x->bm_measured.b_packets++;
2115 	x->bm_measured.b_bytes += plen;
2116 
2117 	/*
2118 	 * Test if we should deliver an upcall
2119 	 */
2120 	if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2121 		if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2122 		    (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2123 		    ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2124 		    (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2125 			/* Prepare an upcall for delivery */
2126 			bw_meter_prepare_upcall(x, nowp);
2127 			x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2128 		}
2129 	}
2130 }
2131 
2132 /*
2133  * Prepare a bandwidth-related upcall
2134  */
2135 static void
2136 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2137 {
2138 	struct timeval delta;
2139 	struct bw_upcall *u;
2140 
2141 	MRW_LOCK_ASSERT();
2142 
2143 	/*
2144 	 * Compute the measured time interval
2145 	 */
2146 	delta = *nowp;
2147 	BW_TIMEVALDECR(&delta, &x->bm_start_time);
2148 
2149 	/*
2150 	 * Set the bw_upcall entry
2151 	 */
2152 	u = malloc(sizeof(struct bw_upcall), M_MRTABLE, M_NOWAIT | M_ZERO);
2153 	if (!u) {
2154 		log(LOG_WARNING, "bw_meter_prepare_upcall: cannot allocate entry\n");
2155 		return;
2156 	}
2157 	u->bu_src = x->bm_mfc->mfc_origin;
2158 	u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2159 	u->bu_threshold.b_time = x->bm_threshold.b_time;
2160 	u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2161 	u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2162 	u->bu_measured.b_time = delta;
2163 	u->bu_measured.b_packets = x->bm_measured.b_packets;
2164 	u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2165 	u->bu_flags = 0;
2166 	if (x->bm_flags & BW_METER_UNIT_PACKETS)
2167 		u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2168 	if (x->bm_flags & BW_METER_UNIT_BYTES)
2169 		u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2170 	if (x->bm_flags & BW_METER_GEQ)
2171 		u->bu_flags |= BW_UPCALL_GEQ;
2172 	if (x->bm_flags & BW_METER_LEQ)
2173 		u->bu_flags |= BW_UPCALL_LEQ;
2174 
2175 	if (buf_ring_enqueue(V_bw_upcalls_ring, u))
2176 		log(LOG_WARNING, "bw_meter_prepare_upcall: cannot enqueue upcall\n");
2177 	if (buf_ring_count(V_bw_upcalls_ring) > (BW_UPCALLS_MAX / 2)) {
2178 		taskqueue_enqueue(V_task_queue, &V_task);
2179 	}
2180 }
2181 /*
2182  * Send the pending bandwidth-related upcalls
2183  */
2184 static void
2185 bw_upcalls_send(void)
2186 {
2187 	struct mbuf *m;
2188 	int len = 0;
2189 	struct bw_upcall *bu;
2190 	struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2191 	static struct igmpmsg igmpmsg = {
2192 		0,		/* unused1 */
2193 		0,		/* unused2 */
2194 		IGMPMSG_BW_UPCALL,/* im_msgtype */
2195 		0,		/* im_mbz  */
2196 		0,		/* im_vif  */
2197 		0,		/* unused3 */
2198 		{ 0 },		/* im_src  */
2199 		{ 0 }		/* im_dst  */
2200 	};
2201 
2202 	MRW_LOCK_ASSERT();
2203 
2204 	if (buf_ring_empty(V_bw_upcalls_ring))
2205 		return;
2206 
2207 	/*
2208 	 * Allocate a new mbuf, initialize it with the header and
2209 	 * the payload for the pending calls.
2210 	 */
2211 	m = m_gethdr(M_NOWAIT, MT_DATA);
2212 	if (m == NULL) {
2213 		log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2214 		return;
2215 	}
2216 
2217 	m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2218 	len += sizeof(struct igmpmsg);
2219 	while ((bu = buf_ring_dequeue_mc(V_bw_upcalls_ring)) != NULL) {
2220 		m_copyback(m, len, sizeof(struct bw_upcall), (caddr_t)bu);
2221 		len += sizeof(struct bw_upcall);
2222 		free(bu, M_MRTABLE);
2223 	}
2224 
2225 	/*
2226 	 * Send the upcalls
2227 	 * XXX do we need to set the address in k_igmpsrc ?
2228 	 */
2229 	MRTSTAT_INC(mrts_upcalls);
2230 	if (socket_send(V_ip_mrouter, m, &k_igmpsrc) < 0) {
2231 		log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2232 		MRTSTAT_INC(mrts_upq_sockfull);
2233 	}
2234 }
2235 
2236 /*
2237  * A periodic function for sending all upcalls that are pending delivery
2238  */
2239 static void
2240 expire_bw_upcalls_send(void *arg)
2241 {
2242 	CURVNET_SET((struct vnet *) arg);
2243 
2244 	/* This callout is run with MRW_RLOCK taken */
2245 
2246 	bw_upcalls_send();
2247 
2248 	callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
2249 	    curvnet);
2250 	CURVNET_RESTORE();
2251 }
2252 
2253 /*
2254  * End of bandwidth monitoring code
2255  */
2256 
2257 /*
2258  * Send the packet up to the user daemon, or eventually do kernel encapsulation
2259  *
2260  */
2261 static int
2262 pim_register_send(struct ip *ip, struct vif *vifp, struct mbuf *m,
2263     struct mfc *rt)
2264 {
2265 	struct mbuf *mb_copy, *mm;
2266 
2267 	/*
2268 	 * Do not send IGMP_WHOLEPKT notifications to userland, if the
2269 	 * rendezvous point was unspecified, and we were told not to.
2270 	 */
2271 	if (pim_squelch_wholepkt != 0 && (V_mrt_api_config & MRT_MFC_RP) &&
2272 	    in_nullhost(rt->mfc_rp))
2273 		return 0;
2274 
2275 	mb_copy = pim_register_prepare(ip, m);
2276 	if (mb_copy == NULL)
2277 		return ENOBUFS;
2278 
2279 	/*
2280 	 * Send all the fragments. Note that the mbuf for each fragment
2281 	 * is freed by the sending machinery.
2282 	 */
2283 	for (mm = mb_copy; mm; mm = mb_copy) {
2284 		mb_copy = mm->m_nextpkt;
2285 		mm->m_nextpkt = 0;
2286 		mm = m_pullup(mm, sizeof(struct ip));
2287 		if (mm != NULL) {
2288 			ip = mtod(mm, struct ip *);
2289 			if ((V_mrt_api_config & MRT_MFC_RP) && !in_nullhost(rt->mfc_rp)) {
2290 				pim_register_send_rp(ip, vifp, mm, rt);
2291 			} else {
2292 				pim_register_send_upcall(ip, vifp, mm, rt);
2293 			}
2294 		}
2295 	}
2296 
2297 	return 0;
2298 }
2299 
2300 /*
2301  * Return a copy of the data packet that is ready for PIM Register
2302  * encapsulation.
2303  * XXX: Note that in the returned copy the IP header is a valid one.
2304  */
2305 static struct mbuf *
2306 pim_register_prepare(struct ip *ip, struct mbuf *m)
2307 {
2308 	struct mbuf *mb_copy = NULL;
2309 	int mtu;
2310 
2311 	/* Take care of delayed checksums */
2312 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2313 		in_delayed_cksum(m);
2314 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2315 	}
2316 
2317 	/*
2318 	 * Copy the old packet & pullup its IP header into the
2319 	 * new mbuf so we can modify it.
2320 	 */
2321 	mb_copy = m_copypacket(m, M_NOWAIT);
2322 	if (mb_copy == NULL)
2323 		return NULL;
2324 	mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2325 	if (mb_copy == NULL)
2326 		return NULL;
2327 
2328 	/* take care of the TTL */
2329 	ip = mtod(mb_copy, struct ip *);
2330 	--ip->ip_ttl;
2331 
2332 	/* Compute the MTU after the PIM Register encapsulation */
2333 	mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2334 
2335 	if (ntohs(ip->ip_len) <= mtu) {
2336 		/* Turn the IP header into a valid one */
2337 		ip->ip_sum = 0;
2338 		ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2339 	} else {
2340 		/* Fragment the packet */
2341 		mb_copy->m_pkthdr.csum_flags |= CSUM_IP;
2342 		if (ip_fragment(ip, &mb_copy, mtu, 0) != 0) {
2343 			m_freem(mb_copy);
2344 			return NULL;
2345 		}
2346 	}
2347 	return mb_copy;
2348 }
2349 
2350 /*
2351  * Send an upcall with the data packet to the user-level process.
2352  */
2353 static int
2354 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2355     struct mbuf *mb_copy, struct mfc *rt)
2356 {
2357 	struct mbuf *mb_first;
2358 	int len = ntohs(ip->ip_len);
2359 	struct igmpmsg *im;
2360 	struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2361 
2362 	MRW_LOCK_ASSERT();
2363 
2364 	/*
2365 	 * Add a new mbuf with an upcall header
2366 	 */
2367 	mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2368 	if (mb_first == NULL) {
2369 		m_freem(mb_copy);
2370 		return ENOBUFS;
2371 	}
2372 	mb_first->m_data += max_linkhdr;
2373 	mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2374 	mb_first->m_len = sizeof(struct igmpmsg);
2375 	mb_first->m_next = mb_copy;
2376 
2377 	/* Send message to routing daemon */
2378 	im = mtod(mb_first, struct igmpmsg *);
2379 	im->im_msgtype	= IGMPMSG_WHOLEPKT;
2380 	im->im_mbz		= 0;
2381 	im->im_vif		= vifp - V_viftable;
2382 	im->im_src		= ip->ip_src;
2383 	im->im_dst		= ip->ip_dst;
2384 
2385 	k_igmpsrc.sin_addr	= ip->ip_src;
2386 
2387 	MRTSTAT_INC(mrts_upcalls);
2388 
2389 	if (socket_send(V_ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2390 		CTR1(KTR_IPMF, "%s: socket queue full", __func__);
2391 		MRTSTAT_INC(mrts_upq_sockfull);
2392 		return ENOBUFS;
2393 	}
2394 
2395 	/* Keep statistics */
2396 	PIMSTAT_INC(pims_snd_registers_msgs);
2397 	PIMSTAT_ADD(pims_snd_registers_bytes, len);
2398 
2399 	return 0;
2400 }
2401 
2402 /*
2403  * Encapsulate the data packet in PIM Register message and send it to the RP.
2404  */
2405 static int
2406 pim_register_send_rp(struct ip *ip, struct vif *vifp, struct mbuf *mb_copy,
2407     struct mfc *rt)
2408 {
2409 	struct mbuf *mb_first;
2410 	struct ip *ip_outer;
2411 	struct pim_encap_pimhdr *pimhdr;
2412 	int len = ntohs(ip->ip_len);
2413 	vifi_t vifi = rt->mfc_parent;
2414 
2415 	MRW_LOCK_ASSERT();
2416 
2417 	if ((vifi >= V_numvifs) || in_nullhost(V_viftable[vifi].v_lcl_addr)) {
2418 		m_freem(mb_copy);
2419 		return EADDRNOTAVAIL;		/* The iif vif is invalid */
2420 	}
2421 
2422 	/*
2423 	 * Add a new mbuf with the encapsulating header
2424 	 */
2425 	mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2426 	if (mb_first == NULL) {
2427 		m_freem(mb_copy);
2428 		return ENOBUFS;
2429 	}
2430 	mb_first->m_data += max_linkhdr;
2431 	mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2432 	mb_first->m_next = mb_copy;
2433 
2434 	mb_first->m_pkthdr.len = len + mb_first->m_len;
2435 
2436 	/*
2437 	 * Fill in the encapsulating IP and PIM header
2438 	 */
2439 	ip_outer = mtod(mb_first, struct ip *);
2440 	*ip_outer = pim_encap_iphdr;
2441 	ip_outer->ip_len = htons(len + sizeof(pim_encap_iphdr) +
2442 			sizeof(pim_encap_pimhdr));
2443 	ip_outer->ip_src = V_viftable[vifi].v_lcl_addr;
2444 	ip_outer->ip_dst = rt->mfc_rp;
2445 	/*
2446 	 * Copy the inner header TOS to the outer header, and take care of the
2447 	 * IP_DF bit.
2448 	 */
2449 	ip_outer->ip_tos = ip->ip_tos;
2450 	if (ip->ip_off & htons(IP_DF))
2451 		ip_outer->ip_off |= htons(IP_DF);
2452 	ip_fillid(ip_outer);
2453 	pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2454 			+ sizeof(pim_encap_iphdr));
2455 	*pimhdr = pim_encap_pimhdr;
2456 	/* If the iif crosses a border, set the Border-bit */
2457 	if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & V_mrt_api_config)
2458 		pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
2459 
2460 	mb_first->m_data += sizeof(pim_encap_iphdr);
2461 	pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
2462 	mb_first->m_data -= sizeof(pim_encap_iphdr);
2463 
2464 	send_packet(vifp, mb_first);
2465 
2466 	/* Keep statistics */
2467 	PIMSTAT_INC(pims_snd_registers_msgs);
2468 	PIMSTAT_ADD(pims_snd_registers_bytes, len);
2469 
2470 	return 0;
2471 }
2472 
2473 /*
2474  * pim_encapcheck() is called by the encap4_input() path at runtime to
2475  * determine if a packet is for PIM; allowing PIM to be dynamically loaded
2476  * into the kernel.
2477  */
2478 static int
2479 pim_encapcheck(const struct mbuf *m __unused, int off __unused,
2480     int proto __unused, void *arg __unused)
2481 {
2482 
2483 	KASSERT(proto == IPPROTO_PIM, ("not for IPPROTO_PIM"));
2484 	return (8);		/* claim the datagram. */
2485 }
2486 
2487 /*
2488  * PIM-SMv2 and PIM-DM messages processing.
2489  * Receives and verifies the PIM control messages, and passes them
2490  * up to the listening socket, using rip_input().
2491  * The only message with special processing is the PIM_REGISTER message
2492  * (used by PIM-SM): the PIM header is stripped off, and the inner packet
2493  * is passed to if_simloop().
2494  */
2495 static int
2496 pim_input(struct mbuf *m, int off, int proto, void *arg __unused)
2497 {
2498 	struct ip *ip = mtod(m, struct ip *);
2499 	struct pim *pim;
2500 	int iphlen = off;
2501 	int minlen;
2502 	int datalen = ntohs(ip->ip_len) - iphlen;
2503 	int ip_tos;
2504 
2505 	/* Keep statistics */
2506 	PIMSTAT_INC(pims_rcv_total_msgs);
2507 	PIMSTAT_ADD(pims_rcv_total_bytes, datalen);
2508 
2509 	/*
2510 	 * Validate lengths
2511 	 */
2512 	if (datalen < PIM_MINLEN) {
2513 		PIMSTAT_INC(pims_rcv_tooshort);
2514 		CTR3(KTR_IPMF, "%s: short packet (%d) from 0x%08x",
2515 		    __func__, datalen, ntohl(ip->ip_src.s_addr));
2516 		m_freem(m);
2517 		return (IPPROTO_DONE);
2518 	}
2519 
2520 	/*
2521 	 * If the packet is at least as big as a REGISTER, go agead
2522 	 * and grab the PIM REGISTER header size, to avoid another
2523 	 * possible m_pullup() later.
2524 	 *
2525 	 * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
2526 	 * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
2527 	 */
2528 	minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
2529 	/*
2530 	 * Get the IP and PIM headers in contiguous memory, and
2531 	 * possibly the PIM REGISTER header.
2532 	 */
2533 	if (m->m_len < minlen && (m = m_pullup(m, minlen)) == NULL) {
2534 		CTR1(KTR_IPMF, "%s: m_pullup() failed", __func__);
2535 		return (IPPROTO_DONE);
2536 	}
2537 
2538 	/* m_pullup() may have given us a new mbuf so reset ip. */
2539 	ip = mtod(m, struct ip *);
2540 	ip_tos = ip->ip_tos;
2541 
2542 	/* adjust mbuf to point to the PIM header */
2543 	m->m_data += iphlen;
2544 	m->m_len  -= iphlen;
2545 	pim = mtod(m, struct pim *);
2546 
2547 	/*
2548 	 * Validate checksum. If PIM REGISTER, exclude the data packet.
2549 	 *
2550 	 * XXX: some older PIMv2 implementations don't make this distinction,
2551 	 * so for compatibility reason perform the checksum over part of the
2552 	 * message, and if error, then over the whole message.
2553 	 */
2554 	if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
2555 		/* do nothing, checksum okay */
2556 	} else if (in_cksum(m, datalen)) {
2557 		PIMSTAT_INC(pims_rcv_badsum);
2558 		CTR1(KTR_IPMF, "%s: invalid checksum", __func__);
2559 		m_freem(m);
2560 		return (IPPROTO_DONE);
2561 	}
2562 
2563 	/* PIM version check */
2564 	if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
2565 		PIMSTAT_INC(pims_rcv_badversion);
2566 		CTR3(KTR_IPMF, "%s: bad version %d expect %d", __func__,
2567 		    (int)PIM_VT_V(pim->pim_vt), PIM_VERSION);
2568 		m_freem(m);
2569 		return (IPPROTO_DONE);
2570 	}
2571 
2572 	/* restore mbuf back to the outer IP */
2573 	m->m_data -= iphlen;
2574 	m->m_len  += iphlen;
2575 
2576 	if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
2577 		/*
2578 		 * Since this is a REGISTER, we'll make a copy of the register
2579 		 * headers ip + pim + u_int32 + encap_ip, to be passed up to the
2580 		 * routing daemon.
2581 		 */
2582 		struct sockaddr_in dst = { sizeof(dst), AF_INET };
2583 		struct mbuf *mcp;
2584 		struct ip *encap_ip;
2585 		u_int32_t *reghdr;
2586 		struct ifnet *vifp;
2587 
2588 		MRW_RLOCK();
2589 		if ((V_reg_vif_num >= V_numvifs) || (V_reg_vif_num == VIFI_INVALID)) {
2590 			MRW_RUNLOCK();
2591 			CTR2(KTR_IPMF, "%s: register vif not set: %d", __func__,
2592 			    (int)V_reg_vif_num);
2593 			m_freem(m);
2594 			return (IPPROTO_DONE);
2595 		}
2596 		/* XXX need refcnt? */
2597 		vifp = V_viftable[V_reg_vif_num].v_ifp;
2598 		MRW_RUNLOCK();
2599 
2600 		/*
2601 		 * Validate length
2602 		 */
2603 		if (datalen < PIM_REG_MINLEN) {
2604 			PIMSTAT_INC(pims_rcv_tooshort);
2605 			PIMSTAT_INC(pims_rcv_badregisters);
2606 			CTR1(KTR_IPMF, "%s: register packet size too small", __func__);
2607 			m_freem(m);
2608 			return (IPPROTO_DONE);
2609 		}
2610 
2611 		reghdr = (u_int32_t *)(pim + 1);
2612 		encap_ip = (struct ip *)(reghdr + 1);
2613 
2614 		CTR3(KTR_IPMF, "%s: register: encap ip src 0x%08x len %d",
2615 		    __func__, ntohl(encap_ip->ip_src.s_addr),
2616 		    ntohs(encap_ip->ip_len));
2617 
2618 		/* verify the version number of the inner packet */
2619 		if (encap_ip->ip_v != IPVERSION) {
2620 			PIMSTAT_INC(pims_rcv_badregisters);
2621 			CTR1(KTR_IPMF, "%s: bad encap ip version", __func__);
2622 			m_freem(m);
2623 			return (IPPROTO_DONE);
2624 		}
2625 
2626 		/* verify the inner packet is destined to a mcast group */
2627 		if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
2628 			PIMSTAT_INC(pims_rcv_badregisters);
2629 			CTR2(KTR_IPMF, "%s: bad encap ip dest 0x%08x", __func__,
2630 			    ntohl(encap_ip->ip_dst.s_addr));
2631 			m_freem(m);
2632 			return (IPPROTO_DONE);
2633 		}
2634 
2635 		/* If a NULL_REGISTER, pass it to the daemon */
2636 		if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
2637 			goto pim_input_to_daemon;
2638 
2639 		/*
2640 		 * Copy the TOS from the outer IP header to the inner IP header.
2641 		 */
2642 		if (encap_ip->ip_tos != ip_tos) {
2643 			/* Outer TOS -> inner TOS */
2644 			encap_ip->ip_tos = ip_tos;
2645 			/* Recompute the inner header checksum. Sigh... */
2646 
2647 			/* adjust mbuf to point to the inner IP header */
2648 			m->m_data += (iphlen + PIM_MINLEN);
2649 			m->m_len  -= (iphlen + PIM_MINLEN);
2650 
2651 			encap_ip->ip_sum = 0;
2652 			encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
2653 
2654 			/* restore mbuf to point back to the outer IP header */
2655 			m->m_data -= (iphlen + PIM_MINLEN);
2656 			m->m_len  += (iphlen + PIM_MINLEN);
2657 		}
2658 
2659 		/*
2660 		 * Decapsulate the inner IP packet and loopback to forward it
2661 		 * as a normal multicast packet. Also, make a copy of the
2662 		 *     outer_iphdr + pimhdr + reghdr + encap_iphdr
2663 		 * to pass to the daemon later, so it can take the appropriate
2664 		 * actions (e.g., send back PIM_REGISTER_STOP).
2665 		 * XXX: here m->m_data points to the outer IP header.
2666 		 */
2667 		mcp = m_copym(m, 0, iphlen + PIM_REG_MINLEN, M_NOWAIT);
2668 		if (mcp == NULL) {
2669 			CTR1(KTR_IPMF, "%s: m_copym() failed", __func__);
2670 			m_freem(m);
2671 			return (IPPROTO_DONE);
2672 		}
2673 
2674 		/* Keep statistics */
2675 		/* XXX: registers_bytes include only the encap. mcast pkt */
2676 		PIMSTAT_INC(pims_rcv_registers_msgs);
2677 		PIMSTAT_ADD(pims_rcv_registers_bytes, ntohs(encap_ip->ip_len));
2678 
2679 		/*
2680 		 * forward the inner ip packet; point m_data at the inner ip.
2681 		 */
2682 		m_adj(m, iphlen + PIM_MINLEN);
2683 
2684 		CTR4(KTR_IPMF,
2685 		    "%s: forward decap'd REGISTER: src %lx dst %lx vif %d",
2686 		    __func__,
2687 		    (u_long)ntohl(encap_ip->ip_src.s_addr),
2688 		    (u_long)ntohl(encap_ip->ip_dst.s_addr),
2689 		    (int)V_reg_vif_num);
2690 
2691 		/* NB: vifp was collected above; can it change on us? */
2692 		if_simloop(vifp, m, dst.sin_family, 0);
2693 
2694 		/* prepare the register head to send to the mrouting daemon */
2695 		m = mcp;
2696 	}
2697 
2698 pim_input_to_daemon:
2699 	/*
2700 	 * Pass the PIM message up to the daemon; if it is a Register message,
2701 	 * pass the 'head' only up to the daemon. This includes the
2702 	 * outer IP header, PIM header, PIM-Register header and the
2703 	 * inner IP header.
2704 	 * XXX: the outer IP header pkt size of a Register is not adjust to
2705 	 * reflect the fact that the inner multicast data is truncated.
2706 	 */
2707 	return (rip_input(&m, &off, proto));
2708 }
2709 
2710 static int
2711 sysctl_mfctable(SYSCTL_HANDLER_ARGS)
2712 {
2713 	struct mfc	*rt;
2714 	int		 error, i;
2715 
2716 	if (req->newptr)
2717 		return (EPERM);
2718 	if (V_mfchashtbl == NULL)	/* XXX unlocked */
2719 		return (0);
2720 	error = sysctl_wire_old_buffer(req, 0);
2721 	if (error)
2722 		return (error);
2723 
2724 	MRW_RLOCK();
2725 	for (i = 0; i < mfchashsize; i++) {
2726 		LIST_FOREACH(rt, &V_mfchashtbl[i], mfc_hash) {
2727 			error = SYSCTL_OUT(req, rt, sizeof(struct mfc));
2728 			if (error)
2729 				goto out_locked;
2730 		}
2731 	}
2732 out_locked:
2733 	MRW_RUNLOCK();
2734 	return (error);
2735 }
2736 
2737 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, mfctable,
2738     CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_mfctable,
2739     "IPv4 Multicast Forwarding Table "
2740     "(struct *mfc[mfchashsize], netinet/ip_mroute.h)");
2741 
2742 static int
2743 sysctl_viflist(SYSCTL_HANDLER_ARGS)
2744 {
2745 	int error, i;
2746 
2747 	if (req->newptr)
2748 		return (EPERM);
2749 	if (V_viftable == NULL)		/* XXX unlocked */
2750 		return (0);
2751 	error = sysctl_wire_old_buffer(req, MROUTE_VIF_SYSCTL_LEN * MAXVIFS);
2752 	if (error)
2753 		return (error);
2754 
2755 	MRW_RLOCK();
2756 	/* Copy out user-visible portion of vif entry. */
2757 	for (i = 0; i < MAXVIFS; i++) {
2758 		error = SYSCTL_OUT(req, &V_viftable[i], MROUTE_VIF_SYSCTL_LEN);
2759 		if (error)
2760 			break;
2761 	}
2762 	MRW_RUNLOCK();
2763 	return (error);
2764 }
2765 
2766 SYSCTL_PROC(_net_inet_ip, OID_AUTO, viftable,
2767     CTLTYPE_OPAQUE | CTLFLAG_VNET | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2768     sysctl_viflist, "S,vif[MAXVIFS]",
2769     "IPv4 Multicast Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
2770 
2771 static void
2772 vnet_mroute_init(const void *unused __unused)
2773 {
2774 
2775 	V_nexpire = malloc(mfchashsize, M_MRTABLE, M_WAITOK|M_ZERO);
2776 
2777 	V_viftable = mallocarray(MAXVIFS, sizeof(*V_viftable),
2778 	    M_MRTABLE, M_WAITOK|M_ZERO);
2779 
2780 	callout_init_rw(&V_expire_upcalls_ch, &mrouter_lock, 0);
2781 	callout_init_rw(&V_bw_upcalls_ch, &mrouter_lock, 0);
2782 
2783 	/* Prepare taskqueue */
2784 	V_task_queue = taskqueue_create_fast("ip_mroute_tskq", M_NOWAIT,
2785 		    taskqueue_thread_enqueue, &V_task_queue);
2786 	taskqueue_start_threads(&V_task_queue, 1, PI_NET, "ip_mroute_tskq task");
2787 }
2788 
2789 VNET_SYSINIT(vnet_mroute_init, SI_SUB_PROTO_MC, SI_ORDER_ANY, vnet_mroute_init,
2790 	NULL);
2791 
2792 static void
2793 vnet_mroute_uninit(const void *unused __unused)
2794 {
2795 
2796 	/* Taskqueue should be cancelled and drained before freeing */
2797 	taskqueue_free(V_task_queue);
2798 
2799 	free(V_viftable, M_MRTABLE);
2800 	free(V_nexpire, M_MRTABLE);
2801 	V_nexpire = NULL;
2802 }
2803 
2804 VNET_SYSUNINIT(vnet_mroute_uninit, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE,
2805     vnet_mroute_uninit, NULL);
2806 
2807 static int
2808 ip_mroute_modevent(module_t mod, int type, void *unused)
2809 {
2810 
2811 	switch (type) {
2812 	case MOD_LOAD:
2813 		MRW_LOCK_INIT();
2814 
2815 		if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
2816 		    if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
2817 		if (if_detach_event_tag == NULL) {
2818 			printf("ip_mroute: unable to register "
2819 					"ifnet_departure_event handler\n");
2820 			MRW_LOCK_DESTROY();
2821 			return (EINVAL);
2822 		}
2823 
2824 		if (!powerof2(mfchashsize)) {
2825 			printf("WARNING: %s not a power of 2; using default\n",
2826 					"net.inet.ip.mfchashsize");
2827 			mfchashsize = MFCHASHSIZE;
2828 		}
2829 
2830 		pim_encap_cookie = ip_encap_attach(&ipv4_encap_cfg, NULL, M_WAITOK);
2831 
2832 		ip_mcast_src = X_ip_mcast_src;
2833 		ip_mforward = X_ip_mforward;
2834 		ip_mrouter_done = X_ip_mrouter_done;
2835 		ip_mrouter_get = X_ip_mrouter_get;
2836 		ip_mrouter_set = X_ip_mrouter_set;
2837 
2838 		ip_rsvp_force_done = X_ip_rsvp_force_done;
2839 		ip_rsvp_vif = X_ip_rsvp_vif;
2840 
2841 		legal_vif_num = X_legal_vif_num;
2842 		mrt_ioctl = X_mrt_ioctl;
2843 		rsvp_input_p = X_rsvp_input;
2844 		break;
2845 
2846 	case MOD_UNLOAD:
2847 		/*
2848 		 * Typically module unload happens after the user-level
2849 		 * process has shutdown the kernel services (the check
2850 		 * below insures someone can't just yank the module out
2851 		 * from under a running process).  But if the module is
2852 		 * just loaded and then unloaded w/o starting up a user
2853 		 * process we still need to cleanup.
2854 		 */
2855 		MRW_WLOCK();
2856 		if (ip_mrouter_cnt != 0) {
2857 			MRW_WUNLOCK();
2858 			return (EINVAL);
2859 		}
2860 		ip_mrouter_unloading = 1;
2861 		MRW_WUNLOCK();
2862 
2863 		EVENTHANDLER_DEREGISTER(ifnet_departure_event, if_detach_event_tag);
2864 
2865 		if (pim_encap_cookie) {
2866 			ip_encap_detach(pim_encap_cookie);
2867 			pim_encap_cookie = NULL;
2868 		}
2869 
2870 		ip_mcast_src = NULL;
2871 		ip_mforward = NULL;
2872 		ip_mrouter_done = NULL;
2873 		ip_mrouter_get = NULL;
2874 		ip_mrouter_set = NULL;
2875 
2876 		ip_rsvp_force_done = NULL;
2877 		ip_rsvp_vif = NULL;
2878 
2879 		legal_vif_num = NULL;
2880 		mrt_ioctl = NULL;
2881 		rsvp_input_p = NULL;
2882 
2883 		MRW_LOCK_DESTROY();
2884 		break;
2885 
2886 	default:
2887 		return EOPNOTSUPP;
2888 	}
2889 	return 0;
2890 }
2891 
2892 static moduledata_t ip_mroutemod = {
2893 	"ip_mroute",
2894 	ip_mroute_modevent,
2895 	0
2896 };
2897 
2898 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);
2899