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