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