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