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