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