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