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