ip_mroute.c revision 121446
1/*
2 * IP multicast forwarding procedures
3 *
4 * Written by David Waitzman, BBN Labs, August 1988.
5 * Modified by Steve Deering, Stanford, February 1989.
6 * Modified by Mark J. Steiglitz, Stanford, May, 1991
7 * Modified by Van Jacobson, LBL, January 1993
8 * Modified by Ajit Thyagarajan, PARC, August 1993
9 * Modified by Bill Fenner, PARC, April 1995
10 * Modified by Ahmed Helmy, SGI, June 1996
11 * Modified by George Edmond Eddy (Rusty), ISI, February 1998
12 * Modified by Pavlin Radoslavov, USC/ISI, May 1998, August 1999, October 2000
13 * Modified by Hitoshi Asaeda, WIDE, August 2000
14 * Modified by Pavlin Radoslavov, ICSI, October 2002
15 *
16 * MROUTING Revision: 3.5
17 * and PIM-SMv2 and PIM-DM support, advanced API support,
18 * bandwidth metering and signaling
19 *
20 * $FreeBSD: head/sys/netinet/ip_mroute.c 121446 2003-10-24 00:09:18Z sam $
21 */
22
23#include "opt_mac.h"
24#include "opt_mrouting.h"
25#include "opt_random_ip_id.h"
26
27#ifdef PIM
28#define _PIM_VT 1
29#endif
30
31#include <sys/param.h>
32#include <sys/kernel.h>
33#include <sys/lock.h>
34#include <sys/mac.h>
35#include <sys/malloc.h>
36#include <sys/mbuf.h>
37#include <sys/protosw.h>
38#include <sys/signalvar.h>
39#include <sys/socket.h>
40#include <sys/socketvar.h>
41#include <sys/sockio.h>
42#include <sys/sx.h>
43#include <sys/sysctl.h>
44#include <sys/syslog.h>
45#include <sys/systm.h>
46#include <sys/time.h>
47#include <net/if.h>
48#include <net/netisr.h>
49#include <net/route.h>
50#include <netinet/in.h>
51#include <netinet/igmp.h>
52#include <netinet/in_systm.h>
53#include <netinet/in_var.h>
54#include <netinet/ip.h>
55#include <netinet/ip_encap.h>
56#include <netinet/ip_mroute.h>
57#include <netinet/ip_var.h>
58#ifdef PIM
59#include <netinet/pim.h>
60#include <netinet/pim_var.h>
61#endif
62#include <netinet/udp.h>
63#include <machine/in_cksum.h>
64
65/*
66 * Control debugging code for rsvp and multicast routing code.
67 * Can only set them with the debugger.
68 */
69static u_int    rsvpdebug;		/* non-zero enables debugging	*/
70
71static u_int	mrtdebug;		/* any set of the flags below	*/
72#define		DEBUG_MFC	0x02
73#define		DEBUG_FORWARD	0x04
74#define		DEBUG_EXPIRE	0x08
75#define		DEBUG_XMIT	0x10
76#define		DEBUG_PIM	0x20
77
78#define		VIFI_INVALID	((vifi_t) -1)
79
80#define M_HASCL(m)	((m)->m_flags & M_EXT)
81
82static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast routing tables");
83
84/*
85 * Locking.  We use two locks: one for the virtual interface table and
86 * one for the forwarding table.  These locks may be nested in which case
87 * the VIF lock must always be taken first.  Note that each lock is used
88 * to cover not only the specific data structure but also related data
89 * structures.  It may be better to add more fine-grained locking later;
90 * it's not clear how performance-critical this code is.
91 */
92
93static struct mrtstat	mrtstat;
94SYSCTL_STRUCT(_net_inet_ip, OID_AUTO, mrtstat, CTLFLAG_RW,
95    &mrtstat, mrtstat,
96    "Multicast Routing Statistics (struct mrtstat, netinet/ip_mroute.h)");
97
98static struct mfc	*mfctable[MFCTBLSIZ];
99SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, mfctable, CTLFLAG_RD,
100    &mfctable, sizeof(mfctable), "S,*mfc[MFCTBLSIZ]",
101    "Multicast Forwarding Table (struct *mfc[MFCTBLSIZ], netinet/ip_mroute.h)");
102
103static struct mtx mfc_mtx;
104#define	MFC_LOCK()	mtx_lock(&mfc_mtx)
105#define	MFC_UNLOCK()	mtx_unlock(&mfc_mtx)
106#define	MFC_LOCK_ASSERT()	mtx_assert(&mfc_mtx, MA_OWNED)
107#define	MFC_LOCK_INIT()	mtx_init(&mfc_mtx, "mroute mfc table", NULL, MTX_DEF)
108#define	MFC_LOCK_DESTROY()	mtx_destroy(&mfc_mtx)
109
110static struct vif	viftable[MAXVIFS];
111SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, viftable, CTLFLAG_RD,
112    &viftable, sizeof(viftable), "S,vif[MAXVIFS]",
113    "Multicast Virtual Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
114
115static struct mtx vif_mtx;
116#define	VIF_LOCK()	mtx_lock(&vif_mtx)
117#define	VIF_UNLOCK()	mtx_unlock(&vif_mtx)
118#define	VIF_LOCK_ASSERT()	mtx_assert(&vif_mtx, MA_OWNED)
119#define	VIF_LOCK_INIT()	mtx_init(&vif_mtx, "mroute vif table", NULL, MTX_DEF)
120#define	VIF_LOCK_DESTROY()	mtx_destroy(&vif_mtx)
121
122static u_char		nexpire[MFCTBLSIZ];
123
124static struct callout expire_upcalls_ch;
125
126#define		EXPIRE_TIMEOUT	(hz / 4)	/* 4x / second		*/
127#define		UPCALL_EXPIRE	6		/* number of timeouts	*/
128
129/*
130 * Define the token bucket filter structures
131 * tbftable -> each vif has one of these for storing info
132 */
133
134static struct tbf tbftable[MAXVIFS];
135#define		TBF_REPROCESS	(hz / 100)	/* 100x / second */
136
137/*
138 * 'Interfaces' associated with decapsulator (so we can tell
139 * packets that went through it from ones that get reflected
140 * by a broken gateway).  These interfaces are never linked into
141 * the system ifnet list & no routes point to them.  I.e., packets
142 * can't be sent this way.  They only exist as a placeholder for
143 * multicast source verification.
144 */
145static struct ifnet multicast_decap_if[MAXVIFS];
146
147#define ENCAP_TTL 64
148#define ENCAP_PROTO IPPROTO_IPIP	/* 4 */
149
150/* prototype IP hdr for encapsulated packets */
151static struct ip multicast_encap_iphdr = {
152#if BYTE_ORDER == LITTLE_ENDIAN
153	sizeof(struct ip) >> 2, IPVERSION,
154#else
155	IPVERSION, sizeof(struct ip) >> 2,
156#endif
157	0,				/* tos */
158	sizeof(struct ip),		/* total length */
159	0,				/* id */
160	0,				/* frag offset */
161	ENCAP_TTL, ENCAP_PROTO,
162	0,				/* checksum */
163};
164
165/*
166 * Bandwidth meter variables and constants
167 */
168static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
169/*
170 * Pending timeouts are stored in a hash table, the key being the
171 * expiration time. Periodically, the entries are analysed and processed.
172 */
173#define BW_METER_BUCKETS	1024
174static struct bw_meter *bw_meter_timers[BW_METER_BUCKETS];
175static struct callout bw_meter_ch;
176#define BW_METER_PERIOD (hz)		/* periodical handling of bw meters */
177
178/*
179 * Pending upcalls are stored in a vector which is flushed when
180 * full, or periodically
181 */
182static struct bw_upcall	bw_upcalls[BW_UPCALLS_MAX];
183static u_int	bw_upcalls_n; /* # of pending upcalls */
184static struct callout bw_upcalls_ch;
185#define BW_UPCALLS_PERIOD (hz)		/* periodical flush of bw upcalls */
186
187#ifdef PIM
188static struct pimstat pimstat;
189SYSCTL_STRUCT(_net_inet_pim, PIMCTL_STATS, stats, CTLFLAG_RD,
190    &pimstat, pimstat,
191    "PIM Statistics (struct pimstat, netinet/pim_var.h)");
192
193/*
194 * Note: the PIM Register encapsulation adds the following in front of a
195 * data packet:
196 *
197 * struct pim_encap_hdr {
198 *    struct ip ip;
199 *    struct pim_encap_pimhdr  pim;
200 * }
201 *
202 */
203
204struct pim_encap_pimhdr {
205	struct pim pim;
206	uint32_t   flags;
207};
208
209static struct ip pim_encap_iphdr = {
210#if BYTE_ORDER == LITTLE_ENDIAN
211	sizeof(struct ip) >> 2,
212	IPVERSION,
213#else
214	IPVERSION,
215	sizeof(struct ip) >> 2,
216#endif
217	0,			/* tos */
218	sizeof(struct ip),	/* total length */
219	0,			/* id */
220	0,			/* frag offset */
221	ENCAP_TTL,
222	IPPROTO_PIM,
223	0,			/* checksum */
224};
225
226static struct pim_encap_pimhdr pim_encap_pimhdr = {
227    {
228	PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
229	0,			/* reserved */
230	0,			/* checksum */
231    },
232    0				/* flags */
233};
234
235static struct ifnet multicast_register_if;
236static vifi_t reg_vif_num = VIFI_INVALID;
237#endif /* PIM */
238
239/*
240 * Private variables.
241 */
242static vifi_t	   numvifs;
243static const struct encaptab *encap_cookie;
244
245/*
246 * one-back cache used by mroute_encapcheck to locate a tunnel's vif
247 * given a datagram's src ip address.
248 */
249static u_long last_encap_src;
250static struct vif *last_encap_vif;
251
252/*
253 * Callout for queue processing.
254 */
255static struct callout tbf_reprocess_ch;
256
257static u_long	X_ip_mcast_src(int vifi);
258static int	X_ip_mforward(struct ip *ip, struct ifnet *ifp,
259			struct mbuf *m, struct ip_moptions *imo);
260static int	X_ip_mrouter_done(void);
261static int	X_ip_mrouter_get(struct socket *so, struct sockopt *m);
262static int	X_ip_mrouter_set(struct socket *so, struct sockopt *m);
263static int	X_legal_vif_num(int vif);
264static int	X_mrt_ioctl(int cmd, caddr_t data);
265
266static int get_sg_cnt(struct sioc_sg_req *);
267static int get_vif_cnt(struct sioc_vif_req *);
268static int ip_mrouter_init(struct socket *, int);
269static int add_vif(struct vifctl *);
270static int del_vif(vifi_t);
271static int add_mfc(struct mfcctl2 *);
272static int del_mfc(struct mfcctl2 *);
273static int set_api_config(uint32_t *); /* chose API capabilities */
274static int socket_send(struct socket *, struct mbuf *, struct sockaddr_in *);
275static int set_assert(int);
276static void expire_upcalls(void *);
277static int ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
278static void phyint_send(struct ip *, struct vif *, struct mbuf *);
279static void encap_send(struct ip *, struct vif *, struct mbuf *);
280static void tbf_control(struct vif *, struct mbuf *, struct ip *, u_long);
281static void tbf_queue(struct vif *, struct mbuf *);
282static void tbf_process_q(struct vif *);
283static void tbf_reprocess_q(void *);
284static int tbf_dq_sel(struct vif *, struct ip *);
285static void tbf_send_packet(struct vif *, struct mbuf *);
286static void tbf_update_tokens(struct vif *);
287static int priority(struct vif *, struct ip *);
288
289/*
290 * Bandwidth monitoring
291 */
292static void free_bw_list(struct bw_meter *list);
293static int add_bw_upcall(struct bw_upcall *);
294static int del_bw_upcall(struct bw_upcall *);
295static void bw_meter_receive_packet(struct bw_meter *x, int plen,
296		struct timeval *nowp);
297static void bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp);
298static void bw_upcalls_send(void);
299static void schedule_bw_meter(struct bw_meter *x, struct timeval *nowp);
300static void unschedule_bw_meter(struct bw_meter *x);
301static void bw_meter_process(void);
302static void expire_bw_upcalls_send(void *);
303static void expire_bw_meter_process(void *);
304
305#ifdef PIM
306static int pim_register_send(struct ip *, struct vif *,
307		struct mbuf *, struct mfc *);
308static int pim_register_send_rp(struct ip *, struct vif *,
309		struct mbuf *, struct mfc *);
310static int pim_register_send_upcall(struct ip *, struct vif *,
311		struct mbuf *, struct mfc *);
312static struct mbuf *pim_register_prepare(struct ip *, struct mbuf *);
313#endif
314
315/*
316 * whether or not special PIM assert processing is enabled.
317 */
318static int pim_assert;
319/*
320 * Rate limit for assert notification messages, in usec
321 */
322#define ASSERT_MSG_TIME		3000000
323
324/*
325 * Kernel multicast routing API capabilities and setup.
326 * If more API capabilities are added to the kernel, they should be
327 * recorded in `mrt_api_support'.
328 */
329static const uint32_t mrt_api_support = (MRT_MFC_FLAGS_DISABLE_WRONGVIF |
330					 MRT_MFC_FLAGS_BORDER_VIF |
331					 MRT_MFC_RP |
332					 MRT_MFC_BW_UPCALL);
333static uint32_t mrt_api_config = 0;
334
335/*
336 * Hash function for a source, group entry
337 */
338#define MFCHASH(a, g) MFCHASHMOD(((a) >> 20) ^ ((a) >> 10) ^ (a) ^ \
339			((g) >> 20) ^ ((g) >> 10) ^ (g))
340
341/*
342 * Find a route for a given origin IP address and Multicast group address
343 * Type of service parameter to be added in the future!!!
344 * Statistics are updated by the caller if needed
345 * (mrtstat.mrts_mfc_lookups and mrtstat.mrts_mfc_misses)
346 */
347static struct mfc *
348mfc_find(in_addr_t o, in_addr_t g)
349{
350    struct mfc *rt;
351
352    MFC_LOCK_ASSERT();
353
354    for (rt = mfctable[MFCHASH(o,g)]; rt; rt = rt->mfc_next)
355	if ((rt->mfc_origin.s_addr == o) &&
356		(rt->mfc_mcastgrp.s_addr == g) && (rt->mfc_stall == NULL))
357	    break;
358    return rt;
359}
360
361/*
362 * Macros to compute elapsed time efficiently
363 * Borrowed from Van Jacobson's scheduling code
364 */
365#define TV_DELTA(a, b, delta) {					\
366	int xxs;						\
367	delta = (a).tv_usec - (b).tv_usec;			\
368	if ((xxs = (a).tv_sec - (b).tv_sec)) {			\
369		switch (xxs) {					\
370		case 2:						\
371		      delta += 1000000;				\
372		      /* FALLTHROUGH */				\
373		case 1:						\
374		      delta += 1000000;				\
375		      break;					\
376		default:					\
377		      delta += (1000000 * xxs);			\
378		}						\
379	}							\
380}
381
382#define TV_LT(a, b) (((a).tv_usec < (b).tv_usec && \
383	      (a).tv_sec <= (b).tv_sec) || (a).tv_sec < (b).tv_sec)
384
385/*
386 * Handle MRT setsockopt commands to modify the multicast routing tables.
387 */
388static int
389X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
390{
391    int	error, optval;
392    vifi_t	vifi;
393    struct	vifctl vifc;
394    struct	mfcctl2 mfc;
395    struct	bw_upcall bw_upcall;
396    uint32_t	i;
397
398    if (so != ip_mrouter && sopt->sopt_name != MRT_INIT)
399	return EPERM;
400
401    error = 0;
402    switch (sopt->sopt_name) {
403    case MRT_INIT:
404	error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
405	if (error)
406	    break;
407	error = ip_mrouter_init(so, optval);
408	break;
409
410    case MRT_DONE:
411	error = ip_mrouter_done();
412	break;
413
414    case MRT_ADD_VIF:
415	error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
416	if (error)
417	    break;
418	error = add_vif(&vifc);
419	break;
420
421    case MRT_DEL_VIF:
422	error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
423	if (error)
424	    break;
425	error = del_vif(vifi);
426	break;
427
428    case MRT_ADD_MFC:
429    case MRT_DEL_MFC:
430	/*
431	 * select data size depending on API version.
432	 */
433	if (sopt->sopt_name == MRT_ADD_MFC &&
434		mrt_api_config & MRT_API_FLAGS_ALL) {
435	    error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl2),
436				sizeof(struct mfcctl2));
437	} else {
438	    error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl),
439				sizeof(struct mfcctl));
440	    bzero((caddr_t)&mfc + sizeof(struct mfcctl),
441			sizeof(mfc) - sizeof(struct mfcctl));
442	}
443	if (error)
444	    break;
445	if (sopt->sopt_name == MRT_ADD_MFC)
446	    error = add_mfc(&mfc);
447	else
448	    error = del_mfc(&mfc);
449	break;
450
451    case MRT_ASSERT:
452	error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
453	if (error)
454	    break;
455	set_assert(optval);
456	break;
457
458    case MRT_API_CONFIG:
459	error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
460	if (!error)
461	    error = set_api_config(&i);
462	if (!error)
463	    error = sooptcopyout(sopt, &i, sizeof i);
464	break;
465
466    case MRT_ADD_BW_UPCALL:
467    case MRT_DEL_BW_UPCALL:
468	error = sooptcopyin(sopt, &bw_upcall, sizeof bw_upcall,
469				sizeof bw_upcall);
470	if (error)
471	    break;
472	if (sopt->sopt_name == MRT_ADD_BW_UPCALL)
473	    error = add_bw_upcall(&bw_upcall);
474	else
475	    error = del_bw_upcall(&bw_upcall);
476	break;
477
478    default:
479	error = EOPNOTSUPP;
480	break;
481    }
482    return error;
483}
484
485/*
486 * Handle MRT getsockopt commands
487 */
488static int
489X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
490{
491    int error;
492    static int version = 0x0305; /* !!! why is this here? XXX */
493
494    switch (sopt->sopt_name) {
495    case MRT_VERSION:
496	error = sooptcopyout(sopt, &version, sizeof version);
497	break;
498
499    case MRT_ASSERT:
500	error = sooptcopyout(sopt, &pim_assert, sizeof pim_assert);
501	break;
502
503    case MRT_API_SUPPORT:
504	error = sooptcopyout(sopt, &mrt_api_support, sizeof mrt_api_support);
505	break;
506
507    case MRT_API_CONFIG:
508	error = sooptcopyout(sopt, &mrt_api_config, sizeof mrt_api_config);
509	break;
510
511    default:
512	error = EOPNOTSUPP;
513	break;
514    }
515    return error;
516}
517
518/*
519 * Handle ioctl commands to obtain information from the cache
520 */
521static int
522X_mrt_ioctl(int cmd, caddr_t data)
523{
524    int error = 0;
525
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.s_addr, req->grp.s_addr);
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    bzero((caddr_t)mfctable, sizeof(mfctable));
591    MFC_LOCK_INIT();
592    VIF_LOCK_INIT();
593    bzero((caddr_t)nexpire, sizeof(nexpire));
594
595    pim_assert = 0;
596    mrt_api_config = 0;
597
598    callout_init(&expire_upcalls_ch, CALLOUT_MPSAFE);
599
600    bw_upcalls_n = 0;
601    bzero((caddr_t)bw_meter_timers, sizeof(bw_meter_timers));
602    callout_init(&bw_upcalls_ch, CALLOUT_MPSAFE);
603    callout_init(&bw_meter_ch, CALLOUT_MPSAFE);
604
605    callout_init(&tbf_reprocess_ch, CALLOUT_MPSAFE);
606}
607
608/*
609 * Enable multicast routing
610 */
611static int
612ip_mrouter_init(struct socket *so, int version)
613{
614    if (mrtdebug)
615	log(LOG_DEBUG, "ip_mrouter_init: so_type = %d, pr_protocol = %d\n",
616	    so->so_type, so->so_proto->pr_protocol);
617
618    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_IGMP)
619	return EOPNOTSUPP;
620
621    if (version != 1)
622	return ENOPROTOOPT;
623
624    if (ip_mrouter != NULL)
625	return EADDRINUSE;
626
627    ip_mrouter_reset();
628
629    callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
630
631    callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
632	expire_bw_upcalls_send, NULL);
633    callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
634
635    ip_mrouter = so;
636
637    if (mrtdebug)
638	log(LOG_DEBUG, "ip_mrouter_init\n");
639
640    return 0;
641}
642
643/*
644 * Disable multicast routing
645 */
646static int
647X_ip_mrouter_done(void)
648{
649    vifi_t vifi;
650    int i;
651    struct ifnet *ifp;
652    struct ifreq ifr;
653    struct mfc *rt;
654    struct rtdetq *rte;
655
656    /*
657     * Detach/disable hooks to the reset of the system.
658     */
659    ip_mrouter = NULL;
660    mrt_api_config = 0;
661
662    VIF_LOCK();
663    if (encap_cookie) {
664	encap_detach(encap_cookie);
665	encap_cookie = NULL;
666    }
667    callout_stop(&tbf_reprocess_ch);
668
669    /*
670     * For each phyint in use, disable promiscuous reception of all IP
671     * multicasts.
672     */
673    for (vifi = 0; vifi < numvifs; vifi++) {
674	if (viftable[vifi].v_lcl_addr.s_addr != 0 &&
675		!(viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
676	    struct sockaddr_in *so = (struct sockaddr_in *)&(ifr.ifr_addr);
677
678	    so->sin_len = sizeof(struct sockaddr_in);
679	    so->sin_family = AF_INET;
680	    so->sin_addr.s_addr = INADDR_ANY;
681	    ifp = viftable[vifi].v_ifp;
682	    if_allmulti(ifp, 0);
683	}
684    }
685    bzero((caddr_t)tbftable, sizeof(tbftable));
686    bzero((caddr_t)viftable, sizeof(viftable));
687    numvifs = 0;
688    pim_assert = 0;
689    VIF_LOCK_DESTROY();
690
691    /*
692     * Free all multicast forwarding cache entries.
693     */
694    MFC_LOCK();
695    callout_stop(&expire_upcalls_ch);
696    callout_stop(&bw_upcalls_ch);
697    callout_stop(&bw_meter_ch);
698
699    for (i = 0; i < MFCTBLSIZ; i++) {
700	for (rt = mfctable[i]; rt != NULL; ) {
701	    struct mfc *nr = rt->mfc_next;
702
703	    for (rte = rt->mfc_stall; rte != NULL; ) {
704		struct rtdetq *n = rte->next;
705
706		m_freem(rte->m);
707		free(rte, M_MRTABLE);
708		rte = n;
709	    }
710	    free_bw_list(rt->mfc_bw_meter);
711	    free(rt, M_MRTABLE);
712	    rt = nr;
713	}
714    }
715    bzero((caddr_t)mfctable, sizeof(mfctable));
716    bw_upcalls_n = 0;
717    bzero(bw_meter_timers, sizeof(bw_meter_timers));
718    MFC_LOCK_DESTROY();
719
720    /*
721     * Reset de-encapsulation cache
722     */
723    last_encap_src = INADDR_ANY;
724    last_encap_vif = NULL;
725#ifdef PIM
726    reg_vif_num = VIFI_INVALID;
727#endif
728
729    if (mrtdebug)
730	log(LOG_DEBUG, "ip_mrouter_done\n");
731
732    return 0;
733}
734
735/*
736 * Set PIM assert processing global
737 */
738static int
739set_assert(int i)
740{
741    if ((i != 1) && (i != 0))
742	return EINVAL;
743
744    pim_assert = i;
745
746    return 0;
747}
748
749/*
750 * Configure API capabilities
751 */
752int
753set_api_config(uint32_t *apival)
754{
755    int i;
756
757    /*
758     * We can set the API capabilities only if it is the first operation
759     * after MRT_INIT. I.e.:
760     *  - there are no vifs installed
761     *  - pim_assert is not enabled
762     *  - the MFC table is empty
763     */
764    if (numvifs > 0) {
765	*apival = 0;
766	return EPERM;
767    }
768    if (pim_assert) {
769	*apival = 0;
770	return EPERM;
771    }
772    for (i = 0; i < MFCTBLSIZ; i++) {
773	if (mfctable[i] != NULL) {
774	    *apival = 0;
775	    return EPERM;
776	}
777    }
778
779    mrt_api_config = *apival & mrt_api_support;
780    *apival = mrt_api_config;
781
782    return 0;
783}
784
785/*
786 * Decide if a packet is from a tunnelled peer.
787 * Return 0 if not, 64 if so.  XXX yuck.. 64 ???
788 */
789static int
790mroute_encapcheck(const struct mbuf *m, int off, int proto, void *arg)
791{
792    struct ip *ip = mtod(m, struct ip *);
793    int hlen = ip->ip_hl << 2;
794
795    /*
796     * don't claim the packet if it's not to a multicast destination or if
797     * we don't have an encapsulating tunnel with the source.
798     * Note:  This code assumes that the remote site IP address
799     * uniquely identifies the tunnel (i.e., that this site has
800     * at most one tunnel with the remote site).
801     */
802    if (!IN_MULTICAST(ntohl(((struct ip *)((char *)ip+hlen))->ip_dst.s_addr)))
803	return 0;
804    if (ip->ip_src.s_addr != last_encap_src) {
805	struct vif *vifp = viftable;
806	struct vif *vife = vifp + numvifs;
807
808	last_encap_src = ip->ip_src.s_addr;
809	last_encap_vif = NULL;
810	for ( ; vifp < vife; ++vifp)
811	    if (vifp->v_rmt_addr.s_addr == ip->ip_src.s_addr) {
812		if ((vifp->v_flags & (VIFF_TUNNEL|VIFF_SRCRT)) == VIFF_TUNNEL)
813		    last_encap_vif = vifp;
814		break;
815	    }
816    }
817    if (last_encap_vif == NULL) {
818	last_encap_src = INADDR_ANY;
819	return 0;
820    }
821    return 64;
822}
823
824/*
825 * De-encapsulate a packet and feed it back through ip input (this
826 * routine is called whenever IP gets a packet that mroute_encap_func()
827 * claimed).
828 */
829static void
830mroute_encap_input(struct mbuf *m, int off)
831{
832    struct ip *ip = mtod(m, struct ip *);
833    int hlen = ip->ip_hl << 2;
834
835    if (hlen > sizeof(struct ip))
836	ip_stripoptions(m, (struct mbuf *) 0);
837    m->m_data += sizeof(struct ip);
838    m->m_len -= sizeof(struct ip);
839    m->m_pkthdr.len -= sizeof(struct ip);
840
841    m->m_pkthdr.rcvif = last_encap_vif->v_ifp;
842
843    netisr_queue(NETISR_IP, m);
844    /*
845     * normally we would need a "schednetisr(NETISR_IP)"
846     * here but we were called by ip_input and it is going
847     * to loop back & try to dequeue the packet we just
848     * queued as soon as we return so we avoid the
849     * unnecessary software interrrupt.
850     *
851     * XXX
852     * This no longer holds - we may have direct-dispatched the packet,
853     * or there may be a queue processing limit.
854     */
855}
856
857extern struct domain inetdomain;
858static struct protosw mroute_encap_protosw =
859{ SOCK_RAW,	&inetdomain,	IPPROTO_IPV4,	PR_ATOMIC|PR_ADDR,
860  mroute_encap_input,	0,	0,		rip_ctloutput,
861  0,
862  0,		0,		0,		0,
863  &rip_usrreqs
864};
865
866/*
867 * Add a vif to the vif table
868 */
869static int
870add_vif(struct vifctl *vifcp)
871{
872    struct vif *vifp = viftable + vifcp->vifc_vifi;
873    struct sockaddr_in sin = {sizeof sin, AF_INET};
874    struct ifaddr *ifa;
875    struct ifnet *ifp;
876    int error;
877    struct tbf *v_tbf = tbftable + vifcp->vifc_vifi;
878
879    VIF_LOCK();
880    if (vifcp->vifc_vifi >= MAXVIFS) {
881	VIF_UNLOCK();
882	return EINVAL;
883    }
884    if (vifp->v_lcl_addr.s_addr != INADDR_ANY) {
885	VIF_UNLOCK();
886	return EADDRINUSE;
887    }
888    if (vifcp->vifc_lcl_addr.s_addr == INADDR_ANY) {
889	VIF_UNLOCK();
890	return EADDRNOTAVAIL;
891    }
892
893    /* Find the interface with an address in AF_INET family */
894#ifdef PIM
895    if (vifcp->vifc_flags & VIFF_REGISTER) {
896	/*
897	 * XXX: Because VIFF_REGISTER does not really need a valid
898	 * local interface (e.g. it could be 127.0.0.2), we don't
899	 * check its address.
900	 */
901	ifp = NULL;
902    } else
903#endif
904    {
905	sin.sin_addr = vifcp->vifc_lcl_addr;
906	ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
907	if (ifa == NULL) {
908	    VIF_UNLOCK();
909	    return EADDRNOTAVAIL;
910	}
911	ifp = ifa->ifa_ifp;
912    }
913
914    if (vifcp->vifc_flags & VIFF_TUNNEL) {
915	if ((vifcp->vifc_flags & VIFF_SRCRT) == 0) {
916	    /*
917	     * An encapsulating tunnel is wanted.  Tell
918	     * mroute_encap_input() to start paying attention
919	     * to encapsulated packets.
920	     */
921	    if (encap_cookie == NULL) {
922		int i;
923
924		encap_cookie = encap_attach_func(AF_INET, IPPROTO_IPV4,
925				mroute_encapcheck,
926				(struct protosw *)&mroute_encap_protosw, NULL);
927
928		if (encap_cookie == NULL) {
929		    printf("ip_mroute: unable to attach encap\n");
930		    VIF_UNLOCK();
931		    return EIO;	/* XXX */
932		}
933		for (i = 0; i < MAXVIFS; ++i) {
934		    multicast_decap_if[i].if_name = "mdecap";
935		    multicast_decap_if[i].if_unit = i;
936		}
937	    }
938	    /*
939	     * Set interface to fake encapsulator interface
940	     */
941	    ifp = &multicast_decap_if[vifcp->vifc_vifi];
942	    /*
943	     * Prepare cached route entry
944	     */
945	    bzero(&vifp->v_route, sizeof(vifp->v_route));
946	} else {
947	    log(LOG_ERR, "source routed tunnels not supported\n");
948	    VIF_UNLOCK();
949	    return EOPNOTSUPP;
950	}
951#ifdef PIM
952    } else if (vifcp->vifc_flags & VIFF_REGISTER) {
953	ifp = &multicast_register_if;
954	if (mrtdebug)
955	    log(LOG_DEBUG, "Adding a register vif, ifp: %p\n",
956		    (void *)&multicast_register_if);
957	if (reg_vif_num == VIFI_INVALID) {
958	    multicast_register_if.if_name = "register_vif";
959	    multicast_register_if.if_unit = 0;
960	    multicast_register_if.if_flags = IFF_LOOPBACK;
961	    bzero(&vifp->v_route, sizeof(vifp->v_route));
962	    reg_vif_num = vifcp->vifc_vifi;
963	}
964#endif
965    } else {		/* Make sure the interface supports multicast */
966	if ((ifp->if_flags & IFF_MULTICAST) == 0) {
967	    VIF_UNLOCK();
968	    return EOPNOTSUPP;
969	}
970
971	/* Enable promiscuous reception of all IP multicasts from the if */
972	error = if_allmulti(ifp, 1);
973	if (error) {
974	    VIF_UNLOCK();
975	    return error;
976	}
977    }
978
979    /* define parameters for the tbf structure */
980    vifp->v_tbf = v_tbf;
981    GET_TIME(vifp->v_tbf->tbf_last_pkt_t);
982    vifp->v_tbf->tbf_n_tok = 0;
983    vifp->v_tbf->tbf_q_len = 0;
984    vifp->v_tbf->tbf_max_q_len = MAXQSIZE;
985    vifp->v_tbf->tbf_q = vifp->v_tbf->tbf_t = NULL;
986
987    vifp->v_flags     = vifcp->vifc_flags;
988    vifp->v_threshold = vifcp->vifc_threshold;
989    vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
990    vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
991    vifp->v_ifp       = ifp;
992    /* scaling up here allows division by 1024 in critical code */
993    vifp->v_rate_limit= vifcp->vifc_rate_limit * 1024 / 1000;
994    vifp->v_rsvp_on   = 0;
995    vifp->v_rsvpd     = NULL;
996    /* initialize per vif pkt counters */
997    vifp->v_pkt_in    = 0;
998    vifp->v_pkt_out   = 0;
999    vifp->v_bytes_in  = 0;
1000    vifp->v_bytes_out = 0;
1001
1002    /* Adjust numvifs up if the vifi is higher than numvifs */
1003    if (numvifs <= vifcp->vifc_vifi) numvifs = vifcp->vifc_vifi + 1;
1004
1005    VIF_UNLOCK();
1006
1007    if (mrtdebug)
1008	log(LOG_DEBUG, "add_vif #%d, lcladdr %lx, %s %lx, thresh %x, rate %d\n",
1009	    vifcp->vifc_vifi,
1010	    (u_long)ntohl(vifcp->vifc_lcl_addr.s_addr),
1011	    (vifcp->vifc_flags & VIFF_TUNNEL) ? "rmtaddr" : "mask",
1012	    (u_long)ntohl(vifcp->vifc_rmt_addr.s_addr),
1013	    vifcp->vifc_threshold,
1014	    vifcp->vifc_rate_limit);
1015
1016    return 0;
1017}
1018
1019/*
1020 * Delete a vif from the vif table
1021 */
1022static int
1023del_vif(vifi_t vifi)
1024{
1025    struct vif *vifp;
1026
1027    VIF_LOCK();
1028
1029    if (vifi >= numvifs) {
1030	VIF_UNLOCK();
1031	return EINVAL;
1032    }
1033    vifp = &viftable[vifi];
1034    if (vifp->v_lcl_addr.s_addr == INADDR_ANY) {
1035	VIF_UNLOCK();
1036	return EADDRNOTAVAIL;
1037    }
1038
1039    if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
1040	if_allmulti(vifp->v_ifp, 0);
1041
1042    if (vifp == last_encap_vif) {
1043	last_encap_vif = NULL;
1044	last_encap_src = INADDR_ANY;
1045    }
1046
1047    /*
1048     * Free packets queued at the interface
1049     */
1050    while (vifp->v_tbf->tbf_q) {
1051	struct mbuf *m = vifp->v_tbf->tbf_q;
1052
1053	vifp->v_tbf->tbf_q = m->m_act;
1054	m_freem(m);
1055    }
1056
1057#ifdef PIM
1058    if (vifp->v_flags & VIFF_REGISTER)
1059	reg_vif_num = VIFI_INVALID;
1060#endif
1061
1062    bzero((caddr_t)vifp->v_tbf, sizeof(*(vifp->v_tbf)));
1063    bzero((caddr_t)vifp, sizeof (*vifp));
1064
1065    if (mrtdebug)
1066	log(LOG_DEBUG, "del_vif %d, numvifs %d\n", vifi, numvifs);
1067
1068    /* Adjust numvifs down */
1069    for (vifi = numvifs; vifi > 0; vifi--)
1070	if (viftable[vifi-1].v_lcl_addr.s_addr != INADDR_ANY)
1071	    break;
1072    numvifs = vifi;
1073
1074    VIF_UNLOCK();
1075
1076    return 0;
1077}
1078
1079/*
1080 * update an mfc entry without resetting counters and S,G addresses.
1081 */
1082static void
1083update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1084{
1085    int i;
1086
1087    rt->mfc_parent = mfccp->mfcc_parent;
1088    for (i = 0; i < numvifs; i++) {
1089	rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1090	rt->mfc_flags[i] = mfccp->mfcc_flags[i] & mrt_api_config &
1091	    MRT_MFC_FLAGS_ALL;
1092    }
1093    /* set the RP address */
1094    if (mrt_api_config & MRT_MFC_RP)
1095	rt->mfc_rp = mfccp->mfcc_rp;
1096    else
1097	rt->mfc_rp.s_addr = INADDR_ANY;
1098}
1099
1100/*
1101 * fully initialize an mfc entry from the parameter.
1102 */
1103static void
1104init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1105{
1106    rt->mfc_origin     = mfccp->mfcc_origin;
1107    rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
1108
1109    update_mfc_params(rt, mfccp);
1110
1111    /* initialize pkt counters per src-grp */
1112    rt->mfc_pkt_cnt    = 0;
1113    rt->mfc_byte_cnt   = 0;
1114    rt->mfc_wrong_if   = 0;
1115    rt->mfc_last_assert.tv_sec = rt->mfc_last_assert.tv_usec = 0;
1116}
1117
1118
1119/*
1120 * Add an mfc entry
1121 */
1122static int
1123add_mfc(struct mfcctl2 *mfccp)
1124{
1125    struct mfc *rt;
1126    u_long hash;
1127    struct rtdetq *rte;
1128    u_short nstl;
1129
1130    VIF_LOCK();
1131    MFC_LOCK();
1132
1133    rt = mfc_find(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
1134
1135    /* If an entry already exists, just update the fields */
1136    if (rt) {
1137	if (mrtdebug & DEBUG_MFC)
1138	    log(LOG_DEBUG,"add_mfc update o %lx g %lx p %x\n",
1139		(u_long)ntohl(mfccp->mfcc_origin.s_addr),
1140		(u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1141		mfccp->mfcc_parent);
1142
1143	update_mfc_params(rt, mfccp);
1144	MFC_UNLOCK();
1145	VIF_UNLOCK();
1146	return 0;
1147    }
1148
1149    /*
1150     * Find the entry for which the upcall was made and update
1151     */
1152    hash = MFCHASH(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
1153    for (rt = mfctable[hash], nstl = 0; rt; rt = rt->mfc_next) {
1154
1155	if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1156		(rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr) &&
1157		(rt->mfc_stall != NULL)) {
1158
1159	    if (nstl++)
1160		log(LOG_ERR, "add_mfc %s o %lx g %lx p %x dbx %p\n",
1161		    "multiple kernel entries",
1162		    (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1163		    (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1164		    mfccp->mfcc_parent, (void *)rt->mfc_stall);
1165
1166	    if (mrtdebug & DEBUG_MFC)
1167		log(LOG_DEBUG,"add_mfc o %lx g %lx p %x dbg %p\n",
1168		    (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1169		    (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1170		    mfccp->mfcc_parent, (void *)rt->mfc_stall);
1171
1172	    init_mfc_params(rt, mfccp);
1173
1174	    rt->mfc_expire = 0;	/* Don't clean this guy up */
1175	    nexpire[hash]--;
1176
1177	    /* free packets Qed at the end of this entry */
1178	    for (rte = rt->mfc_stall; rte != NULL; ) {
1179		struct rtdetq *n = rte->next;
1180
1181		ip_mdq(rte->m, rte->ifp, rt, -1);
1182		m_freem(rte->m);
1183		free(rte, M_MRTABLE);
1184		rte = n;
1185	    }
1186	    rt->mfc_stall = NULL;
1187	}
1188    }
1189
1190    /*
1191     * It is possible that an entry is being inserted without an upcall
1192     */
1193    if (nstl == 0) {
1194	if (mrtdebug & DEBUG_MFC)
1195	    log(LOG_DEBUG,"add_mfc no upcall h %lu o %lx g %lx p %x\n",
1196		hash, (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1197		(u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1198		mfccp->mfcc_parent);
1199
1200	for (rt = mfctable[hash]; rt != NULL; rt = rt->mfc_next) {
1201	    if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1202		    (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr)) {
1203		init_mfc_params(rt, mfccp);
1204		if (rt->mfc_expire)
1205		    nexpire[hash]--;
1206		rt->mfc_expire = 0;
1207		break; /* XXX */
1208	    }
1209	}
1210	if (rt == NULL) {		/* no upcall, so make a new entry */
1211	    rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1212	    if (rt == NULL) {
1213		MFC_UNLOCK();
1214		VIF_UNLOCK();
1215		return ENOBUFS;
1216	    }
1217
1218	    init_mfc_params(rt, mfccp);
1219	    rt->mfc_expire     = 0;
1220	    rt->mfc_stall      = NULL;
1221
1222	    rt->mfc_bw_meter = NULL;
1223	    /* insert new entry at head of hash chain */
1224	    rt->mfc_next = mfctable[hash];
1225	    mfctable[hash] = rt;
1226	}
1227    }
1228    MFC_UNLOCK();
1229    VIF_UNLOCK();
1230    return 0;
1231}
1232
1233/*
1234 * Delete an mfc entry
1235 */
1236static int
1237del_mfc(struct mfcctl2 *mfccp)
1238{
1239    struct in_addr 	origin;
1240    struct in_addr 	mcastgrp;
1241    struct mfc 		*rt;
1242    struct mfc	 	**nptr;
1243    u_long 		hash;
1244    struct bw_meter	*list;
1245
1246    origin = mfccp->mfcc_origin;
1247    mcastgrp = mfccp->mfcc_mcastgrp;
1248
1249    if (mrtdebug & DEBUG_MFC)
1250	log(LOG_DEBUG,"del_mfc orig %lx mcastgrp %lx\n",
1251	    (u_long)ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
1252
1253    MFC_LOCK();
1254
1255    hash = MFCHASH(origin.s_addr, mcastgrp.s_addr);
1256    for (nptr = &mfctable[hash]; (rt = *nptr) != NULL; nptr = &rt->mfc_next)
1257	if (origin.s_addr == rt->mfc_origin.s_addr &&
1258		mcastgrp.s_addr == rt->mfc_mcastgrp.s_addr &&
1259		rt->mfc_stall == NULL)
1260	    break;
1261    if (rt == NULL) {
1262	MFC_UNLOCK();
1263	return EADDRNOTAVAIL;
1264    }
1265
1266    *nptr = rt->mfc_next;
1267
1268    /*
1269     * free the bw_meter entries
1270     */
1271    list = rt->mfc_bw_meter;
1272    rt->mfc_bw_meter = NULL;
1273
1274    free(rt, M_MRTABLE);
1275
1276    free_bw_list(list);
1277
1278    MFC_UNLOCK();
1279
1280    return 0;
1281}
1282
1283/*
1284 * Send a message to mrouted on the multicast routing socket
1285 */
1286static int
1287socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1288{
1289    if (s) {
1290	if (sbappendaddr(&s->so_rcv, (struct sockaddr *)src, mm, NULL) != 0) {
1291	    sorwakeup(s);
1292	    return 0;
1293	}
1294    }
1295    m_freem(mm);
1296    return -1;
1297}
1298
1299/*
1300 * IP multicast forwarding function. This function assumes that the packet
1301 * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1302 * pointed to by "ifp", and the packet is to be relayed to other networks
1303 * that have members of the packet's destination IP multicast group.
1304 *
1305 * The packet is returned unscathed to the caller, unless it is
1306 * erroneous, in which case a non-zero return value tells the caller to
1307 * discard it.
1308 */
1309
1310#define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1311
1312static int
1313X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1314    struct ip_moptions *imo)
1315{
1316    struct mfc *rt;
1317    int error;
1318    vifi_t vifi;
1319
1320    if (mrtdebug & DEBUG_FORWARD)
1321	log(LOG_DEBUG, "ip_mforward: src %lx, dst %lx, ifp %p\n",
1322	    (u_long)ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr),
1323	    (void *)ifp);
1324
1325    if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1326		((u_char *)(ip + 1))[1] != IPOPT_LSRR ) {
1327	/*
1328	 * Packet arrived via a physical interface or
1329	 * an encapsulated tunnel or a register_vif.
1330	 */
1331    } else {
1332	/*
1333	 * Packet arrived through a source-route tunnel.
1334	 * Source-route tunnels are no longer supported.
1335	 */
1336	static int last_log;
1337	if (last_log != time_second) {
1338	    last_log = time_second;
1339	    log(LOG_ERR,
1340		"ip_mforward: received source-routed packet from %lx\n",
1341		(u_long)ntohl(ip->ip_src.s_addr));
1342	}
1343	return 1;
1344    }
1345
1346    VIF_LOCK();
1347    MFC_LOCK();
1348    if (imo && ((vifi = imo->imo_multicast_vif) < numvifs)) {
1349	if (ip->ip_ttl < 255)
1350	    ip->ip_ttl++;	/* compensate for -1 in *_send routines */
1351	if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1352	    struct vif *vifp = viftable + vifi;
1353
1354	    printf("Sending IPPROTO_RSVP from %lx to %lx on vif %d (%s%s%d)\n",
1355		(long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr),
1356		vifi,
1357		(vifp->v_flags & VIFF_TUNNEL) ? "tunnel on " : "",
1358		vifp->v_ifp->if_name, vifp->v_ifp->if_unit);
1359	}
1360	error = ip_mdq(m, ifp, NULL, vifi);
1361	MFC_UNLOCK();
1362	VIF_UNLOCK();
1363	return error;
1364    }
1365    if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1366	printf("Warning: IPPROTO_RSVP from %lx to %lx without vif option\n",
1367	    (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr));
1368	if (!imo)
1369	    printf("In fact, no options were specified at all\n");
1370    }
1371
1372    /*
1373     * Don't forward a packet with time-to-live of zero or one,
1374     * or a packet destined to a local-only group.
1375     */
1376    if (ip->ip_ttl <= 1 || ntohl(ip->ip_dst.s_addr) <= INADDR_MAX_LOCAL_GROUP) {
1377	MFC_UNLOCK();
1378	VIF_UNLOCK();
1379	return 0;
1380    }
1381
1382    /*
1383     * Determine forwarding vifs from the forwarding cache table
1384     */
1385    ++mrtstat.mrts_mfc_lookups;
1386    rt = mfc_find(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1387
1388    /* Entry exists, so forward if necessary */
1389    if (rt != NULL) {
1390	error = ip_mdq(m, ifp, rt, -1);
1391	MFC_UNLOCK();
1392	VIF_UNLOCK();
1393	return error;
1394    } else {
1395	/*
1396	 * If we don't have a route for packet's origin,
1397	 * Make a copy of the packet & send message to routing daemon
1398	 */
1399
1400	struct mbuf *mb0;
1401	struct rtdetq *rte;
1402	u_long hash;
1403	int hlen = ip->ip_hl << 2;
1404
1405	++mrtstat.mrts_mfc_misses;
1406
1407	mrtstat.mrts_no_route++;
1408	if (mrtdebug & (DEBUG_FORWARD | DEBUG_MFC))
1409	    log(LOG_DEBUG, "ip_mforward: no rte s %lx g %lx\n",
1410		(u_long)ntohl(ip->ip_src.s_addr),
1411		(u_long)ntohl(ip->ip_dst.s_addr));
1412
1413	/*
1414	 * Allocate mbufs early so that we don't do extra work if we are
1415	 * just going to fail anyway.  Make sure to pullup the header so
1416	 * that other people can't step on it.
1417	 */
1418	rte = (struct rtdetq *)malloc((sizeof *rte), M_MRTABLE, M_NOWAIT);
1419	if (rte == NULL) {
1420	    MFC_UNLOCK();
1421	    VIF_UNLOCK();
1422	    return ENOBUFS;
1423	}
1424	mb0 = m_copypacket(m, M_DONTWAIT);
1425	if (mb0 && (M_HASCL(mb0) || mb0->m_len < hlen))
1426	    mb0 = m_pullup(mb0, hlen);
1427	if (mb0 == NULL) {
1428	    free(rte, M_MRTABLE);
1429	    MFC_UNLOCK();
1430	    VIF_UNLOCK();
1431	    return ENOBUFS;
1432	}
1433
1434	/* is there an upcall waiting for this flow ? */
1435	hash = MFCHASH(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1436	for (rt = mfctable[hash]; rt; rt = rt->mfc_next) {
1437	    if ((ip->ip_src.s_addr == rt->mfc_origin.s_addr) &&
1438		    (ip->ip_dst.s_addr == rt->mfc_mcastgrp.s_addr) &&
1439		    (rt->mfc_stall != NULL))
1440		break;
1441	}
1442
1443	if (rt == NULL) {
1444	    int i;
1445	    struct igmpmsg *im;
1446	    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1447	    struct mbuf *mm;
1448
1449	    /*
1450	     * Locate the vifi for the incoming interface for this packet.
1451	     * If none found, drop packet.
1452	     */
1453	    for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1454		;
1455	    if (vifi >= numvifs)	/* vif not found, drop packet */
1456		goto non_fatal;
1457
1458	    /* no upcall, so make a new entry */
1459	    rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1460	    if (rt == NULL)
1461		goto fail;
1462	    /* Make a copy of the header to send to the user level process */
1463	    mm = m_copy(mb0, 0, hlen);
1464	    if (mm == NULL)
1465		goto fail1;
1466
1467	    /*
1468	     * Send message to routing daemon to install
1469	     * a route into the kernel table
1470	     */
1471
1472	    im = mtod(mm, struct igmpmsg *);
1473	    im->im_msgtype = IGMPMSG_NOCACHE;
1474	    im->im_mbz = 0;
1475	    im->im_vif = vifi;
1476
1477	    mrtstat.mrts_upcalls++;
1478
1479	    k_igmpsrc.sin_addr = ip->ip_src;
1480	    if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1481		log(LOG_WARNING, "ip_mforward: ip_mrouter socket queue full\n");
1482		++mrtstat.mrts_upq_sockfull;
1483fail1:
1484		free(rt, M_MRTABLE);
1485fail:
1486		free(rte, M_MRTABLE);
1487		m_freem(mb0);
1488		MFC_UNLOCK();
1489		VIF_UNLOCK();
1490		return ENOBUFS;
1491	    }
1492
1493	    /* insert new entry at head of hash chain */
1494	    rt->mfc_origin.s_addr     = ip->ip_src.s_addr;
1495	    rt->mfc_mcastgrp.s_addr   = ip->ip_dst.s_addr;
1496	    rt->mfc_expire	      = UPCALL_EXPIRE;
1497	    nexpire[hash]++;
1498	    for (i = 0; i < numvifs; i++) {
1499		rt->mfc_ttls[i] = 0;
1500		rt->mfc_flags[i] = 0;
1501	    }
1502	    rt->mfc_parent = -1;
1503
1504	    rt->mfc_rp.s_addr = INADDR_ANY; /* clear the RP address */
1505
1506	    rt->mfc_bw_meter = NULL;
1507
1508	    /* link into table */
1509	    rt->mfc_next   = mfctable[hash];
1510	    mfctable[hash] = rt;
1511	    rt->mfc_stall = rte;
1512
1513	} else {
1514	    /* determine if q has overflowed */
1515	    int npkts = 0;
1516	    struct rtdetq **p;
1517
1518	    /*
1519	     * XXX ouch! we need to append to the list, but we
1520	     * only have a pointer to the front, so we have to
1521	     * scan the entire list every time.
1522	     */
1523	    for (p = &rt->mfc_stall; *p != NULL; p = &(*p)->next)
1524		npkts++;
1525
1526	    if (npkts > MAX_UPQ) {
1527		mrtstat.mrts_upq_ovflw++;
1528non_fatal:
1529		free(rte, M_MRTABLE);
1530		m_freem(mb0);
1531		MFC_UNLOCK();
1532		VIF_UNLOCK();
1533		return 0;
1534	    }
1535
1536	    /* Add this entry to the end of the queue */
1537	    *p = rte;
1538	}
1539
1540	rte->m 			= mb0;
1541	rte->ifp 		= ifp;
1542	rte->next		= NULL;
1543
1544	MFC_UNLOCK();
1545	VIF_UNLOCK();
1546
1547	return 0;
1548    }
1549}
1550
1551/*
1552 * Clean up the cache entry if upcall is not serviced
1553 */
1554static void
1555expire_upcalls(void *unused)
1556{
1557    struct rtdetq *rte;
1558    struct mfc *mfc, **nptr;
1559    int i;
1560
1561    MFC_LOCK();
1562    for (i = 0; i < MFCTBLSIZ; i++) {
1563	if (nexpire[i] == 0)
1564	    continue;
1565	nptr = &mfctable[i];
1566	for (mfc = *nptr; mfc != NULL; mfc = *nptr) {
1567	    /*
1568	     * Skip real cache entries
1569	     * Make sure it wasn't marked to not expire (shouldn't happen)
1570	     * If it expires now
1571	     */
1572	    if (mfc->mfc_stall != NULL && mfc->mfc_expire != 0 &&
1573		    --mfc->mfc_expire == 0) {
1574		if (mrtdebug & DEBUG_EXPIRE)
1575		    log(LOG_DEBUG, "expire_upcalls: expiring (%lx %lx)\n",
1576			(u_long)ntohl(mfc->mfc_origin.s_addr),
1577			(u_long)ntohl(mfc->mfc_mcastgrp.s_addr));
1578		/*
1579		 * drop all the packets
1580		 * free the mbuf with the pkt, if, timing info
1581		 */
1582		for (rte = mfc->mfc_stall; rte; ) {
1583		    struct rtdetq *n = rte->next;
1584
1585		    m_freem(rte->m);
1586		    free(rte, M_MRTABLE);
1587		    rte = n;
1588		}
1589		++mrtstat.mrts_cache_cleanups;
1590		nexpire[i]--;
1591
1592		/*
1593		 * free the bw_meter entries
1594		 */
1595		while (mfc->mfc_bw_meter != NULL) {
1596		    struct bw_meter *x = mfc->mfc_bw_meter;
1597
1598		    mfc->mfc_bw_meter = x->bm_mfc_next;
1599		    free(x, M_BWMETER);
1600		}
1601
1602		*nptr = mfc->mfc_next;
1603		free(mfc, M_MRTABLE);
1604	    } else {
1605		nptr = &mfc->mfc_next;
1606	    }
1607	}
1608    }
1609    MFC_UNLOCK();
1610
1611    callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
1612}
1613
1614/*
1615 * Packet forwarding routine once entry in the cache is made
1616 */
1617static int
1618ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1619{
1620    struct ip  *ip = mtod(m, struct ip *);
1621    vifi_t vifi;
1622    int plen = ip->ip_len;
1623
1624    VIF_LOCK_ASSERT();
1625/*
1626 * Macro to send packet on vif.  Since RSVP packets don't get counted on
1627 * input, they shouldn't get counted on output, so statistics keeping is
1628 * separate.
1629 */
1630#define MC_SEND(ip,vifp,m) {				\
1631		if ((vifp)->v_flags & VIFF_TUNNEL)	\
1632		    encap_send((ip), (vifp), (m));	\
1633		else					\
1634		    phyint_send((ip), (vifp), (m));	\
1635}
1636
1637    /*
1638     * If xmt_vif is not -1, send on only the requested vif.
1639     *
1640     * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1641     */
1642    if (xmt_vif < numvifs) {
1643#ifdef PIM
1644	if (viftable[xmt_vif].v_flags & VIFF_REGISTER)
1645	    pim_register_send(ip, viftable + xmt_vif, m, rt);
1646        else
1647#endif
1648	MC_SEND(ip, viftable + xmt_vif, m);
1649	return 1;
1650    }
1651
1652    /*
1653     * Don't forward if it didn't arrive from the parent vif for its origin.
1654     */
1655    vifi = rt->mfc_parent;
1656    if ((vifi >= numvifs) || (viftable[vifi].v_ifp != ifp)) {
1657	/* came in the wrong interface */
1658	if (mrtdebug & DEBUG_FORWARD)
1659	    log(LOG_DEBUG, "wrong if: ifp %p vifi %d vififp %p\n",
1660		(void *)ifp, vifi, (void *)viftable[vifi].v_ifp);
1661	++mrtstat.mrts_wrong_if;
1662	++rt->mfc_wrong_if;
1663	/*
1664	 * If we are doing PIM assert processing, send a message
1665	 * to the routing daemon.
1666	 *
1667	 * XXX: A PIM-SM router needs the WRONGVIF detection so it
1668	 * can complete the SPT switch, regardless of the type
1669	 * of the iif (broadcast media, GRE tunnel, etc).
1670	 */
1671	if (pim_assert && (vifi < numvifs) && viftable[vifi].v_ifp) {
1672	    struct timeval now;
1673	    u_long delta;
1674
1675#ifdef PIM
1676	    if (ifp == &multicast_register_if)
1677		pimstat.pims_rcv_registers_wrongiif++;
1678#endif
1679
1680	    /* Get vifi for the incoming packet */
1681	    for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1682		;
1683	    if (vifi >= numvifs)
1684		return 0;	/* The iif is not found: ignore the packet. */
1685
1686	    if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1687		return 0;	/* WRONGVIF disabled: ignore the packet */
1688
1689	    GET_TIME(now);
1690
1691	    TV_DELTA(rt->mfc_last_assert, now, delta);
1692
1693	    if (delta > ASSERT_MSG_TIME) {
1694		struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1695		struct igmpmsg *im;
1696		int hlen = ip->ip_hl << 2;
1697		struct mbuf *mm = m_copy(m, 0, hlen);
1698
1699		if (mm && (M_HASCL(mm) || mm->m_len < hlen))
1700		    mm = m_pullup(mm, hlen);
1701		if (mm == NULL)
1702		    return ENOBUFS;
1703
1704		rt->mfc_last_assert = now;
1705
1706		im = mtod(mm, struct igmpmsg *);
1707		im->im_msgtype	= IGMPMSG_WRONGVIF;
1708		im->im_mbz		= 0;
1709		im->im_vif		= vifi;
1710
1711		mrtstat.mrts_upcalls++;
1712
1713		k_igmpsrc.sin_addr = im->im_src;
1714		if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1715		    log(LOG_WARNING,
1716			"ip_mforward: ip_mrouter socket queue full\n");
1717		    ++mrtstat.mrts_upq_sockfull;
1718		    return ENOBUFS;
1719		}
1720	    }
1721	}
1722	return 0;
1723    }
1724
1725    /* If I sourced this packet, it counts as output, else it was input. */
1726    if (ip->ip_src.s_addr == viftable[vifi].v_lcl_addr.s_addr) {
1727	viftable[vifi].v_pkt_out++;
1728	viftable[vifi].v_bytes_out += plen;
1729    } else {
1730	viftable[vifi].v_pkt_in++;
1731	viftable[vifi].v_bytes_in += plen;
1732    }
1733    rt->mfc_pkt_cnt++;
1734    rt->mfc_byte_cnt += plen;
1735
1736    /*
1737     * For each vif, decide if a copy of the packet should be forwarded.
1738     * Forward if:
1739     *		- the ttl exceeds the vif's threshold
1740     *		- there are group members downstream on interface
1741     */
1742    for (vifi = 0; vifi < numvifs; vifi++)
1743	if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1744	    viftable[vifi].v_pkt_out++;
1745	    viftable[vifi].v_bytes_out += plen;
1746#ifdef PIM
1747	    if (viftable[vifi].v_flags & VIFF_REGISTER)
1748		pim_register_send(ip, viftable + vifi, m, rt);
1749	    else
1750#endif
1751	    MC_SEND(ip, viftable+vifi, m);
1752	}
1753
1754    /*
1755     * Perform upcall-related bw measuring.
1756     */
1757    if (rt->mfc_bw_meter != NULL) {
1758	struct bw_meter *x;
1759	struct timeval now;
1760
1761	GET_TIME(now);
1762	MFC_LOCK_ASSERT();
1763	for (x = rt->mfc_bw_meter; x != NULL; x = x->bm_mfc_next)
1764	    bw_meter_receive_packet(x, plen, &now);
1765    }
1766
1767    return 0;
1768}
1769
1770/*
1771 * check if a vif number is legal/ok. This is used by ip_output.
1772 */
1773static int
1774X_legal_vif_num(int vif)
1775{
1776    /* XXX unlocked, matter? */
1777    return (vif >= 0 && vif < numvifs);
1778}
1779
1780/*
1781 * Return the local address used by this vif
1782 */
1783static u_long
1784X_ip_mcast_src(int vifi)
1785{
1786    /* XXX unlocked, matter? */
1787    if (vifi >= 0 && vifi < numvifs)
1788	return viftable[vifi].v_lcl_addr.s_addr;
1789    else
1790	return INADDR_ANY;
1791}
1792
1793static void
1794phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1795{
1796    struct mbuf *mb_copy;
1797    int hlen = ip->ip_hl << 2;
1798
1799    VIF_LOCK_ASSERT();
1800
1801    /*
1802     * Make a new reference to the packet; make sure that
1803     * the IP header is actually copied, not just referenced,
1804     * so that ip_output() only scribbles on the copy.
1805     */
1806    mb_copy = m_copypacket(m, M_DONTWAIT);
1807    if (mb_copy && (M_HASCL(mb_copy) || mb_copy->m_len < hlen))
1808	mb_copy = m_pullup(mb_copy, hlen);
1809    if (mb_copy == NULL)
1810	return;
1811
1812    if (vifp->v_rate_limit == 0)
1813	tbf_send_packet(vifp, mb_copy);
1814    else
1815	tbf_control(vifp, mb_copy, mtod(mb_copy, struct ip *), ip->ip_len);
1816}
1817
1818static void
1819encap_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1820{
1821    struct mbuf *mb_copy;
1822    struct ip *ip_copy;
1823    int i, len = ip->ip_len;
1824
1825    VIF_LOCK_ASSERT();
1826
1827    /* Take care of delayed checksums */
1828    if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1829	in_delayed_cksum(m);
1830	m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1831    }
1832
1833    /*
1834     * copy the old packet & pullup its IP header into the
1835     * new mbuf so we can modify it.  Try to fill the new
1836     * mbuf since if we don't the ethernet driver will.
1837     */
1838    MGETHDR(mb_copy, M_DONTWAIT, MT_HEADER);
1839    if (mb_copy == NULL)
1840	return;
1841#ifdef MAC
1842    mac_create_mbuf_multicast_encap(m, vifp->v_ifp, mb_copy);
1843#endif
1844    mb_copy->m_data += max_linkhdr;
1845    mb_copy->m_len = sizeof(multicast_encap_iphdr);
1846
1847    if ((mb_copy->m_next = m_copypacket(m, M_DONTWAIT)) == NULL) {
1848	m_freem(mb_copy);
1849	return;
1850    }
1851    i = MHLEN - M_LEADINGSPACE(mb_copy);
1852    if (i > len)
1853	i = len;
1854    mb_copy = m_pullup(mb_copy, i);
1855    if (mb_copy == NULL)
1856	return;
1857    mb_copy->m_pkthdr.len = len + sizeof(multicast_encap_iphdr);
1858
1859    /*
1860     * fill in the encapsulating IP header.
1861     */
1862    ip_copy = mtod(mb_copy, struct ip *);
1863    *ip_copy = multicast_encap_iphdr;
1864#ifdef RANDOM_IP_ID
1865    ip_copy->ip_id = ip_randomid();
1866#else
1867    ip_copy->ip_id = htons(ip_id++);
1868#endif
1869    ip_copy->ip_len += len;
1870    ip_copy->ip_src = vifp->v_lcl_addr;
1871    ip_copy->ip_dst = vifp->v_rmt_addr;
1872
1873    /*
1874     * turn the encapsulated IP header back into a valid one.
1875     */
1876    ip = (struct ip *)((caddr_t)ip_copy + sizeof(multicast_encap_iphdr));
1877    --ip->ip_ttl;
1878    ip->ip_len = htons(ip->ip_len);
1879    ip->ip_off = htons(ip->ip_off);
1880    ip->ip_sum = 0;
1881    mb_copy->m_data += sizeof(multicast_encap_iphdr);
1882    ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
1883    mb_copy->m_data -= sizeof(multicast_encap_iphdr);
1884
1885    if (vifp->v_rate_limit == 0)
1886	tbf_send_packet(vifp, mb_copy);
1887    else
1888	tbf_control(vifp, mb_copy, ip, ip_copy->ip_len);
1889}
1890
1891/*
1892 * Token bucket filter module
1893 */
1894
1895static void
1896tbf_control(struct vif *vifp, struct mbuf *m, struct ip *ip, u_long p_len)
1897{
1898    struct tbf *t = vifp->v_tbf;
1899
1900    VIF_LOCK_ASSERT();
1901
1902    if (p_len > MAX_BKT_SIZE) {		/* drop if packet is too large */
1903	mrtstat.mrts_pkt2large++;
1904	m_freem(m);
1905	return;
1906    }
1907
1908    tbf_update_tokens(vifp);
1909
1910    if (t->tbf_q_len == 0) {		/* queue empty...		*/
1911	if (p_len <= t->tbf_n_tok) {	/* send packet if enough tokens */
1912	    t->tbf_n_tok -= p_len;
1913	    tbf_send_packet(vifp, m);
1914	} else {			/* no, queue packet and try later */
1915	    tbf_queue(vifp, m);
1916	    callout_reset(&tbf_reprocess_ch, TBF_REPROCESS,
1917		tbf_reprocess_q, vifp);
1918	}
1919    } else if (t->tbf_q_len < t->tbf_max_q_len) {
1920	/* finite queue length, so queue pkts and process queue */
1921	tbf_queue(vifp, m);
1922	tbf_process_q(vifp);
1923    } else {
1924	/* queue full, try to dq and queue and process */
1925	if (!tbf_dq_sel(vifp, ip)) {
1926	    mrtstat.mrts_q_overflow++;
1927	    m_freem(m);
1928	} else {
1929	    tbf_queue(vifp, m);
1930	    tbf_process_q(vifp);
1931	}
1932    }
1933}
1934
1935/*
1936 * adds a packet to the queue at the interface
1937 */
1938static void
1939tbf_queue(struct vif *vifp, struct mbuf *m)
1940{
1941    struct tbf *t = vifp->v_tbf;
1942
1943    VIF_LOCK_ASSERT();
1944
1945    if (t->tbf_t == NULL)	/* Queue was empty */
1946	t->tbf_q = m;
1947    else			/* Insert at tail */
1948	t->tbf_t->m_act = m;
1949
1950    t->tbf_t = m;		/* Set new tail pointer */
1951
1952#ifdef DIAGNOSTIC
1953    /* Make sure we didn't get fed a bogus mbuf */
1954    if (m->m_act)
1955	panic("tbf_queue: m_act");
1956#endif
1957    m->m_act = NULL;
1958
1959    t->tbf_q_len++;
1960}
1961
1962/*
1963 * processes the queue at the interface
1964 */
1965static void
1966tbf_process_q(struct vif *vifp)
1967{
1968    struct tbf *t = vifp->v_tbf;
1969
1970    VIF_LOCK_ASSERT();
1971
1972    /* loop through the queue at the interface and send as many packets
1973     * as possible
1974     */
1975    while (t->tbf_q_len > 0) {
1976	struct mbuf *m = t->tbf_q;
1977	int len = mtod(m, struct ip *)->ip_len;
1978
1979	/* determine if the packet can be sent */
1980	if (len > t->tbf_n_tok)	/* not enough tokens, we are done */
1981	    break;
1982	/* ok, reduce no of tokens, dequeue and send the packet. */
1983	t->tbf_n_tok -= len;
1984
1985	t->tbf_q = m->m_act;
1986	if (--t->tbf_q_len == 0)
1987	    t->tbf_t = NULL;
1988
1989	m->m_act = NULL;
1990	tbf_send_packet(vifp, m);
1991    }
1992}
1993
1994static void
1995tbf_reprocess_q(void *xvifp)
1996{
1997    struct vif *vifp = xvifp;
1998
1999    if (ip_mrouter == NULL)
2000	return;
2001    VIF_LOCK();
2002    tbf_update_tokens(vifp);
2003    tbf_process_q(vifp);
2004    if (vifp->v_tbf->tbf_q_len)
2005	callout_reset(&tbf_reprocess_ch, TBF_REPROCESS, tbf_reprocess_q, vifp);
2006    VIF_UNLOCK();
2007}
2008
2009/* function that will selectively discard a member of the queue
2010 * based on the precedence value and the priority
2011 */
2012static int
2013tbf_dq_sel(struct vif *vifp, struct ip *ip)
2014{
2015    u_int p;
2016    struct mbuf *m, *last;
2017    struct mbuf **np;
2018    struct tbf *t = vifp->v_tbf;
2019
2020    VIF_LOCK_ASSERT();
2021
2022    p = priority(vifp, ip);
2023
2024    np = &t->tbf_q;
2025    last = NULL;
2026    while ((m = *np) != NULL) {
2027	if (p > priority(vifp, mtod(m, struct ip *))) {
2028	    *np = m->m_act;
2029	    /* If we're removing the last packet, fix the tail pointer */
2030	    if (m == t->tbf_t)
2031		t->tbf_t = last;
2032	    m_freem(m);
2033	    /* It's impossible for the queue to be empty, but check anyways. */
2034	    if (--t->tbf_q_len == 0)
2035		t->tbf_t = NULL;
2036	    mrtstat.mrts_drop_sel++;
2037	    return 1;
2038	}
2039	np = &m->m_act;
2040	last = m;
2041    }
2042    return 0;
2043}
2044
2045static void
2046tbf_send_packet(struct vif *vifp, struct mbuf *m)
2047{
2048    VIF_LOCK_ASSERT();
2049
2050    if (vifp->v_flags & VIFF_TUNNEL)	/* If tunnel options */
2051	ip_output(m, NULL, &vifp->v_route, IP_FORWARDING, NULL, NULL);
2052    else {
2053	struct ip_moptions imo;
2054	int error;
2055	static struct route ro; /* XXX check this */
2056
2057	imo.imo_multicast_ifp  = vifp->v_ifp;
2058	imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
2059	imo.imo_multicast_loop = 1;
2060	imo.imo_multicast_vif  = -1;
2061
2062	/*
2063	 * Re-entrancy should not be a problem here, because
2064	 * the packets that we send out and are looped back at us
2065	 * should get rejected because they appear to come from
2066	 * the loopback interface, thus preventing looping.
2067	 */
2068	error = ip_output(m, NULL, &ro, IP_FORWARDING, &imo, NULL);
2069
2070	if (mrtdebug & DEBUG_XMIT)
2071	    log(LOG_DEBUG, "phyint_send on vif %d err %d\n",
2072		(int)(vifp - viftable), error);
2073    }
2074}
2075
2076/* determine the current time and then
2077 * the elapsed time (between the last time and time now)
2078 * in milliseconds & update the no. of tokens in the bucket
2079 */
2080static void
2081tbf_update_tokens(struct vif *vifp)
2082{
2083    struct timeval tp;
2084    u_long tm;
2085    struct tbf *t = vifp->v_tbf;
2086
2087    VIF_LOCK_ASSERT();
2088
2089    GET_TIME(tp);
2090
2091    TV_DELTA(tp, t->tbf_last_pkt_t, tm);
2092
2093    /*
2094     * This formula is actually
2095     * "time in seconds" * "bytes/second".
2096     *
2097     * (tm / 1000000) * (v_rate_limit * 1000 * (1000/1024) / 8)
2098     *
2099     * The (1000/1024) was introduced in add_vif to optimize
2100     * this divide into a shift.
2101     */
2102    t->tbf_n_tok += tm * vifp->v_rate_limit / 1024 / 8;
2103    t->tbf_last_pkt_t = tp;
2104
2105    if (t->tbf_n_tok > MAX_BKT_SIZE)
2106	t->tbf_n_tok = MAX_BKT_SIZE;
2107}
2108
2109static int
2110priority(struct vif *vifp, struct ip *ip)
2111{
2112    int prio = 50; /* the lowest priority -- default case */
2113
2114    /* temporary hack; may add general packet classifier some day */
2115
2116    /*
2117     * The UDP port space is divided up into four priority ranges:
2118     * [0, 16384)     : unclassified - lowest priority
2119     * [16384, 32768) : audio - highest priority
2120     * [32768, 49152) : whiteboard - medium priority
2121     * [49152, 65536) : video - low priority
2122     *
2123     * Everything else gets lowest priority.
2124     */
2125    if (ip->ip_p == IPPROTO_UDP) {
2126	struct udphdr *udp = (struct udphdr *)(((char *)ip) + (ip->ip_hl << 2));
2127	switch (ntohs(udp->uh_dport) & 0xc000) {
2128	case 0x4000:
2129	    prio = 70;
2130	    break;
2131	case 0x8000:
2132	    prio = 60;
2133	    break;
2134	case 0xc000:
2135	    prio = 55;
2136	    break;
2137	}
2138    }
2139    return prio;
2140}
2141
2142/*
2143 * End of token bucket filter modifications
2144 */
2145
2146static int
2147X_ip_rsvp_vif(struct socket *so, struct sockopt *sopt)
2148{
2149    int error, vifi;
2150
2151    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
2152	return EOPNOTSUPP;
2153
2154    error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
2155    if (error)
2156	return error;
2157
2158    VIF_LOCK();
2159
2160    if (vifi < 0 || vifi >= numvifs) {	/* Error if vif is invalid */
2161	VIF_UNLOCK();
2162	return EADDRNOTAVAIL;
2163    }
2164
2165    if (sopt->sopt_name == IP_RSVP_VIF_ON) {
2166	/* Check if socket is available. */
2167	if (viftable[vifi].v_rsvpd != NULL) {
2168	    VIF_UNLOCK();
2169	    return EADDRINUSE;
2170	}
2171
2172	viftable[vifi].v_rsvpd = so;
2173	/* This may seem silly, but we need to be sure we don't over-increment
2174	 * the RSVP counter, in case something slips up.
2175	 */
2176	if (!viftable[vifi].v_rsvp_on) {
2177	    viftable[vifi].v_rsvp_on = 1;
2178	    rsvp_on++;
2179	}
2180    } else { /* must be VIF_OFF */
2181	/*
2182	 * XXX as an additional consistency check, one could make sure
2183	 * that viftable[vifi].v_rsvpd == so, otherwise passing so as
2184	 * first parameter is pretty useless.
2185	 */
2186	viftable[vifi].v_rsvpd = NULL;
2187	/*
2188	 * This may seem silly, but we need to be sure we don't over-decrement
2189	 * the RSVP counter, in case something slips up.
2190	 */
2191	if (viftable[vifi].v_rsvp_on) {
2192	    viftable[vifi].v_rsvp_on = 0;
2193	    rsvp_on--;
2194	}
2195    }
2196    VIF_UNLOCK();
2197    return 0;
2198}
2199
2200static void
2201X_ip_rsvp_force_done(struct socket *so)
2202{
2203    int vifi;
2204
2205    /* Don't bother if it is not the right type of socket. */
2206    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
2207	return;
2208
2209    VIF_LOCK();
2210
2211    /* The socket may be attached to more than one vif...this
2212     * is perfectly legal.
2213     */
2214    for (vifi = 0; vifi < numvifs; vifi++) {
2215	if (viftable[vifi].v_rsvpd == so) {
2216	    viftable[vifi].v_rsvpd = NULL;
2217	    /* This may seem silly, but we need to be sure we don't
2218	     * over-decrement the RSVP counter, in case something slips up.
2219	     */
2220	    if (viftable[vifi].v_rsvp_on) {
2221		viftable[vifi].v_rsvp_on = 0;
2222		rsvp_on--;
2223	    }
2224	}
2225    }
2226
2227    VIF_UNLOCK();
2228}
2229
2230static void
2231X_rsvp_input(struct mbuf *m, int off)
2232{
2233    int vifi;
2234    struct ip *ip = mtod(m, struct ip *);
2235    struct sockaddr_in rsvp_src = { sizeof rsvp_src, AF_INET };
2236    struct ifnet *ifp;
2237
2238    if (rsvpdebug)
2239	printf("rsvp_input: rsvp_on %d\n",rsvp_on);
2240
2241    /* Can still get packets with rsvp_on = 0 if there is a local member
2242     * of the group to which the RSVP packet is addressed.  But in this
2243     * case we want to throw the packet away.
2244     */
2245    if (!rsvp_on) {
2246	m_freem(m);
2247	return;
2248    }
2249
2250    if (rsvpdebug)
2251	printf("rsvp_input: check vifs\n");
2252
2253#ifdef DIAGNOSTIC
2254    M_ASSERTPKTHDR(m);
2255#endif
2256
2257    ifp = m->m_pkthdr.rcvif;
2258
2259    VIF_LOCK();
2260    /* Find which vif the packet arrived on. */
2261    for (vifi = 0; vifi < numvifs; vifi++)
2262	if (viftable[vifi].v_ifp == ifp)
2263	    break;
2264
2265    if (vifi == numvifs || viftable[vifi].v_rsvpd == NULL) {
2266	/*
2267	 * Drop the lock here to avoid holding it across rip_input.
2268	 * This could make rsvpdebug printfs wrong.  If you care,
2269	 * record the state of stuff before dropping the lock.
2270	 */
2271	VIF_UNLOCK();
2272	/*
2273	 * If the old-style non-vif-associated socket is set,
2274	 * then use it.  Otherwise, drop packet since there
2275	 * is no specific socket for this vif.
2276	 */
2277	if (ip_rsvpd != NULL) {
2278	    if (rsvpdebug)
2279		printf("rsvp_input: Sending packet up old-style socket\n");
2280	    rip_input(m, off);  /* xxx */
2281	} else {
2282	    if (rsvpdebug && vifi == numvifs)
2283		printf("rsvp_input: Can't find vif for packet.\n");
2284	    else if (rsvpdebug && viftable[vifi].v_rsvpd == NULL)
2285		printf("rsvp_input: No socket defined for vif %d\n",vifi);
2286	    m_freem(m);
2287	}
2288	return;
2289    }
2290    rsvp_src.sin_addr = ip->ip_src;
2291
2292    if (rsvpdebug && m)
2293	printf("rsvp_input: m->m_len = %d, sbspace() = %ld\n",
2294	       m->m_len,sbspace(&(viftable[vifi].v_rsvpd->so_rcv)));
2295
2296    if (socket_send(viftable[vifi].v_rsvpd, m, &rsvp_src) < 0) {
2297	if (rsvpdebug)
2298	    printf("rsvp_input: Failed to append to socket\n");
2299    } else {
2300	if (rsvpdebug)
2301	    printf("rsvp_input: send packet up\n");
2302    }
2303    VIF_UNLOCK();
2304}
2305
2306/*
2307 * Code for bandwidth monitors
2308 */
2309
2310/*
2311 * Define common interface for timeval-related methods
2312 */
2313#define	BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
2314#define	BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
2315#define	BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
2316
2317static uint32_t
2318compute_bw_meter_flags(struct bw_upcall *req)
2319{
2320    uint32_t flags = 0;
2321
2322    if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
2323	flags |= BW_METER_UNIT_PACKETS;
2324    if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
2325	flags |= BW_METER_UNIT_BYTES;
2326    if (req->bu_flags & BW_UPCALL_GEQ)
2327	flags |= BW_METER_GEQ;
2328    if (req->bu_flags & BW_UPCALL_LEQ)
2329	flags |= BW_METER_LEQ;
2330
2331    return flags;
2332}
2333
2334/*
2335 * Add a bw_meter entry
2336 */
2337static int
2338add_bw_upcall(struct bw_upcall *req)
2339{
2340    struct mfc *mfc;
2341    struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
2342		BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
2343    struct timeval now;
2344    struct bw_meter *x;
2345    uint32_t flags;
2346
2347    if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2348	return EOPNOTSUPP;
2349
2350    /* Test if the flags are valid */
2351    if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
2352	return EINVAL;
2353    if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
2354	return EINVAL;
2355    if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2356	    == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2357	return EINVAL;
2358
2359    /* Test if the threshold time interval is valid */
2360    if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
2361	return EINVAL;
2362
2363    flags = compute_bw_meter_flags(req);
2364
2365    /*
2366     * Find if we have already same bw_meter entry
2367     */
2368    MFC_LOCK();
2369    mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2370    if (mfc == NULL) {
2371	MFC_UNLOCK();
2372	return EADDRNOTAVAIL;
2373    }
2374    for (x = mfc->mfc_bw_meter; x != NULL; x = x->bm_mfc_next) {
2375	if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2376			   &req->bu_threshold.b_time, ==)) &&
2377	    (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2378	    (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2379	    (x->bm_flags & BW_METER_USER_FLAGS) == flags)  {
2380	    MFC_UNLOCK();
2381	    return 0;		/* XXX Already installed */
2382	}
2383    }
2384
2385    /* Allocate the new bw_meter entry */
2386    x = (struct bw_meter *)malloc(sizeof(*x), M_BWMETER, M_NOWAIT);
2387    if (x == NULL) {
2388	MFC_UNLOCK();
2389	return ENOBUFS;
2390    }
2391
2392    /* Set the new bw_meter entry */
2393    x->bm_threshold.b_time = req->bu_threshold.b_time;
2394    GET_TIME(now);
2395    x->bm_start_time = now;
2396    x->bm_threshold.b_packets = req->bu_threshold.b_packets;
2397    x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
2398    x->bm_measured.b_packets = 0;
2399    x->bm_measured.b_bytes = 0;
2400    x->bm_flags = flags;
2401    x->bm_time_next = NULL;
2402    x->bm_time_hash = BW_METER_BUCKETS;
2403
2404    /* Add the new bw_meter entry to the front of entries for this MFC */
2405    x->bm_mfc = mfc;
2406    x->bm_mfc_next = mfc->mfc_bw_meter;
2407    mfc->mfc_bw_meter = x;
2408    schedule_bw_meter(x, &now);
2409    MFC_UNLOCK();
2410
2411    return 0;
2412}
2413
2414static void
2415free_bw_list(struct bw_meter *list)
2416{
2417    while (list != NULL) {
2418	struct bw_meter *x = list;
2419
2420	list = list->bm_mfc_next;
2421	unschedule_bw_meter(x);
2422	free(x, M_BWMETER);
2423    }
2424}
2425
2426/*
2427 * Delete one or multiple bw_meter entries
2428 */
2429static int
2430del_bw_upcall(struct bw_upcall *req)
2431{
2432    struct mfc *mfc;
2433    struct bw_meter *x;
2434
2435    if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2436	return EOPNOTSUPP;
2437
2438    MFC_LOCK();
2439    /* Find the corresponding MFC entry */
2440    mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2441    if (mfc == NULL) {
2442	MFC_UNLOCK();
2443	return EADDRNOTAVAIL;
2444    } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2445	/*
2446	 * Delete all bw_meter entries for this mfc
2447	 */
2448	struct bw_meter *list;
2449
2450	list = mfc->mfc_bw_meter;
2451	mfc->mfc_bw_meter = NULL;
2452	free_bw_list(list);
2453	MFC_UNLOCK();
2454	return 0;
2455    } else {			/* Delete a single bw_meter entry */
2456	struct bw_meter *prev;
2457	uint32_t flags = 0;
2458
2459	flags = compute_bw_meter_flags(req);
2460
2461	/* Find the bw_meter entry to delete */
2462	for (prev = NULL, x = mfc->mfc_bw_meter; x != NULL;
2463	     x = x->bm_mfc_next) {
2464	    if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2465			       &req->bu_threshold.b_time, ==)) &&
2466		(x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2467		(x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2468		(x->bm_flags & BW_METER_USER_FLAGS) == flags)
2469		break;
2470	}
2471	if (x != NULL) { /* Delete entry from the list for this MFC */
2472	    if (prev != NULL)
2473		prev->bm_mfc_next = x->bm_mfc_next;	/* remove from middle*/
2474	    else
2475		x->bm_mfc->mfc_bw_meter = x->bm_mfc_next;/* new head of list */
2476
2477	    unschedule_bw_meter(x);
2478	    MFC_UNLOCK();
2479	    /* Free the bw_meter entry */
2480	    free(x, M_BWMETER);
2481	    return 0;
2482	} else {
2483	    MFC_UNLOCK();
2484	    return EINVAL;
2485	}
2486    }
2487    /* NOTREACHED */
2488}
2489
2490/*
2491 * Perform bandwidth measurement processing that may result in an upcall
2492 */
2493static void
2494bw_meter_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2495{
2496    struct timeval delta;
2497
2498    MFC_LOCK_ASSERT();
2499
2500    delta = *nowp;
2501    BW_TIMEVALDECR(&delta, &x->bm_start_time);
2502
2503    if (x->bm_flags & BW_METER_GEQ) {
2504	/*
2505	 * Processing for ">=" type of bw_meter entry
2506	 */
2507	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2508	    /* Reset the bw_meter entry */
2509	    x->bm_start_time = *nowp;
2510	    x->bm_measured.b_packets = 0;
2511	    x->bm_measured.b_bytes = 0;
2512	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2513	}
2514
2515	/* Record that a packet is received */
2516	x->bm_measured.b_packets++;
2517	x->bm_measured.b_bytes += plen;
2518
2519	/*
2520	 * Test if we should deliver an upcall
2521	 */
2522	if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2523	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2524		 (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2525		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2526		 (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2527		/* Prepare an upcall for delivery */
2528		bw_meter_prepare_upcall(x, nowp);
2529		x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2530	    }
2531	}
2532    } else if (x->bm_flags & BW_METER_LEQ) {
2533	/*
2534	 * Processing for "<=" type of bw_meter entry
2535	 */
2536	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2537	    /*
2538	     * We are behind time with the multicast forwarding table
2539	     * scanning for "<=" type of bw_meter entries, so test now
2540	     * if we should deliver an upcall.
2541	     */
2542	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2543		 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2544		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2545		 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2546		/* Prepare an upcall for delivery */
2547		bw_meter_prepare_upcall(x, nowp);
2548	    }
2549	    /* Reschedule the bw_meter entry */
2550	    unschedule_bw_meter(x);
2551	    schedule_bw_meter(x, nowp);
2552	}
2553
2554	/* Record that a packet is received */
2555	x->bm_measured.b_packets++;
2556	x->bm_measured.b_bytes += plen;
2557
2558	/*
2559	 * Test if we should restart the measuring interval
2560	 */
2561	if ((x->bm_flags & BW_METER_UNIT_PACKETS &&
2562	     x->bm_measured.b_packets <= x->bm_threshold.b_packets) ||
2563	    (x->bm_flags & BW_METER_UNIT_BYTES &&
2564	     x->bm_measured.b_bytes <= x->bm_threshold.b_bytes)) {
2565	    /* Don't restart the measuring interval */
2566	} else {
2567	    /* Do restart the measuring interval */
2568	    /*
2569	     * XXX: note that we don't unschedule and schedule, because this
2570	     * might be too much overhead per packet. Instead, when we process
2571	     * all entries for a given timer hash bin, we check whether it is
2572	     * really a timeout. If not, we reschedule at that time.
2573	     */
2574	    x->bm_start_time = *nowp;
2575	    x->bm_measured.b_packets = 0;
2576	    x->bm_measured.b_bytes = 0;
2577	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2578	}
2579    }
2580}
2581
2582/*
2583 * Prepare a bandwidth-related upcall
2584 */
2585static void
2586bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2587{
2588    struct timeval delta;
2589    struct bw_upcall *u;
2590
2591    MFC_LOCK_ASSERT();
2592
2593    /*
2594     * Compute the measured time interval
2595     */
2596    delta = *nowp;
2597    BW_TIMEVALDECR(&delta, &x->bm_start_time);
2598
2599    /*
2600     * If there are too many pending upcalls, deliver them now
2601     */
2602    if (bw_upcalls_n >= BW_UPCALLS_MAX)
2603	bw_upcalls_send();
2604
2605    /*
2606     * Set the bw_upcall entry
2607     */
2608    u = &bw_upcalls[bw_upcalls_n++];
2609    u->bu_src = x->bm_mfc->mfc_origin;
2610    u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2611    u->bu_threshold.b_time = x->bm_threshold.b_time;
2612    u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2613    u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2614    u->bu_measured.b_time = delta;
2615    u->bu_measured.b_packets = x->bm_measured.b_packets;
2616    u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2617    u->bu_flags = 0;
2618    if (x->bm_flags & BW_METER_UNIT_PACKETS)
2619	u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2620    if (x->bm_flags & BW_METER_UNIT_BYTES)
2621	u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2622    if (x->bm_flags & BW_METER_GEQ)
2623	u->bu_flags |= BW_UPCALL_GEQ;
2624    if (x->bm_flags & BW_METER_LEQ)
2625	u->bu_flags |= BW_UPCALL_LEQ;
2626}
2627
2628/*
2629 * Send the pending bandwidth-related upcalls
2630 */
2631static void
2632bw_upcalls_send(void)
2633{
2634    struct mbuf *m;
2635    int len = bw_upcalls_n * sizeof(bw_upcalls[0]);
2636    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2637    static struct igmpmsg igmpmsg = { 0,		/* unused1 */
2638				      0,		/* unused2 */
2639				      IGMPMSG_BW_UPCALL,/* im_msgtype */
2640				      0,		/* im_mbz  */
2641				      0,		/* im_vif  */
2642				      0,		/* unused3 */
2643				      { 0 },		/* im_src  */
2644				      { 0 } };		/* im_dst  */
2645
2646    MFC_LOCK_ASSERT();
2647
2648    if (bw_upcalls_n == 0)
2649	return;			/* No pending upcalls */
2650
2651    bw_upcalls_n = 0;
2652
2653    /*
2654     * Allocate a new mbuf, initialize it with the header and
2655     * the payload for the pending calls.
2656     */
2657    MGETHDR(m, M_DONTWAIT, MT_HEADER);
2658    if (m == NULL) {
2659	log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2660	return;
2661    }
2662
2663    m->m_len = m->m_pkthdr.len = 0;
2664    m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2665    m_copyback(m, sizeof(struct igmpmsg), len, (caddr_t)&bw_upcalls[0]);
2666
2667    /*
2668     * Send the upcalls
2669     * XXX do we need to set the address in k_igmpsrc ?
2670     */
2671    mrtstat.mrts_upcalls++;
2672    if (socket_send(ip_mrouter, m, &k_igmpsrc) < 0) {
2673	log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2674	++mrtstat.mrts_upq_sockfull;
2675    }
2676}
2677
2678/*
2679 * Compute the timeout hash value for the bw_meter entries
2680 */
2681#define	BW_METER_TIMEHASH(bw_meter, hash)				\
2682    do {								\
2683	struct timeval next_timeval = (bw_meter)->bm_start_time;	\
2684									\
2685	BW_TIMEVALADD(&next_timeval, &(bw_meter)->bm_threshold.b_time); \
2686	(hash) = next_timeval.tv_sec;					\
2687	if (next_timeval.tv_usec)					\
2688	    (hash)++; /* XXX: make sure we don't timeout early */	\
2689	(hash) %= BW_METER_BUCKETS;					\
2690    } while (0)
2691
2692/*
2693 * Schedule a timer to process periodically bw_meter entry of type "<="
2694 * by linking the entry in the proper hash bucket.
2695 */
2696static void
2697schedule_bw_meter(struct bw_meter *x, struct timeval *nowp)
2698{
2699    int time_hash;
2700
2701    MFC_LOCK_ASSERT();
2702
2703    if (!(x->bm_flags & BW_METER_LEQ))
2704	return;		/* XXX: we schedule timers only for "<=" entries */
2705
2706    /*
2707     * Reset the bw_meter entry
2708     */
2709    x->bm_start_time = *nowp;
2710    x->bm_measured.b_packets = 0;
2711    x->bm_measured.b_bytes = 0;
2712    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2713
2714    /*
2715     * Compute the timeout hash value and insert the entry
2716     */
2717    BW_METER_TIMEHASH(x, time_hash);
2718    x->bm_time_next = bw_meter_timers[time_hash];
2719    bw_meter_timers[time_hash] = x;
2720    x->bm_time_hash = time_hash;
2721}
2722
2723/*
2724 * Unschedule the periodic timer that processes bw_meter entry of type "<="
2725 * by removing the entry from the proper hash bucket.
2726 */
2727static void
2728unschedule_bw_meter(struct bw_meter *x)
2729{
2730    int time_hash;
2731    struct bw_meter *prev, *tmp;
2732
2733    MFC_LOCK_ASSERT();
2734
2735    if (!(x->bm_flags & BW_METER_LEQ))
2736	return;		/* XXX: we schedule timers only for "<=" entries */
2737
2738    /*
2739     * Compute the timeout hash value and delete the entry
2740     */
2741    time_hash = x->bm_time_hash;
2742    if (time_hash >= BW_METER_BUCKETS)
2743	return;		/* Entry was not scheduled */
2744
2745    for (prev = NULL, tmp = bw_meter_timers[time_hash];
2746	     tmp != NULL; prev = tmp, tmp = tmp->bm_time_next)
2747	if (tmp == x)
2748	    break;
2749
2750    if (tmp == NULL)
2751	panic("unschedule_bw_meter: bw_meter entry not found");
2752
2753    if (prev != NULL)
2754	prev->bm_time_next = x->bm_time_next;
2755    else
2756	bw_meter_timers[time_hash] = x->bm_time_next;
2757
2758    x->bm_time_next = NULL;
2759    x->bm_time_hash = BW_METER_BUCKETS;
2760}
2761
2762
2763/*
2764 * Process all "<=" type of bw_meter that should be processed now,
2765 * and for each entry prepare an upcall if necessary. Each processed
2766 * entry is rescheduled again for the (periodic) processing.
2767 *
2768 * This is run periodically (once per second normally). On each round,
2769 * all the potentially matching entries are in the hash slot that we are
2770 * looking at.
2771 */
2772static void
2773bw_meter_process()
2774{
2775    static uint32_t last_tv_sec;	/* last time we processed this */
2776
2777    uint32_t loops;
2778    int i;
2779    struct timeval now, process_endtime;
2780
2781    GET_TIME(now);
2782    if (last_tv_sec == now.tv_sec)
2783	return;		/* nothing to do */
2784
2785    loops = now.tv_sec - last_tv_sec;
2786    last_tv_sec = now.tv_sec;
2787    if (loops > BW_METER_BUCKETS)
2788	loops = BW_METER_BUCKETS;
2789
2790    MFC_LOCK();
2791    /*
2792     * Process all bins of bw_meter entries from the one after the last
2793     * processed to the current one. On entry, i points to the last bucket
2794     * visited, so we need to increment i at the beginning of the loop.
2795     */
2796    for (i = (now.tv_sec - loops) % BW_METER_BUCKETS; loops > 0; loops--) {
2797	struct bw_meter *x, *tmp_list;
2798
2799	if (++i >= BW_METER_BUCKETS)
2800	    i = 0;
2801
2802	/* Disconnect the list of bw_meter entries from the bin */
2803	tmp_list = bw_meter_timers[i];
2804	bw_meter_timers[i] = NULL;
2805
2806	/* Process the list of bw_meter entries */
2807	while (tmp_list != NULL) {
2808	    x = tmp_list;
2809	    tmp_list = tmp_list->bm_time_next;
2810
2811	    /* Test if the time interval is over */
2812	    process_endtime = x->bm_start_time;
2813	    BW_TIMEVALADD(&process_endtime, &x->bm_threshold.b_time);
2814	    if (BW_TIMEVALCMP(&process_endtime, &now, >)) {
2815		/* Not yet: reschedule, but don't reset */
2816		int time_hash;
2817
2818		BW_METER_TIMEHASH(x, time_hash);
2819		if (time_hash == i && process_endtime.tv_sec == now.tv_sec) {
2820		    /*
2821		     * XXX: somehow the bin processing is a bit ahead of time.
2822		     * Put the entry in the next bin.
2823		     */
2824		    if (++time_hash >= BW_METER_BUCKETS)
2825			time_hash = 0;
2826		}
2827		x->bm_time_next = bw_meter_timers[time_hash];
2828		bw_meter_timers[time_hash] = x;
2829		x->bm_time_hash = time_hash;
2830
2831		continue;
2832	    }
2833
2834	    /*
2835	     * Test if we should deliver an upcall
2836	     */
2837	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2838		 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2839		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2840		 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2841		/* Prepare an upcall for delivery */
2842		bw_meter_prepare_upcall(x, &now);
2843	    }
2844
2845	    /*
2846	     * Reschedule for next processing
2847	     */
2848	    schedule_bw_meter(x, &now);
2849	}
2850    }
2851
2852    /* Send all upcalls that are pending delivery */
2853    bw_upcalls_send();
2854
2855    MFC_UNLOCK();
2856}
2857
2858/*
2859 * A periodic function for sending all upcalls that are pending delivery
2860 */
2861static void
2862expire_bw_upcalls_send(void *unused)
2863{
2864    MFC_LOCK();
2865    bw_upcalls_send();
2866    MFC_UNLOCK();
2867
2868    callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
2869	expire_bw_upcalls_send, NULL);
2870}
2871
2872/*
2873 * A periodic function for periodic scanning of the multicast forwarding
2874 * table for processing all "<=" bw_meter entries.
2875 */
2876static void
2877expire_bw_meter_process(void *unused)
2878{
2879    if (mrt_api_config & MRT_MFC_BW_UPCALL)
2880	bw_meter_process();
2881
2882    callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
2883}
2884
2885/*
2886 * End of bandwidth monitoring code
2887 */
2888
2889#ifdef PIM
2890/*
2891 * Send the packet up to the user daemon, or eventually do kernel encapsulation
2892 *
2893 */
2894static int
2895pim_register_send(struct ip *ip, struct vif *vifp,
2896	struct mbuf *m, struct mfc *rt)
2897{
2898    struct mbuf *mb_copy, *mm;
2899
2900    if (mrtdebug & DEBUG_PIM)
2901        log(LOG_DEBUG, "pim_register_send: ");
2902
2903    mb_copy = pim_register_prepare(ip, m);
2904    if (mb_copy == NULL)
2905	return ENOBUFS;
2906
2907    /*
2908     * Send all the fragments. Note that the mbuf for each fragment
2909     * is freed by the sending machinery.
2910     */
2911    for (mm = mb_copy; mm; mm = mb_copy) {
2912	mb_copy = mm->m_nextpkt;
2913	mm->m_nextpkt = 0;
2914	mm = m_pullup(mm, sizeof(struct ip));
2915	if (mm != NULL) {
2916	    ip = mtod(mm, struct ip *);
2917	    if ((mrt_api_config & MRT_MFC_RP) &&
2918		(rt->mfc_rp.s_addr != INADDR_ANY)) {
2919		pim_register_send_rp(ip, vifp, mm, rt);
2920	    } else {
2921		pim_register_send_upcall(ip, vifp, mm, rt);
2922	    }
2923	}
2924    }
2925
2926    return 0;
2927}
2928
2929/*
2930 * Return a copy of the data packet that is ready for PIM Register
2931 * encapsulation.
2932 * XXX: Note that in the returned copy the IP header is a valid one.
2933 */
2934static struct mbuf *
2935pim_register_prepare(struct ip *ip, struct mbuf *m)
2936{
2937    struct mbuf *mb_copy = NULL;
2938    int mtu;
2939
2940    /* Take care of delayed checksums */
2941    if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2942	in_delayed_cksum(m);
2943	m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2944    }
2945
2946    /*
2947     * Copy the old packet & pullup its IP header into the
2948     * new mbuf so we can modify it.
2949     */
2950    mb_copy = m_copypacket(m, M_DONTWAIT);
2951    if (mb_copy == NULL)
2952	return NULL;
2953    mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2954    if (mb_copy == NULL)
2955	return NULL;
2956
2957    /* take care of the TTL */
2958    ip = mtod(mb_copy, struct ip *);
2959    --ip->ip_ttl;
2960
2961    /* Compute the MTU after the PIM Register encapsulation */
2962    mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2963
2964    if (ip->ip_len <= mtu) {
2965	/* Turn the IP header into a valid one */
2966	ip->ip_len = htons(ip->ip_len);
2967	ip->ip_off = htons(ip->ip_off);
2968	ip->ip_sum = 0;
2969	ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2970    } else {
2971	/* Fragment the packet */
2972	if (ip_fragment(ip, &mb_copy, mtu, 0, CSUM_DELAY_IP) != 0) {
2973	    m_freem(mb_copy);
2974	    return NULL;
2975	}
2976    }
2977    return mb_copy;
2978}
2979
2980/*
2981 * Send an upcall with the data packet to the user-level process.
2982 */
2983static int
2984pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2985	struct mbuf *mb_copy, struct mfc *rt)
2986{
2987    struct mbuf *mb_first;
2988    int len = ntohs(ip->ip_len);
2989    struct igmpmsg *im;
2990    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2991
2992    VIF_LOCK_ASSERT();
2993
2994    /*
2995     * Add a new mbuf with an upcall header
2996     */
2997    MGETHDR(mb_first, M_DONTWAIT, MT_HEADER);
2998    if (mb_first == NULL) {
2999	m_freem(mb_copy);
3000	return ENOBUFS;
3001    }
3002    mb_first->m_data += max_linkhdr;
3003    mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
3004    mb_first->m_len = sizeof(struct igmpmsg);
3005    mb_first->m_next = mb_copy;
3006
3007    /* Send message to routing daemon */
3008    im = mtod(mb_first, struct igmpmsg *);
3009    im->im_msgtype	= IGMPMSG_WHOLEPKT;
3010    im->im_mbz		= 0;
3011    im->im_vif		= vifp - viftable;
3012    im->im_src		= ip->ip_src;
3013    im->im_dst		= ip->ip_dst;
3014
3015    k_igmpsrc.sin_addr	= ip->ip_src;
3016
3017    mrtstat.mrts_upcalls++;
3018
3019    if (socket_send(ip_mrouter, mb_first, &k_igmpsrc) < 0) {
3020	if (mrtdebug & DEBUG_PIM)
3021	    log(LOG_WARNING,
3022		"mcast: pim_register_send_upcall: ip_mrouter socket queue full");
3023	++mrtstat.mrts_upq_sockfull;
3024	return ENOBUFS;
3025    }
3026
3027    /* Keep statistics */
3028    pimstat.pims_snd_registers_msgs++;
3029    pimstat.pims_snd_registers_bytes += len;
3030
3031    return 0;
3032}
3033
3034/*
3035 * Encapsulate the data packet in PIM Register message and send it to the RP.
3036 */
3037static int
3038pim_register_send_rp(struct ip *ip, struct vif *vifp,
3039	struct mbuf *mb_copy, struct mfc *rt)
3040{
3041    struct mbuf *mb_first;
3042    struct ip *ip_outer;
3043    struct pim_encap_pimhdr *pimhdr;
3044    int len = ntohs(ip->ip_len);
3045    vifi_t vifi = rt->mfc_parent;
3046
3047    VIF_LOCK_ASSERT();
3048
3049    if ((vifi >= numvifs) || (viftable[vifi].v_lcl_addr.s_addr == 0)) {
3050	m_freem(mb_copy);
3051	return EADDRNOTAVAIL;		/* The iif vif is invalid */
3052    }
3053
3054    /*
3055     * Add a new mbuf with the encapsulating header
3056     */
3057    MGETHDR(mb_first, M_DONTWAIT, MT_HEADER);
3058    if (mb_first == NULL) {
3059	m_freem(mb_copy);
3060	return ENOBUFS;
3061    }
3062    mb_first->m_data += max_linkhdr;
3063    mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
3064    mb_first->m_next = mb_copy;
3065
3066    mb_first->m_pkthdr.len = len + mb_first->m_len;
3067
3068    /*
3069     * Fill in the encapsulating IP and PIM header
3070     */
3071    ip_outer = mtod(mb_first, struct ip *);
3072    *ip_outer = pim_encap_iphdr;
3073#ifdef RANDOM_IP_ID
3074    ip_outer->ip_id = ip_randomid();
3075#else
3076    ip_outer->ip_id = htons(ip_id++);
3077#endif
3078    ip_outer->ip_len = len + sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
3079    ip_outer->ip_src = viftable[vifi].v_lcl_addr;
3080    ip_outer->ip_dst = rt->mfc_rp;
3081    /*
3082     * Copy the inner header TOS to the outer header, and take care of the
3083     * IP_DF bit.
3084     */
3085    ip_outer->ip_tos = ip->ip_tos;
3086    if (ntohs(ip->ip_off) & IP_DF)
3087	ip_outer->ip_off |= IP_DF;
3088    pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
3089					 + sizeof(pim_encap_iphdr));
3090    *pimhdr = pim_encap_pimhdr;
3091    /* If the iif crosses a border, set the Border-bit */
3092    if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & mrt_api_config)
3093	pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
3094
3095    mb_first->m_data += sizeof(pim_encap_iphdr);
3096    pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
3097    mb_first->m_data -= sizeof(pim_encap_iphdr);
3098
3099    if (vifp->v_rate_limit == 0)
3100	tbf_send_packet(vifp, mb_first);
3101    else
3102	tbf_control(vifp, mb_first, ip, ip_outer->ip_len);
3103
3104    /* Keep statistics */
3105    pimstat.pims_snd_registers_msgs++;
3106    pimstat.pims_snd_registers_bytes += len;
3107
3108    return 0;
3109}
3110
3111/*
3112 * PIM-SMv2 and PIM-DM messages processing.
3113 * Receives and verifies the PIM control messages, and passes them
3114 * up to the listening socket, using rip_input().
3115 * The only message with special processing is the PIM_REGISTER message
3116 * (used by PIM-SM): the PIM header is stripped off, and the inner packet
3117 * is passed to if_simloop().
3118 */
3119void
3120pim_input(struct mbuf *m, int off)
3121{
3122    struct ip *ip = mtod(m, struct ip *);
3123    struct pim *pim;
3124    int minlen;
3125    int datalen = ip->ip_len;
3126    int ip_tos;
3127    int iphlen = off;
3128
3129    /* Keep statistics */
3130    pimstat.pims_rcv_total_msgs++;
3131    pimstat.pims_rcv_total_bytes += datalen;
3132
3133    /*
3134     * Validate lengths
3135     */
3136    if (datalen < PIM_MINLEN) {
3137	pimstat.pims_rcv_tooshort++;
3138	log(LOG_ERR, "pim_input: packet size too small %d from %lx\n",
3139	    datalen, (u_long)ip->ip_src.s_addr);
3140	m_freem(m);
3141	return;
3142    }
3143
3144    /*
3145     * If the packet is at least as big as a REGISTER, go agead
3146     * and grab the PIM REGISTER header size, to avoid another
3147     * possible m_pullup() later.
3148     *
3149     * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
3150     * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
3151     */
3152    minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
3153    /*
3154     * Get the IP and PIM headers in contiguous memory, and
3155     * possibly the PIM REGISTER header.
3156     */
3157    if ((m->m_flags & M_EXT || m->m_len < minlen) &&
3158	(m = m_pullup(m, minlen)) == 0) {
3159	log(LOG_ERR, "pim_input: m_pullup failure\n");
3160	return;
3161    }
3162    /* m_pullup() may have given us a new mbuf so reset ip. */
3163    ip = mtod(m, struct ip *);
3164    ip_tos = ip->ip_tos;
3165
3166    /* adjust mbuf to point to the PIM header */
3167    m->m_data += iphlen;
3168    m->m_len  -= iphlen;
3169    pim = mtod(m, struct pim *);
3170
3171    /*
3172     * Validate checksum. If PIM REGISTER, exclude the data packet.
3173     *
3174     * XXX: some older PIMv2 implementations don't make this distinction,
3175     * so for compatibility reason perform the checksum over part of the
3176     * message, and if error, then over the whole message.
3177     */
3178    if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
3179	/* do nothing, checksum okay */
3180    } else if (in_cksum(m, datalen)) {
3181	pimstat.pims_rcv_badsum++;
3182	if (mrtdebug & DEBUG_PIM)
3183	    log(LOG_DEBUG, "pim_input: invalid checksum");
3184	m_freem(m);
3185	return;
3186    }
3187
3188    /* PIM version check */
3189    if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
3190	pimstat.pims_rcv_badversion++;
3191	log(LOG_ERR, "pim_input: incorrect version %d, expecting %d\n",
3192	    PIM_VT_V(pim->pim_vt), PIM_VERSION);
3193	m_freem(m);
3194	return;
3195    }
3196
3197    /* restore mbuf back to the outer IP */
3198    m->m_data -= iphlen;
3199    m->m_len  += iphlen;
3200
3201    if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
3202	/*
3203	 * Since this is a REGISTER, we'll make a copy of the register
3204	 * headers ip + pim + u_int32 + encap_ip, to be passed up to the
3205	 * routing daemon.
3206	 */
3207	struct sockaddr_in dst = { sizeof(dst), AF_INET };
3208	struct mbuf *mcp;
3209	struct ip *encap_ip;
3210	u_int32_t *reghdr;
3211	struct ifnet *vifp;
3212
3213	VIF_LOCK();
3214	if ((reg_vif_num >= numvifs) || (reg_vif_num == VIFI_INVALID)) {
3215	    VIF_UNLOCK();
3216	    if (mrtdebug & DEBUG_PIM)
3217		log(LOG_DEBUG,
3218		    "pim_input: register vif not set: %d\n", reg_vif_num);
3219	    m_freem(m);
3220	    return;
3221	}
3222	/* XXX need refcnt? */
3223	vifp = viftable[reg_vif_num].v_ifp;
3224	VIF_UNLOCK();
3225
3226	/*
3227	 * Validate length
3228	 */
3229	if (datalen < PIM_REG_MINLEN) {
3230	    pimstat.pims_rcv_tooshort++;
3231	    pimstat.pims_rcv_badregisters++;
3232	    log(LOG_ERR,
3233		"pim_input: register packet size too small %d from %lx\n",
3234		datalen, (u_long)ip->ip_src.s_addr);
3235	    m_freem(m);
3236	    return;
3237	}
3238
3239	reghdr = (u_int32_t *)(pim + 1);
3240	encap_ip = (struct ip *)(reghdr + 1);
3241
3242	if (mrtdebug & DEBUG_PIM) {
3243	    log(LOG_DEBUG,
3244		"pim_input[register], encap_ip: %lx -> %lx, encap_ip len %d\n",
3245		(u_long)ntohl(encap_ip->ip_src.s_addr),
3246		(u_long)ntohl(encap_ip->ip_dst.s_addr),
3247		ntohs(encap_ip->ip_len));
3248	}
3249
3250	/* verify the version number of the inner packet */
3251	if (encap_ip->ip_v != IPVERSION) {
3252	    pimstat.pims_rcv_badregisters++;
3253	    if (mrtdebug & DEBUG_PIM) {
3254		log(LOG_DEBUG, "pim_input: invalid IP version (%d) "
3255		    "of the inner packet\n", encap_ip->ip_v);
3256	    }
3257	    m_freem(m);
3258	    return;
3259	}
3260
3261	/* verify the inner packet is destined to a mcast group */
3262	if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
3263	    pimstat.pims_rcv_badregisters++;
3264	    if (mrtdebug & DEBUG_PIM)
3265		log(LOG_DEBUG,
3266		    "pim_input: inner packet of register is not "
3267		    "multicast %lx\n",
3268		    (u_long)ntohl(encap_ip->ip_dst.s_addr));
3269	    m_freem(m);
3270	    return;
3271	}
3272
3273	/*
3274	 * Copy the TOS from the outer IP header to the inner IP header.
3275	 */
3276	if (encap_ip->ip_tos != ip_tos) {
3277	    /* Outer TOS -> inner TOS */
3278	    encap_ip->ip_tos = ip_tos;
3279	    /* Recompute the inner header checksum. Sigh... */
3280
3281	    /* adjust mbuf to point to the inner IP header */
3282	    m->m_data += (iphlen + PIM_MINLEN);
3283	    m->m_len  -= (iphlen + PIM_MINLEN);
3284
3285	    encap_ip->ip_sum = 0;
3286	    encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
3287
3288	    /* restore mbuf to point back to the outer IP header */
3289	    m->m_data -= (iphlen + PIM_MINLEN);
3290	    m->m_len  += (iphlen + PIM_MINLEN);
3291	}
3292
3293	/* If a NULL_REGISTER, pass it to the daemon */
3294	if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
3295	    goto pim_input_to_daemon;
3296
3297	/*
3298	 * Decapsulate the inner IP packet and loopback to forward it
3299	 * as a normal multicast packet. Also, make a copy of the
3300	 *     outer_iphdr + pimhdr + reghdr + encap_iphdr
3301	 * to pass to the daemon later, so it can take the appropriate
3302	 * actions (e.g., send back PIM_REGISTER_STOP).
3303	 * XXX: here m->m_data points to the outer IP header.
3304	 */
3305	mcp = m_copy(m, 0, iphlen + PIM_REG_MINLEN);
3306	if (mcp == NULL) {
3307	    log(LOG_ERR,
3308		"pim_input: pim register: could not copy register head\n");
3309	    m_freem(m);
3310	    return;
3311	}
3312
3313	/* Keep statistics */
3314	/* XXX: registers_bytes include only the encap. mcast pkt */
3315	pimstat.pims_rcv_registers_msgs++;
3316	pimstat.pims_rcv_registers_bytes += ntohs(encap_ip->ip_len);
3317
3318	/*
3319	 * forward the inner ip packet; point m_data at the inner ip.
3320	 */
3321	m_adj(m, iphlen + PIM_MINLEN);
3322
3323	if (mrtdebug & DEBUG_PIM) {
3324	    log(LOG_DEBUG,
3325		"pim_input: forwarding decapsulated register: "
3326		"src %lx, dst %lx, vif %d\n",
3327		(u_long)ntohl(encap_ip->ip_src.s_addr),
3328		(u_long)ntohl(encap_ip->ip_dst.s_addr),
3329		reg_vif_num);
3330	}
3331	/* NB: vifp was collected above; can it change on us? */
3332	if_simloop(vifp, m, dst.sin_family, 0);
3333
3334	/* prepare the register head to send to the mrouting daemon */
3335	m = mcp;
3336    }
3337
3338pim_input_to_daemon:
3339    /*
3340     * Pass the PIM message up to the daemon; if it is a Register message,
3341     * pass the 'head' only up to the daemon. This includes the
3342     * outer IP header, PIM header, PIM-Register header and the
3343     * inner IP header.
3344     * XXX: the outer IP header pkt size of a Register is not adjust to
3345     * reflect the fact that the inner multicast data is truncated.
3346     */
3347    rip_input(m, iphlen);
3348
3349    return;
3350}
3351#endif /* PIM */
3352
3353static int
3354ip_mroute_modevent(module_t mod, int type, void *unused)
3355{
3356    int s;
3357
3358    switch (type) {
3359    case MOD_LOAD:
3360	s = splnet();
3361	ip_mrouter_reset();
3362	/* XXX synchronize setup */
3363	ip_mcast_src = X_ip_mcast_src;
3364	ip_mforward = X_ip_mforward;
3365	ip_mrouter_done = X_ip_mrouter_done;
3366	ip_mrouter_get = X_ip_mrouter_get;
3367	ip_mrouter_set = X_ip_mrouter_set;
3368	ip_rsvp_force_done = X_ip_rsvp_force_done;
3369	ip_rsvp_vif = X_ip_rsvp_vif;
3370	legal_vif_num = X_legal_vif_num;
3371	mrt_ioctl = X_mrt_ioctl;
3372	rsvp_input_p = X_rsvp_input;
3373	break;
3374
3375    case MOD_UNLOAD:
3376	/*
3377	 * Typically module unload happens after the user-level
3378	 * process has shutdown the kernel services (the check
3379	 * below insures someone can't just yank the module out
3380	 * from under a running process).  But if the module is
3381	 * just loaded and then unloaded w/o starting up a user
3382	 * process we still need to cleanup.
3383	 */
3384	if (ip_mrouter)
3385	    return EINVAL;
3386
3387	X_ip_mrouter_done();
3388	ip_mcast_src = NULL;
3389	ip_mforward = NULL;
3390	ip_mrouter_done = NULL;
3391	ip_mrouter_get = NULL;
3392	ip_mrouter_set = NULL;
3393	ip_rsvp_force_done = NULL;
3394	ip_rsvp_vif = NULL;
3395	legal_vif_num = NULL;
3396	mrt_ioctl = NULL;
3397	rsvp_input_p = NULL;
3398	break;
3399    }
3400    return 0;
3401}
3402
3403static moduledata_t ip_mroutemod = {
3404    "ip_mroute",
3405    ip_mroute_modevent,
3406    0
3407};
3408DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PSEUDO, SI_ORDER_ANY);
3409