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