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