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