ip_mroute.c revision 167116
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 167116 2007-02-28 20:02:24Z bms $
56 */
57
58#include "opt_inet.h"
59#include "opt_inet6.h"
60#include "opt_mac.h"
61#include "opt_mrouting.h"
62
63#define _PIM_VT 1
64
65#include <sys/param.h>
66#include <sys/kernel.h>
67#include <sys/lock.h>
68#include <sys/malloc.h>
69#include <sys/mbuf.h>
70#include <sys/module.h>
71#include <sys/priv.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#include <netinet/pim.h>
95#include <netinet/pim_var.h>
96#include <netinet/udp.h>
97#ifdef INET6
98#include <netinet/ip6.h>
99#include <netinet6/in6_var.h>
100#include <netinet6/ip6_mroute.h>
101#include <netinet6/ip6_var.h>
102#endif
103#include <machine/in_cksum.h>
104
105#include <security/mac/mac_framework.h>
106
107/*
108 * Control debugging code for rsvp and multicast routing code.
109 * Can only set them with the debugger.
110 */
111static u_int    rsvpdebug;		/* non-zero enables debugging	*/
112
113static u_int	mrtdebug;		/* any set of the flags below	*/
114#define		DEBUG_MFC	0x02
115#define		DEBUG_FORWARD	0x04
116#define		DEBUG_EXPIRE	0x08
117#define		DEBUG_XMIT	0x10
118#define		DEBUG_PIM	0x20
119
120#define		VIFI_INVALID	((vifi_t) -1)
121
122#define M_HASCL(m)	((m)->m_flags & M_EXT)
123
124static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast routing tables");
125
126/*
127 * Locking.  We use two locks: one for the virtual interface table and
128 * one for the forwarding table.  These locks may be nested in which case
129 * the VIF lock must always be taken first.  Note that each lock is used
130 * to cover not only the specific data structure but also related data
131 * structures.  It may be better to add more fine-grained locking later;
132 * it's not clear how performance-critical this code is.
133 *
134 * XXX: This module could particularly benefit from being cleaned
135 *      up to use the <sys/queue.h> macros.
136 *
137 */
138
139static struct mrtstat	mrtstat;
140SYSCTL_STRUCT(_net_inet_ip, OID_AUTO, mrtstat, CTLFLAG_RW,
141    &mrtstat, mrtstat,
142    "Multicast Routing Statistics (struct mrtstat, netinet/ip_mroute.h)");
143
144static struct mfc	*mfctable[MFCTBLSIZ];
145SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, mfctable, CTLFLAG_RD,
146    &mfctable, sizeof(mfctable), "S,*mfc[MFCTBLSIZ]",
147    "Multicast Forwarding Table (struct *mfc[MFCTBLSIZ], netinet/ip_mroute.h)");
148
149static struct mtx mrouter_mtx;
150#define	MROUTER_LOCK()		mtx_lock(&mrouter_mtx)
151#define	MROUTER_UNLOCK()	mtx_unlock(&mrouter_mtx)
152#define	MROUTER_LOCK_ASSERT()	do {					\
153	mtx_assert(&mrouter_mtx, MA_OWNED);				\
154	NET_ASSERT_GIANT();						\
155} while (0)
156#define	MROUTER_LOCK_INIT()	\
157	mtx_init(&mrouter_mtx, "IPv4 multicast forwarding", NULL, MTX_DEF)
158#define	MROUTER_LOCK_DESTROY()	mtx_destroy(&mrouter_mtx)
159
160static struct mtx mfc_mtx;
161#define	MFC_LOCK()	mtx_lock(&mfc_mtx)
162#define	MFC_UNLOCK()	mtx_unlock(&mfc_mtx)
163#define	MFC_LOCK_ASSERT()	do {					\
164	mtx_assert(&mfc_mtx, MA_OWNED);					\
165	NET_ASSERT_GIANT();						\
166} while (0)
167#define	MFC_LOCK_INIT()	mtx_init(&mfc_mtx, "mroute mfc table", NULL, MTX_DEF)
168#define	MFC_LOCK_DESTROY()	mtx_destroy(&mfc_mtx)
169
170static struct vif	viftable[MAXVIFS];
171SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, viftable, CTLFLAG_RD,
172    &viftable, sizeof(viftable), "S,vif[MAXVIFS]",
173    "Multicast Virtual Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
174
175static struct mtx vif_mtx;
176#define	VIF_LOCK()	mtx_lock(&vif_mtx)
177#define	VIF_UNLOCK()	mtx_unlock(&vif_mtx)
178#define	VIF_LOCK_ASSERT()	mtx_assert(&vif_mtx, MA_OWNED)
179#define	VIF_LOCK_INIT()	mtx_init(&vif_mtx, "mroute vif table", NULL, MTX_DEF)
180#define	VIF_LOCK_DESTROY()	mtx_destroy(&vif_mtx)
181
182static u_char		nexpire[MFCTBLSIZ];
183
184static eventhandler_tag if_detach_event_tag = NULL;
185
186static struct callout expire_upcalls_ch;
187
188#define		EXPIRE_TIMEOUT	(hz / 4)	/* 4x / second		*/
189#define		UPCALL_EXPIRE	6		/* number of timeouts	*/
190
191#define ENCAP_TTL 64
192
193/*
194 * Bandwidth meter variables and constants
195 */
196static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
197/*
198 * Pending timeouts are stored in a hash table, the key being the
199 * expiration time. Periodically, the entries are analysed and processed.
200 */
201#define BW_METER_BUCKETS	1024
202static struct bw_meter *bw_meter_timers[BW_METER_BUCKETS];
203static struct callout bw_meter_ch;
204#define BW_METER_PERIOD (hz)		/* periodical handling of bw meters */
205
206/*
207 * Pending upcalls are stored in a vector which is flushed when
208 * full, or periodically
209 */
210static struct bw_upcall	bw_upcalls[BW_UPCALLS_MAX];
211static u_int	bw_upcalls_n; /* # of pending upcalls */
212static struct callout bw_upcalls_ch;
213#define BW_UPCALLS_PERIOD (hz)		/* periodical flush of bw upcalls */
214
215static struct pimstat pimstat;
216
217SYSCTL_NODE(_net_inet, IPPROTO_PIM, pim, CTLFLAG_RW, 0, "PIM");
218SYSCTL_STRUCT(_net_inet_pim, PIMCTL_STATS, stats, CTLFLAG_RD,
219    &pimstat, pimstat,
220    "PIM Statistics (struct pimstat, netinet/pim_var.h)");
221
222static u_long	pim_squelch_wholepkt = 0;
223SYSCTL_ULONG(_net_inet_pim, OID_AUTO, squelch_wholepkt, CTLFLAG_RW,
224    &pim_squelch_wholepkt, 0,
225    "Disable IGMP_WHOLEPKT notifications if rendezvous point is unspecified");
226
227extern  struct domain inetdomain;
228struct protosw in_pim_protosw = {
229	.pr_type =		SOCK_RAW,
230	.pr_domain =		&inetdomain,
231	.pr_protocol =		IPPROTO_PIM,
232	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_LASTHDR,
233	.pr_input =		pim_input,
234	.pr_output =		(pr_output_t*)rip_output,
235	.pr_ctloutput =		rip_ctloutput,
236	.pr_usrreqs =		&rip_usrreqs
237};
238static const struct encaptab *pim_encap_cookie;
239
240#ifdef INET6
241/* ip6_mroute.c glue */
242extern struct in6_protosw in6_pim_protosw;
243static const struct encaptab *pim6_encap_cookie;
244
245extern int X_ip6_mrouter_set(struct socket *, struct sockopt *);
246extern int X_ip6_mrouter_get(struct socket *, struct sockopt *);
247extern int X_ip6_mrouter_done(void);
248extern int X_ip6_mforward(struct ip6_hdr *, struct ifnet *, struct mbuf *);
249extern int X_mrt6_ioctl(int, caddr_t);
250#endif
251
252static int pim_encapcheck(const struct mbuf *, int, int, void *);
253
254/*
255 * Note: the PIM Register encapsulation adds the following in front of a
256 * data packet:
257 *
258 * struct pim_encap_hdr {
259 *    struct ip ip;
260 *    struct pim_encap_pimhdr  pim;
261 * }
262 *
263 */
264
265struct pim_encap_pimhdr {
266	struct pim pim;
267	uint32_t   flags;
268};
269
270static struct ip pim_encap_iphdr = {
271#if BYTE_ORDER == LITTLE_ENDIAN
272	sizeof(struct ip) >> 2,
273	IPVERSION,
274#else
275	IPVERSION,
276	sizeof(struct ip) >> 2,
277#endif
278	0,			/* tos */
279	sizeof(struct ip),	/* total length */
280	0,			/* id */
281	0,			/* frag offset */
282	ENCAP_TTL,
283	IPPROTO_PIM,
284	0,			/* checksum */
285};
286
287static struct pim_encap_pimhdr pim_encap_pimhdr = {
288    {
289	PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
290	0,			/* reserved */
291	0,			/* checksum */
292    },
293    0				/* flags */
294};
295
296static struct ifnet multicast_register_if;
297static vifi_t reg_vif_num = VIFI_INVALID;
298
299/*
300 * Private variables.
301 */
302static vifi_t	   numvifs;
303
304static u_long	X_ip_mcast_src(int vifi);
305static int	X_ip_mforward(struct ip *ip, struct ifnet *ifp,
306			struct mbuf *m, struct ip_moptions *imo);
307static int	X_ip_mrouter_done(void);
308static int	X_ip_mrouter_get(struct socket *so, struct sockopt *m);
309static int	X_ip_mrouter_set(struct socket *so, struct sockopt *m);
310static int	X_legal_vif_num(int vif);
311static int	X_mrt_ioctl(int cmd, caddr_t data);
312
313static int get_sg_cnt(struct sioc_sg_req *);
314static int get_vif_cnt(struct sioc_vif_req *);
315static void if_detached_event(void *arg __unused, struct ifnet *);
316static int ip_mrouter_init(struct socket *, int);
317static int add_vif(struct vifctl *);
318static int del_vif_locked(vifi_t);
319static int del_vif(vifi_t);
320static int add_mfc(struct mfcctl2 *);
321static int del_mfc(struct mfcctl2 *);
322static int set_api_config(uint32_t *); /* chose API capabilities */
323static int socket_send(struct socket *, struct mbuf *, struct sockaddr_in *);
324static int set_assert(int);
325static void expire_upcalls(void *);
326static int ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
327static void phyint_send(struct ip *, struct vif *, struct mbuf *);
328static void send_packet(struct vif *, struct mbuf *);
329
330/*
331 * Bandwidth monitoring
332 */
333static void free_bw_list(struct bw_meter *list);
334static int add_bw_upcall(struct bw_upcall *);
335static int del_bw_upcall(struct bw_upcall *);
336static void bw_meter_receive_packet(struct bw_meter *x, int plen,
337		struct timeval *nowp);
338static void bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp);
339static void bw_upcalls_send(void);
340static void schedule_bw_meter(struct bw_meter *x, struct timeval *nowp);
341static void unschedule_bw_meter(struct bw_meter *x);
342static void bw_meter_process(void);
343static void expire_bw_upcalls_send(void *);
344static void expire_bw_meter_process(void *);
345
346static int pim_register_send(struct ip *, struct vif *,
347		struct mbuf *, struct mfc *);
348static int pim_register_send_rp(struct ip *, struct vif *,
349		struct mbuf *, struct mfc *);
350static int pim_register_send_upcall(struct ip *, struct vif *,
351		struct mbuf *, struct mfc *);
352static struct mbuf *pim_register_prepare(struct ip *, struct mbuf *);
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 = priv_check(curthread, PRIV_NETINET_MROUTE);
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
651static void
652if_detached_event(void *arg __unused, struct ifnet *ifp)
653{
654    vifi_t vifi;
655    int i;
656    struct mfc *mfc;
657    struct mfc *nmfc;
658    struct mfc **ppmfc;	/* Pointer to previous node's next-pointer */
659    struct rtdetq *pq;
660    struct rtdetq *npq;
661
662    MROUTER_LOCK();
663    if (ip_mrouter == NULL) {
664	MROUTER_UNLOCK();
665    }
666
667    /*
668     * Tear down multicast forwarder state associated with this ifnet.
669     * 1. Walk the vif list, matching vifs against this ifnet.
670     * 2. Walk the multicast forwarding cache (mfc) looking for
671     *    inner matches with this vif's index.
672     * 3. Free any pending mbufs for this mfc.
673     * 4. Free the associated mfc entry and state associated with this vif.
674     *    Be very careful about unlinking from a singly-linked list whose
675     *    "head node" is a pointer in a simple array.
676     * 5. Free vif state. This should disable ALLMULTI on the interface.
677     */
678    VIF_LOCK();
679    MFC_LOCK();
680    for (vifi = 0; vifi < numvifs; vifi++) {
681	if (viftable[vifi].v_ifp != ifp)
682		continue;
683	for (i = 0; i < MFCTBLSIZ; i++) {
684	    ppmfc = &mfctable[i];
685	    for (mfc = mfctable[i]; mfc != NULL; ) {
686		nmfc = mfc->mfc_next;
687		if (mfc->mfc_parent == vifi) {
688		    for (pq = mfc->mfc_stall; pq != NULL; ) {
689			npq = pq->next;
690			m_freem(pq->m);
691			free(pq, M_MRTABLE);
692			pq = npq;
693		    }
694		    free_bw_list(mfc->mfc_bw_meter);
695		    free(mfc, M_MRTABLE);
696		    *ppmfc = nmfc;
697		} else {
698		    ppmfc = &mfc->mfc_next;
699		}
700		mfc = nmfc;
701	    }
702	}
703	del_vif_locked(vifi);
704    }
705    MFC_UNLOCK();
706    VIF_UNLOCK();
707
708    MROUTER_UNLOCK();
709}
710
711/*
712 * Enable multicast routing
713 */
714static int
715ip_mrouter_init(struct socket *so, int version)
716{
717    if (mrtdebug)
718	log(LOG_DEBUG, "ip_mrouter_init: so_type = %d, pr_protocol = %d\n",
719	    so->so_type, so->so_proto->pr_protocol);
720
721    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_IGMP)
722	return EOPNOTSUPP;
723
724    if (version != 1)
725	return ENOPROTOOPT;
726
727    MROUTER_LOCK();
728
729    if (ip_mrouter != NULL) {
730	MROUTER_UNLOCK();
731	return EADDRINUSE;
732    }
733
734    if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
735        if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
736    if (if_detach_event_tag == NULL) {
737	MROUTER_UNLOCK();
738	return (ENOMEM);
739    }
740
741    callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
742
743    callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
744	expire_bw_upcalls_send, NULL);
745    callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
746
747    ip_mrouter = so;
748
749    MROUTER_UNLOCK();
750
751    if (mrtdebug)
752	log(LOG_DEBUG, "ip_mrouter_init\n");
753
754    return 0;
755}
756
757/*
758 * Disable multicast routing
759 */
760static int
761X_ip_mrouter_done(void)
762{
763    vifi_t vifi;
764    int i;
765    struct ifnet *ifp;
766    struct ifreq ifr;
767    struct mfc *rt;
768    struct rtdetq *rte;
769
770    MROUTER_LOCK();
771
772    if (ip_mrouter == NULL) {
773	MROUTER_UNLOCK();
774	return EINVAL;
775    }
776
777    /*
778     * Detach/disable hooks to the reset of the system.
779     */
780    ip_mrouter = NULL;
781    mrt_api_config = 0;
782
783    VIF_LOCK();
784    /*
785     * For each phyint in use, disable promiscuous reception of all IP
786     * multicasts.
787     */
788    for (vifi = 0; vifi < numvifs; vifi++) {
789	if (viftable[vifi].v_lcl_addr.s_addr != 0 &&
790		!(viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
791	    struct sockaddr_in *so = (struct sockaddr_in *)&(ifr.ifr_addr);
792
793	    so->sin_len = sizeof(struct sockaddr_in);
794	    so->sin_family = AF_INET;
795	    so->sin_addr.s_addr = INADDR_ANY;
796	    ifp = viftable[vifi].v_ifp;
797	    if_allmulti(ifp, 0);
798	}
799    }
800    bzero((caddr_t)viftable, sizeof(viftable));
801    numvifs = 0;
802    pim_assert = 0;
803    VIF_UNLOCK();
804    EVENTHANDLER_DEREGISTER(ifnet_departure_event, if_detach_event_tag);
805
806    /*
807     * Free all multicast forwarding cache entries.
808     */
809    callout_stop(&expire_upcalls_ch);
810    callout_stop(&bw_upcalls_ch);
811    callout_stop(&bw_meter_ch);
812
813    MFC_LOCK();
814    for (i = 0; i < MFCTBLSIZ; i++) {
815	for (rt = mfctable[i]; rt != NULL; ) {
816	    struct mfc *nr = rt->mfc_next;
817
818	    for (rte = rt->mfc_stall; rte != NULL; ) {
819		struct rtdetq *n = rte->next;
820
821		m_freem(rte->m);
822		free(rte, M_MRTABLE);
823		rte = n;
824	    }
825	    free_bw_list(rt->mfc_bw_meter);
826	    free(rt, M_MRTABLE);
827	    rt = nr;
828	}
829    }
830    bzero((caddr_t)mfctable, sizeof(mfctable));
831    bzero((caddr_t)nexpire, sizeof(nexpire));
832    bw_upcalls_n = 0;
833    bzero(bw_meter_timers, sizeof(bw_meter_timers));
834    MFC_UNLOCK();
835
836    reg_vif_num = VIFI_INVALID;
837
838    MROUTER_UNLOCK();
839
840    if (mrtdebug)
841	log(LOG_DEBUG, "ip_mrouter_done\n");
842
843    return 0;
844}
845
846/*
847 * Set PIM assert processing global
848 */
849static int
850set_assert(int i)
851{
852    if ((i != 1) && (i != 0))
853	return EINVAL;
854
855    pim_assert = i;
856
857    return 0;
858}
859
860/*
861 * Configure API capabilities
862 */
863int
864set_api_config(uint32_t *apival)
865{
866    int i;
867
868    /*
869     * We can set the API capabilities only if it is the first operation
870     * after MRT_INIT. I.e.:
871     *  - there are no vifs installed
872     *  - pim_assert is not enabled
873     *  - the MFC table is empty
874     */
875    if (numvifs > 0) {
876	*apival = 0;
877	return EPERM;
878    }
879    if (pim_assert) {
880	*apival = 0;
881	return EPERM;
882    }
883    for (i = 0; i < MFCTBLSIZ; i++) {
884	if (mfctable[i] != NULL) {
885	    *apival = 0;
886	    return EPERM;
887	}
888    }
889
890    mrt_api_config = *apival & mrt_api_support;
891    *apival = mrt_api_config;
892
893    return 0;
894}
895
896/*
897 * Add a vif to the vif table
898 */
899static int
900add_vif(struct vifctl *vifcp)
901{
902    struct vif *vifp = viftable + vifcp->vifc_vifi;
903    struct sockaddr_in sin = {sizeof sin, AF_INET};
904    struct ifaddr *ifa;
905    struct ifnet *ifp;
906    int error;
907
908    VIF_LOCK();
909    if (vifcp->vifc_vifi >= MAXVIFS) {
910	VIF_UNLOCK();
911	return EINVAL;
912    }
913    /* rate limiting is no longer supported by this code */
914    if (vifcp->vifc_rate_limit != 0) {
915	log(LOG_ERR, "rate limiting is no longer supported\n");
916	VIF_UNLOCK();
917	return EINVAL;
918    }
919    if (vifp->v_lcl_addr.s_addr != INADDR_ANY) {
920	VIF_UNLOCK();
921	return EADDRINUSE;
922    }
923    if (vifcp->vifc_lcl_addr.s_addr == INADDR_ANY) {
924	VIF_UNLOCK();
925	return EADDRNOTAVAIL;
926    }
927
928    /* Find the interface with an address in AF_INET family */
929    if (vifcp->vifc_flags & VIFF_REGISTER) {
930	/*
931	 * XXX: Because VIFF_REGISTER does not really need a valid
932	 * local interface (e.g. it could be 127.0.0.2), we don't
933	 * check its address.
934	 */
935	ifp = NULL;
936    } else {
937	sin.sin_addr = vifcp->vifc_lcl_addr;
938	ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
939	if (ifa == NULL) {
940	    VIF_UNLOCK();
941	    return EADDRNOTAVAIL;
942	}
943	ifp = ifa->ifa_ifp;
944    }
945
946    if ((vifcp->vifc_flags & VIFF_TUNNEL) != 0) {
947	log(LOG_ERR, "tunnels are no longer supported\n");
948	VIF_UNLOCK();
949	return EOPNOTSUPP;
950    } else if (vifcp->vifc_flags & VIFF_REGISTER) {
951	ifp = &multicast_register_if;
952	if (mrtdebug)
953	    log(LOG_DEBUG, "Adding a register vif, ifp: %p\n",
954		    (void *)&multicast_register_if);
955	if (reg_vif_num == VIFI_INVALID) {
956	    if_initname(&multicast_register_if, "register_vif", 0);
957	    multicast_register_if.if_flags = IFF_LOOPBACK;
958	    reg_vif_num = vifcp->vifc_vifi;
959	}
960    } else {		/* Make sure the interface supports multicast */
961	if ((ifp->if_flags & IFF_MULTICAST) == 0) {
962	    VIF_UNLOCK();
963	    return EOPNOTSUPP;
964	}
965
966	/* Enable promiscuous reception of all IP multicasts from the if */
967	error = if_allmulti(ifp, 1);
968	if (error) {
969	    VIF_UNLOCK();
970	    return error;
971	}
972    }
973
974    vifp->v_flags     = vifcp->vifc_flags;
975    vifp->v_threshold = vifcp->vifc_threshold;
976    vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
977    vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
978    vifp->v_ifp       = ifp;
979    vifp->v_rsvp_on   = 0;
980    vifp->v_rsvpd     = NULL;
981    /* initialize per vif pkt counters */
982    vifp->v_pkt_in    = 0;
983    vifp->v_pkt_out   = 0;
984    vifp->v_bytes_in  = 0;
985    vifp->v_bytes_out = 0;
986    bzero(&vifp->v_route, sizeof(vifp->v_route));
987
988    /* Adjust numvifs up if the vifi is higher than numvifs */
989    if (numvifs <= vifcp->vifc_vifi) numvifs = vifcp->vifc_vifi + 1;
990
991    VIF_UNLOCK();
992
993    if (mrtdebug)
994	log(LOG_DEBUG, "add_vif #%d, lcladdr %lx, %s %lx, thresh %x\n",
995	    vifcp->vifc_vifi,
996	    (u_long)ntohl(vifcp->vifc_lcl_addr.s_addr),
997	    (vifcp->vifc_flags & VIFF_TUNNEL) ? "rmtaddr" : "mask",
998	    (u_long)ntohl(vifcp->vifc_rmt_addr.s_addr),
999	    vifcp->vifc_threshold);
1000
1001    return 0;
1002}
1003
1004/*
1005 * Delete a vif from the vif table
1006 */
1007static int
1008del_vif_locked(vifi_t vifi)
1009{
1010    struct vif *vifp;
1011
1012    VIF_LOCK_ASSERT();
1013
1014    if (vifi >= numvifs) {
1015	return EINVAL;
1016    }
1017    vifp = &viftable[vifi];
1018    if (vifp->v_lcl_addr.s_addr == INADDR_ANY) {
1019	return EADDRNOTAVAIL;
1020    }
1021
1022    if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
1023	if_allmulti(vifp->v_ifp, 0);
1024
1025    if (vifp->v_flags & VIFF_REGISTER)
1026	reg_vif_num = VIFI_INVALID;
1027
1028    bzero((caddr_t)vifp, sizeof (*vifp));
1029
1030    if (mrtdebug)
1031	log(LOG_DEBUG, "del_vif %d, numvifs %d\n", vifi, numvifs);
1032
1033    /* Adjust numvifs down */
1034    for (vifi = numvifs; vifi > 0; vifi--)
1035	if (viftable[vifi-1].v_lcl_addr.s_addr != INADDR_ANY)
1036	    break;
1037    numvifs = vifi;
1038
1039    return 0;
1040}
1041
1042static int
1043del_vif(vifi_t vifi)
1044{
1045    int cc;
1046
1047    VIF_LOCK();
1048    cc = del_vif_locked(vifi);
1049    VIF_UNLOCK();
1050
1051    return cc;
1052}
1053
1054/*
1055 * update an mfc entry without resetting counters and S,G addresses.
1056 */
1057static void
1058update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1059{
1060    int i;
1061
1062    rt->mfc_parent = mfccp->mfcc_parent;
1063    for (i = 0; i < numvifs; i++) {
1064	rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1065	rt->mfc_flags[i] = mfccp->mfcc_flags[i] & mrt_api_config &
1066	    MRT_MFC_FLAGS_ALL;
1067    }
1068    /* set the RP address */
1069    if (mrt_api_config & MRT_MFC_RP)
1070	rt->mfc_rp = mfccp->mfcc_rp;
1071    else
1072	rt->mfc_rp.s_addr = INADDR_ANY;
1073}
1074
1075/*
1076 * fully initialize an mfc entry from the parameter.
1077 */
1078static void
1079init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1080{
1081    rt->mfc_origin     = mfccp->mfcc_origin;
1082    rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
1083
1084    update_mfc_params(rt, mfccp);
1085
1086    /* initialize pkt counters per src-grp */
1087    rt->mfc_pkt_cnt    = 0;
1088    rt->mfc_byte_cnt   = 0;
1089    rt->mfc_wrong_if   = 0;
1090    rt->mfc_last_assert.tv_sec = rt->mfc_last_assert.tv_usec = 0;
1091}
1092
1093
1094/*
1095 * Add an mfc entry
1096 */
1097static int
1098add_mfc(struct mfcctl2 *mfccp)
1099{
1100    struct mfc *rt;
1101    u_long hash;
1102    struct rtdetq *rte;
1103    u_short nstl;
1104
1105    VIF_LOCK();
1106    MFC_LOCK();
1107
1108    rt = mfc_find(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
1109
1110    /* If an entry already exists, just update the fields */
1111    if (rt) {
1112	if (mrtdebug & DEBUG_MFC)
1113	    log(LOG_DEBUG,"add_mfc update o %lx g %lx p %x\n",
1114		(u_long)ntohl(mfccp->mfcc_origin.s_addr),
1115		(u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1116		mfccp->mfcc_parent);
1117
1118	update_mfc_params(rt, mfccp);
1119	MFC_UNLOCK();
1120	VIF_UNLOCK();
1121	return 0;
1122    }
1123
1124    /*
1125     * Find the entry for which the upcall was made and update
1126     */
1127    hash = MFCHASH(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
1128    for (rt = mfctable[hash], nstl = 0; rt; rt = rt->mfc_next) {
1129
1130	if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1131		(rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr) &&
1132		(rt->mfc_stall != NULL)) {
1133
1134	    if (nstl++)
1135		log(LOG_ERR, "add_mfc %s o %lx g %lx p %x dbx %p\n",
1136		    "multiple kernel entries",
1137		    (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1138		    (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1139		    mfccp->mfcc_parent, (void *)rt->mfc_stall);
1140
1141	    if (mrtdebug & DEBUG_MFC)
1142		log(LOG_DEBUG,"add_mfc o %lx g %lx p %x dbg %p\n",
1143		    (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1144		    (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1145		    mfccp->mfcc_parent, (void *)rt->mfc_stall);
1146
1147	    init_mfc_params(rt, mfccp);
1148
1149	    rt->mfc_expire = 0;	/* Don't clean this guy up */
1150	    nexpire[hash]--;
1151
1152	    /* free packets Qed at the end of this entry */
1153	    for (rte = rt->mfc_stall; rte != NULL; ) {
1154		struct rtdetq *n = rte->next;
1155
1156		ip_mdq(rte->m, rte->ifp, rt, -1);
1157		m_freem(rte->m);
1158		free(rte, M_MRTABLE);
1159		rte = n;
1160	    }
1161	    rt->mfc_stall = NULL;
1162	}
1163    }
1164
1165    /*
1166     * It is possible that an entry is being inserted without an upcall
1167     */
1168    if (nstl == 0) {
1169	if (mrtdebug & DEBUG_MFC)
1170	    log(LOG_DEBUG,"add_mfc no upcall h %lu o %lx g %lx p %x\n",
1171		hash, (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1172		(u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1173		mfccp->mfcc_parent);
1174
1175	for (rt = mfctable[hash]; rt != NULL; rt = rt->mfc_next) {
1176	    if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1177		    (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr)) {
1178		init_mfc_params(rt, mfccp);
1179		if (rt->mfc_expire)
1180		    nexpire[hash]--;
1181		rt->mfc_expire = 0;
1182		break; /* XXX */
1183	    }
1184	}
1185	if (rt == NULL) {		/* no upcall, so make a new entry */
1186	    rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1187	    if (rt == NULL) {
1188		MFC_UNLOCK();
1189		VIF_UNLOCK();
1190		return ENOBUFS;
1191	    }
1192
1193	    init_mfc_params(rt, mfccp);
1194	    rt->mfc_expire     = 0;
1195	    rt->mfc_stall      = NULL;
1196
1197	    rt->mfc_bw_meter = NULL;
1198	    /* insert new entry at head of hash chain */
1199	    rt->mfc_next = mfctable[hash];
1200	    mfctable[hash] = rt;
1201	}
1202    }
1203    MFC_UNLOCK();
1204    VIF_UNLOCK();
1205    return 0;
1206}
1207
1208/*
1209 * Delete an mfc entry
1210 */
1211static int
1212del_mfc(struct mfcctl2 *mfccp)
1213{
1214    struct in_addr	origin;
1215    struct in_addr	mcastgrp;
1216    struct mfc		*rt;
1217    struct mfc		**nptr;
1218    u_long		hash;
1219    struct bw_meter	*list;
1220
1221    origin = mfccp->mfcc_origin;
1222    mcastgrp = mfccp->mfcc_mcastgrp;
1223
1224    if (mrtdebug & DEBUG_MFC)
1225	log(LOG_DEBUG,"del_mfc orig %lx mcastgrp %lx\n",
1226	    (u_long)ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
1227
1228    MFC_LOCK();
1229
1230    hash = MFCHASH(origin.s_addr, mcastgrp.s_addr);
1231    for (nptr = &mfctable[hash]; (rt = *nptr) != NULL; nptr = &rt->mfc_next)
1232	if (origin.s_addr == rt->mfc_origin.s_addr &&
1233		mcastgrp.s_addr == rt->mfc_mcastgrp.s_addr &&
1234		rt->mfc_stall == NULL)
1235	    break;
1236    if (rt == NULL) {
1237	MFC_UNLOCK();
1238	return EADDRNOTAVAIL;
1239    }
1240
1241    *nptr = rt->mfc_next;
1242
1243    /*
1244     * free the bw_meter entries
1245     */
1246    list = rt->mfc_bw_meter;
1247    rt->mfc_bw_meter = NULL;
1248
1249    free(rt, M_MRTABLE);
1250
1251    free_bw_list(list);
1252
1253    MFC_UNLOCK();
1254
1255    return 0;
1256}
1257
1258/*
1259 * Send a message to the routing daemon on the multicast routing socket
1260 */
1261static int
1262socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1263{
1264    if (s) {
1265	SOCKBUF_LOCK(&s->so_rcv);
1266	if (sbappendaddr_locked(&s->so_rcv, (struct sockaddr *)src, mm,
1267	    NULL) != 0) {
1268	    sorwakeup_locked(s);
1269	    return 0;
1270	}
1271	SOCKBUF_UNLOCK(&s->so_rcv);
1272    }
1273    m_freem(mm);
1274    return -1;
1275}
1276
1277/*
1278 * IP multicast forwarding function. This function assumes that the packet
1279 * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1280 * pointed to by "ifp", and the packet is to be relayed to other networks
1281 * that have members of the packet's destination IP multicast group.
1282 *
1283 * The packet is returned unscathed to the caller, unless it is
1284 * erroneous, in which case a non-zero return value tells the caller to
1285 * discard it.
1286 */
1287
1288#define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1289
1290static int
1291X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1292    struct ip_moptions *imo)
1293{
1294    struct mfc *rt;
1295    int error;
1296    vifi_t vifi;
1297
1298    if (mrtdebug & DEBUG_FORWARD)
1299	log(LOG_DEBUG, "ip_mforward: src %lx, dst %lx, ifp %p\n",
1300	    (u_long)ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr),
1301	    (void *)ifp);
1302
1303    if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1304		((u_char *)(ip + 1))[1] != IPOPT_LSRR ) {
1305	/*
1306	 * Packet arrived via a physical interface or
1307	 * an encapsulated tunnel or a register_vif.
1308	 */
1309    } else {
1310	/*
1311	 * Packet arrived through a source-route tunnel.
1312	 * Source-route tunnels are no longer supported.
1313	 */
1314	static int last_log;
1315	if (last_log != time_uptime) {
1316	    last_log = time_uptime;
1317	    log(LOG_ERR,
1318		"ip_mforward: received source-routed packet from %lx\n",
1319		(u_long)ntohl(ip->ip_src.s_addr));
1320	}
1321	return 1;
1322    }
1323
1324    VIF_LOCK();
1325    MFC_LOCK();
1326    if (imo && ((vifi = imo->imo_multicast_vif) < numvifs)) {
1327	if (ip->ip_ttl < MAXTTL)
1328	    ip->ip_ttl++;	/* compensate for -1 in *_send routines */
1329	if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1330	    struct vif *vifp = viftable + vifi;
1331
1332	    printf("Sending IPPROTO_RSVP from %lx to %lx on vif %d (%s%s)\n",
1333		(long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr),
1334		vifi,
1335		(vifp->v_flags & VIFF_TUNNEL) ? "tunnel on " : "",
1336		vifp->v_ifp->if_xname);
1337	}
1338	error = ip_mdq(m, ifp, NULL, vifi);
1339	MFC_UNLOCK();
1340	VIF_UNLOCK();
1341	return error;
1342    }
1343    if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1344	printf("Warning: IPPROTO_RSVP from %lx to %lx without vif option\n",
1345	    (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr));
1346	if (!imo)
1347	    printf("In fact, no options were specified at all\n");
1348    }
1349
1350    /*
1351     * Don't forward a packet with time-to-live of zero or one,
1352     * or a packet destined to a local-only group.
1353     */
1354    if (ip->ip_ttl <= 1 || ntohl(ip->ip_dst.s_addr) <= INADDR_MAX_LOCAL_GROUP) {
1355	MFC_UNLOCK();
1356	VIF_UNLOCK();
1357	return 0;
1358    }
1359
1360    /*
1361     * Determine forwarding vifs from the forwarding cache table
1362     */
1363    ++mrtstat.mrts_mfc_lookups;
1364    rt = mfc_find(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1365
1366    /* Entry exists, so forward if necessary */
1367    if (rt != NULL) {
1368	error = ip_mdq(m, ifp, rt, -1);
1369	MFC_UNLOCK();
1370	VIF_UNLOCK();
1371	return error;
1372    } else {
1373	/*
1374	 * If we don't have a route for packet's origin,
1375	 * Make a copy of the packet & send message to routing daemon
1376	 */
1377
1378	struct mbuf *mb0;
1379	struct rtdetq *rte;
1380	u_long hash;
1381	int hlen = ip->ip_hl << 2;
1382
1383	++mrtstat.mrts_mfc_misses;
1384
1385	mrtstat.mrts_no_route++;
1386	if (mrtdebug & (DEBUG_FORWARD | DEBUG_MFC))
1387	    log(LOG_DEBUG, "ip_mforward: no rte s %lx g %lx\n",
1388		(u_long)ntohl(ip->ip_src.s_addr),
1389		(u_long)ntohl(ip->ip_dst.s_addr));
1390
1391	/*
1392	 * Allocate mbufs early so that we don't do extra work if we are
1393	 * just going to fail anyway.  Make sure to pullup the header so
1394	 * that other people can't step on it.
1395	 */
1396	rte = (struct rtdetq *)malloc((sizeof *rte), M_MRTABLE, M_NOWAIT);
1397	if (rte == NULL) {
1398	    MFC_UNLOCK();
1399	    VIF_UNLOCK();
1400	    return ENOBUFS;
1401	}
1402	mb0 = m_copypacket(m, M_DONTWAIT);
1403	if (mb0 && (M_HASCL(mb0) || mb0->m_len < hlen))
1404	    mb0 = m_pullup(mb0, hlen);
1405	if (mb0 == NULL) {
1406	    free(rte, M_MRTABLE);
1407	    MFC_UNLOCK();
1408	    VIF_UNLOCK();
1409	    return ENOBUFS;
1410	}
1411
1412	/* is there an upcall waiting for this flow ? */
1413	hash = MFCHASH(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1414	for (rt = mfctable[hash]; rt; rt = rt->mfc_next) {
1415	    if ((ip->ip_src.s_addr == rt->mfc_origin.s_addr) &&
1416		    (ip->ip_dst.s_addr == rt->mfc_mcastgrp.s_addr) &&
1417		    (rt->mfc_stall != NULL))
1418		break;
1419	}
1420
1421	if (rt == NULL) {
1422	    int i;
1423	    struct igmpmsg *im;
1424	    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1425	    struct mbuf *mm;
1426
1427	    /*
1428	     * Locate the vifi for the incoming interface for this packet.
1429	     * If none found, drop packet.
1430	     */
1431	    for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1432		;
1433	    if (vifi >= numvifs)	/* vif not found, drop packet */
1434		goto non_fatal;
1435
1436	    /* no upcall, so make a new entry */
1437	    rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1438	    if (rt == NULL)
1439		goto fail;
1440	    /* Make a copy of the header to send to the user level process */
1441	    mm = m_copy(mb0, 0, hlen);
1442	    if (mm == NULL)
1443		goto fail1;
1444
1445	    /*
1446	     * Send message to routing daemon to install
1447	     * a route into the kernel table
1448	     */
1449
1450	    im = mtod(mm, struct igmpmsg *);
1451	    im->im_msgtype = IGMPMSG_NOCACHE;
1452	    im->im_mbz = 0;
1453	    im->im_vif = vifi;
1454
1455	    mrtstat.mrts_upcalls++;
1456
1457	    k_igmpsrc.sin_addr = ip->ip_src;
1458	    if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1459		log(LOG_WARNING, "ip_mforward: ip_mrouter socket queue full\n");
1460		++mrtstat.mrts_upq_sockfull;
1461fail1:
1462		free(rt, M_MRTABLE);
1463fail:
1464		free(rte, M_MRTABLE);
1465		m_freem(mb0);
1466		MFC_UNLOCK();
1467		VIF_UNLOCK();
1468		return ENOBUFS;
1469	    }
1470
1471	    /* insert new entry at head of hash chain */
1472	    rt->mfc_origin.s_addr     = ip->ip_src.s_addr;
1473	    rt->mfc_mcastgrp.s_addr   = ip->ip_dst.s_addr;
1474	    rt->mfc_expire	      = UPCALL_EXPIRE;
1475	    nexpire[hash]++;
1476	    for (i = 0; i < numvifs; i++) {
1477		rt->mfc_ttls[i] = 0;
1478		rt->mfc_flags[i] = 0;
1479	    }
1480	    rt->mfc_parent = -1;
1481
1482	    rt->mfc_rp.s_addr = INADDR_ANY; /* clear the RP address */
1483
1484	    rt->mfc_bw_meter = NULL;
1485
1486	    /* link into table */
1487	    rt->mfc_next   = mfctable[hash];
1488	    mfctable[hash] = rt;
1489	    rt->mfc_stall = rte;
1490
1491	} else {
1492	    /* determine if q has overflowed */
1493	    int npkts = 0;
1494	    struct rtdetq **p;
1495
1496	    /*
1497	     * XXX ouch! we need to append to the list, but we
1498	     * only have a pointer to the front, so we have to
1499	     * scan the entire list every time.
1500	     */
1501	    for (p = &rt->mfc_stall; *p != NULL; p = &(*p)->next)
1502		npkts++;
1503
1504	    if (npkts > MAX_UPQ) {
1505		mrtstat.mrts_upq_ovflw++;
1506non_fatal:
1507		free(rte, M_MRTABLE);
1508		m_freem(mb0);
1509		MFC_UNLOCK();
1510		VIF_UNLOCK();
1511		return 0;
1512	    }
1513
1514	    /* Add this entry to the end of the queue */
1515	    *p = rte;
1516	}
1517
1518	rte->m			= mb0;
1519	rte->ifp		= ifp;
1520	rte->next		= NULL;
1521
1522	MFC_UNLOCK();
1523	VIF_UNLOCK();
1524
1525	return 0;
1526    }
1527}
1528
1529/*
1530 * Clean up the cache entry if upcall is not serviced
1531 */
1532static void
1533expire_upcalls(void *unused)
1534{
1535    struct rtdetq *rte;
1536    struct mfc *mfc, **nptr;
1537    int i;
1538
1539    MFC_LOCK();
1540    for (i = 0; i < MFCTBLSIZ; i++) {
1541	if (nexpire[i] == 0)
1542	    continue;
1543	nptr = &mfctable[i];
1544	for (mfc = *nptr; mfc != NULL; mfc = *nptr) {
1545	    /*
1546	     * Skip real cache entries
1547	     * Make sure it wasn't marked to not expire (shouldn't happen)
1548	     * If it expires now
1549	     */
1550	    if (mfc->mfc_stall != NULL && mfc->mfc_expire != 0 &&
1551		    --mfc->mfc_expire == 0) {
1552		if (mrtdebug & DEBUG_EXPIRE)
1553		    log(LOG_DEBUG, "expire_upcalls: expiring (%lx %lx)\n",
1554			(u_long)ntohl(mfc->mfc_origin.s_addr),
1555			(u_long)ntohl(mfc->mfc_mcastgrp.s_addr));
1556		/*
1557		 * drop all the packets
1558		 * free the mbuf with the pkt, if, timing info
1559		 */
1560		for (rte = mfc->mfc_stall; rte; ) {
1561		    struct rtdetq *n = rte->next;
1562
1563		    m_freem(rte->m);
1564		    free(rte, M_MRTABLE);
1565		    rte = n;
1566		}
1567		++mrtstat.mrts_cache_cleanups;
1568		nexpire[i]--;
1569
1570		/*
1571		 * free the bw_meter entries
1572		 */
1573		while (mfc->mfc_bw_meter != NULL) {
1574		    struct bw_meter *x = mfc->mfc_bw_meter;
1575
1576		    mfc->mfc_bw_meter = x->bm_mfc_next;
1577		    free(x, M_BWMETER);
1578		}
1579
1580		*nptr = mfc->mfc_next;
1581		free(mfc, M_MRTABLE);
1582	    } else {
1583		nptr = &mfc->mfc_next;
1584	    }
1585	}
1586    }
1587    MFC_UNLOCK();
1588
1589    callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
1590}
1591
1592/*
1593 * Packet forwarding routine once entry in the cache is made
1594 */
1595static int
1596ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1597{
1598    struct ip  *ip = mtod(m, struct ip *);
1599    vifi_t vifi;
1600    int plen = ip->ip_len;
1601
1602    VIF_LOCK_ASSERT();
1603
1604    /*
1605     * If xmt_vif is not -1, send on only the requested vif.
1606     *
1607     * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1608     */
1609    if (xmt_vif < numvifs) {
1610	if (viftable[xmt_vif].v_flags & VIFF_REGISTER)
1611		pim_register_send(ip, viftable + xmt_vif, m, rt);
1612	else
1613		phyint_send(ip, viftable + xmt_vif, m);
1614	return 1;
1615    }
1616
1617    /*
1618     * Don't forward if it didn't arrive from the parent vif for its origin.
1619     */
1620    vifi = rt->mfc_parent;
1621    if ((vifi >= numvifs) || (viftable[vifi].v_ifp != ifp)) {
1622	/* came in the wrong interface */
1623	if (mrtdebug & DEBUG_FORWARD)
1624	    log(LOG_DEBUG, "wrong if: ifp %p vifi %d vififp %p\n",
1625		(void *)ifp, vifi, (void *)viftable[vifi].v_ifp);
1626	++mrtstat.mrts_wrong_if;
1627	++rt->mfc_wrong_if;
1628	/*
1629	 * If we are doing PIM assert processing, send a message
1630	 * to the routing daemon.
1631	 *
1632	 * XXX: A PIM-SM router needs the WRONGVIF detection so it
1633	 * can complete the SPT switch, regardless of the type
1634	 * of the iif (broadcast media, GRE tunnel, etc).
1635	 */
1636	if (pim_assert && (vifi < numvifs) && viftable[vifi].v_ifp) {
1637	    struct timeval now;
1638	    u_long delta;
1639
1640	    if (ifp == &multicast_register_if)
1641		pimstat.pims_rcv_registers_wrongiif++;
1642
1643	    /* Get vifi for the incoming packet */
1644	    for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1645		;
1646	    if (vifi >= numvifs)
1647		return 0;	/* The iif is not found: ignore the packet. */
1648
1649	    if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1650		return 0;	/* WRONGVIF disabled: ignore the packet */
1651
1652	    GET_TIME(now);
1653
1654	    TV_DELTA(now, rt->mfc_last_assert, delta);
1655
1656	    if (delta > ASSERT_MSG_TIME) {
1657		struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1658		struct igmpmsg *im;
1659		int hlen = ip->ip_hl << 2;
1660		struct mbuf *mm = m_copy(m, 0, hlen);
1661
1662		if (mm && (M_HASCL(mm) || mm->m_len < hlen))
1663		    mm = m_pullup(mm, hlen);
1664		if (mm == NULL)
1665		    return ENOBUFS;
1666
1667		rt->mfc_last_assert = now;
1668
1669		im = mtod(mm, struct igmpmsg *);
1670		im->im_msgtype	= IGMPMSG_WRONGVIF;
1671		im->im_mbz		= 0;
1672		im->im_vif		= vifi;
1673
1674		mrtstat.mrts_upcalls++;
1675
1676		k_igmpsrc.sin_addr = im->im_src;
1677		if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1678		    log(LOG_WARNING,
1679			"ip_mforward: ip_mrouter socket queue full\n");
1680		    ++mrtstat.mrts_upq_sockfull;
1681		    return ENOBUFS;
1682		}
1683	    }
1684	}
1685	return 0;
1686    }
1687
1688    /* If I sourced this packet, it counts as output, else it was input. */
1689    if (ip->ip_src.s_addr == viftable[vifi].v_lcl_addr.s_addr) {
1690	viftable[vifi].v_pkt_out++;
1691	viftable[vifi].v_bytes_out += plen;
1692    } else {
1693	viftable[vifi].v_pkt_in++;
1694	viftable[vifi].v_bytes_in += plen;
1695    }
1696    rt->mfc_pkt_cnt++;
1697    rt->mfc_byte_cnt += plen;
1698
1699    /*
1700     * For each vif, decide if a copy of the packet should be forwarded.
1701     * Forward if:
1702     *		- the ttl exceeds the vif's threshold
1703     *		- there are group members downstream on interface
1704     */
1705    for (vifi = 0; vifi < numvifs; vifi++)
1706	if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1707	    viftable[vifi].v_pkt_out++;
1708	    viftable[vifi].v_bytes_out += plen;
1709	    if (viftable[vifi].v_flags & VIFF_REGISTER)
1710		pim_register_send(ip, viftable + vifi, m, rt);
1711	    else
1712		phyint_send(ip, viftable + vifi, m);
1713	}
1714
1715    /*
1716     * Perform upcall-related bw measuring.
1717     */
1718    if (rt->mfc_bw_meter != NULL) {
1719	struct bw_meter *x;
1720	struct timeval now;
1721
1722	GET_TIME(now);
1723	MFC_LOCK_ASSERT();
1724	for (x = rt->mfc_bw_meter; x != NULL; x = x->bm_mfc_next)
1725	    bw_meter_receive_packet(x, plen, &now);
1726    }
1727
1728    return 0;
1729}
1730
1731/*
1732 * check if a vif number is legal/ok. This is used by ip_output.
1733 */
1734static int
1735X_legal_vif_num(int vif)
1736{
1737    /* XXX unlocked, matter? */
1738    return (vif >= 0 && vif < numvifs);
1739}
1740
1741/*
1742 * Return the local address used by this vif
1743 */
1744static u_long
1745X_ip_mcast_src(int vifi)
1746{
1747    /* XXX unlocked, matter? */
1748    if (vifi >= 0 && vifi < numvifs)
1749	return viftable[vifi].v_lcl_addr.s_addr;
1750    else
1751	return INADDR_ANY;
1752}
1753
1754static void
1755phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1756{
1757    struct mbuf *mb_copy;
1758    int hlen = ip->ip_hl << 2;
1759
1760    VIF_LOCK_ASSERT();
1761
1762    /*
1763     * Make a new reference to the packet; make sure that
1764     * the IP header is actually copied, not just referenced,
1765     * so that ip_output() only scribbles on the copy.
1766     */
1767    mb_copy = m_copypacket(m, M_DONTWAIT);
1768    if (mb_copy && (M_HASCL(mb_copy) || mb_copy->m_len < hlen))
1769	mb_copy = m_pullup(mb_copy, hlen);
1770    if (mb_copy == NULL)
1771	return;
1772
1773    send_packet(vifp, mb_copy);
1774}
1775
1776static void
1777send_packet(struct vif *vifp, struct mbuf *m)
1778{
1779	struct ip_moptions imo;
1780	struct in_multi *imm[2];
1781	int error;
1782
1783	VIF_LOCK_ASSERT();
1784
1785	imo.imo_multicast_ifp  = vifp->v_ifp;
1786	imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1787	imo.imo_multicast_loop = 1;
1788	imo.imo_multicast_vif  = -1;
1789	imo.imo_num_memberships = 0;
1790	imo.imo_max_memberships = 2;
1791	imo.imo_membership  = &imm[0];
1792
1793	/*
1794	 * Re-entrancy should not be a problem here, because
1795	 * the packets that we send out and are looped back at us
1796	 * should get rejected because they appear to come from
1797	 * the loopback interface, thus preventing looping.
1798	 */
1799	error = ip_output(m, NULL, &vifp->v_route, IP_FORWARDING, &imo, NULL);
1800	if (mrtdebug & DEBUG_XMIT) {
1801	    log(LOG_DEBUG, "phyint_send on vif %td err %d\n",
1802		vifp - viftable, error);
1803	}
1804}
1805
1806static int
1807X_ip_rsvp_vif(struct socket *so, struct sockopt *sopt)
1808{
1809    int error, vifi;
1810
1811    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
1812	return EOPNOTSUPP;
1813
1814    error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
1815    if (error)
1816	return error;
1817
1818    VIF_LOCK();
1819
1820    if (vifi < 0 || vifi >= numvifs) {	/* Error if vif is invalid */
1821	VIF_UNLOCK();
1822	return EADDRNOTAVAIL;
1823    }
1824
1825    if (sopt->sopt_name == IP_RSVP_VIF_ON) {
1826	/* Check if socket is available. */
1827	if (viftable[vifi].v_rsvpd != NULL) {
1828	    VIF_UNLOCK();
1829	    return EADDRINUSE;
1830	}
1831
1832	viftable[vifi].v_rsvpd = so;
1833	/* This may seem silly, but we need to be sure we don't over-increment
1834	 * the RSVP counter, in case something slips up.
1835	 */
1836	if (!viftable[vifi].v_rsvp_on) {
1837	    viftable[vifi].v_rsvp_on = 1;
1838	    rsvp_on++;
1839	}
1840    } else { /* must be VIF_OFF */
1841	/*
1842	 * XXX as an additional consistency check, one could make sure
1843	 * that viftable[vifi].v_rsvpd == so, otherwise passing so as
1844	 * first parameter is pretty useless.
1845	 */
1846	viftable[vifi].v_rsvpd = NULL;
1847	/*
1848	 * This may seem silly, but we need to be sure we don't over-decrement
1849	 * the RSVP counter, in case something slips up.
1850	 */
1851	if (viftable[vifi].v_rsvp_on) {
1852	    viftable[vifi].v_rsvp_on = 0;
1853	    rsvp_on--;
1854	}
1855    }
1856    VIF_UNLOCK();
1857    return 0;
1858}
1859
1860static void
1861X_ip_rsvp_force_done(struct socket *so)
1862{
1863    int vifi;
1864
1865    /* Don't bother if it is not the right type of socket. */
1866    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
1867	return;
1868
1869    VIF_LOCK();
1870
1871    /* The socket may be attached to more than one vif...this
1872     * is perfectly legal.
1873     */
1874    for (vifi = 0; vifi < numvifs; vifi++) {
1875	if (viftable[vifi].v_rsvpd == so) {
1876	    viftable[vifi].v_rsvpd = NULL;
1877	    /* This may seem silly, but we need to be sure we don't
1878	     * over-decrement the RSVP counter, in case something slips up.
1879	     */
1880	    if (viftable[vifi].v_rsvp_on) {
1881		viftable[vifi].v_rsvp_on = 0;
1882		rsvp_on--;
1883	    }
1884	}
1885    }
1886
1887    VIF_UNLOCK();
1888}
1889
1890static void
1891X_rsvp_input(struct mbuf *m, int off)
1892{
1893    int vifi;
1894    struct ip *ip = mtod(m, struct ip *);
1895    struct sockaddr_in rsvp_src = { sizeof rsvp_src, AF_INET };
1896    struct ifnet *ifp;
1897
1898    if (rsvpdebug)
1899	printf("rsvp_input: rsvp_on %d\n",rsvp_on);
1900
1901    /* Can still get packets with rsvp_on = 0 if there is a local member
1902     * of the group to which the RSVP packet is addressed.  But in this
1903     * case we want to throw the packet away.
1904     */
1905    if (!rsvp_on) {
1906	m_freem(m);
1907	return;
1908    }
1909
1910    if (rsvpdebug)
1911	printf("rsvp_input: check vifs\n");
1912
1913#ifdef DIAGNOSTIC
1914    M_ASSERTPKTHDR(m);
1915#endif
1916
1917    ifp = m->m_pkthdr.rcvif;
1918
1919    VIF_LOCK();
1920    /* Find which vif the packet arrived on. */
1921    for (vifi = 0; vifi < numvifs; vifi++)
1922	if (viftable[vifi].v_ifp == ifp)
1923	    break;
1924
1925    if (vifi == numvifs || viftable[vifi].v_rsvpd == NULL) {
1926	/*
1927	 * Drop the lock here to avoid holding it across rip_input.
1928	 * This could make rsvpdebug printfs wrong.  If you care,
1929	 * record the state of stuff before dropping the lock.
1930	 */
1931	VIF_UNLOCK();
1932	/*
1933	 * If the old-style non-vif-associated socket is set,
1934	 * then use it.  Otherwise, drop packet since there
1935	 * is no specific socket for this vif.
1936	 */
1937	if (ip_rsvpd != NULL) {
1938	    if (rsvpdebug)
1939		printf("rsvp_input: Sending packet up old-style socket\n");
1940	    rip_input(m, off);  /* xxx */
1941	} else {
1942	    if (rsvpdebug && vifi == numvifs)
1943		printf("rsvp_input: Can't find vif for packet.\n");
1944	    else if (rsvpdebug && viftable[vifi].v_rsvpd == NULL)
1945		printf("rsvp_input: No socket defined for vif %d\n",vifi);
1946	    m_freem(m);
1947	}
1948	return;
1949    }
1950    rsvp_src.sin_addr = ip->ip_src;
1951
1952    if (rsvpdebug && m)
1953	printf("rsvp_input: m->m_len = %d, sbspace() = %ld\n",
1954	       m->m_len,sbspace(&(viftable[vifi].v_rsvpd->so_rcv)));
1955
1956    if (socket_send(viftable[vifi].v_rsvpd, m, &rsvp_src) < 0) {
1957	if (rsvpdebug)
1958	    printf("rsvp_input: Failed to append to socket\n");
1959    } else {
1960	if (rsvpdebug)
1961	    printf("rsvp_input: send packet up\n");
1962    }
1963    VIF_UNLOCK();
1964}
1965
1966/*
1967 * Code for bandwidth monitors
1968 */
1969
1970/*
1971 * Define common interface for timeval-related methods
1972 */
1973#define	BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
1974#define	BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
1975#define	BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
1976
1977static uint32_t
1978compute_bw_meter_flags(struct bw_upcall *req)
1979{
1980    uint32_t flags = 0;
1981
1982    if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
1983	flags |= BW_METER_UNIT_PACKETS;
1984    if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
1985	flags |= BW_METER_UNIT_BYTES;
1986    if (req->bu_flags & BW_UPCALL_GEQ)
1987	flags |= BW_METER_GEQ;
1988    if (req->bu_flags & BW_UPCALL_LEQ)
1989	flags |= BW_METER_LEQ;
1990
1991    return flags;
1992}
1993
1994/*
1995 * Add a bw_meter entry
1996 */
1997static int
1998add_bw_upcall(struct bw_upcall *req)
1999{
2000    struct mfc *mfc;
2001    struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
2002		BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
2003    struct timeval now;
2004    struct bw_meter *x;
2005    uint32_t flags;
2006
2007    if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2008	return EOPNOTSUPP;
2009
2010    /* Test if the flags are valid */
2011    if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
2012	return EINVAL;
2013    if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
2014	return EINVAL;
2015    if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2016	    == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2017	return EINVAL;
2018
2019    /* Test if the threshold time interval is valid */
2020    if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
2021	return EINVAL;
2022
2023    flags = compute_bw_meter_flags(req);
2024
2025    /*
2026     * Find if we have already same bw_meter entry
2027     */
2028    MFC_LOCK();
2029    mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2030    if (mfc == NULL) {
2031	MFC_UNLOCK();
2032	return EADDRNOTAVAIL;
2033    }
2034    for (x = mfc->mfc_bw_meter; x != NULL; x = x->bm_mfc_next) {
2035	if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2036			   &req->bu_threshold.b_time, ==)) &&
2037	    (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2038	    (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2039	    (x->bm_flags & BW_METER_USER_FLAGS) == flags)  {
2040	    MFC_UNLOCK();
2041	    return 0;		/* XXX Already installed */
2042	}
2043    }
2044
2045    /* Allocate the new bw_meter entry */
2046    x = (struct bw_meter *)malloc(sizeof(*x), M_BWMETER, M_NOWAIT);
2047    if (x == NULL) {
2048	MFC_UNLOCK();
2049	return ENOBUFS;
2050    }
2051
2052    /* Set the new bw_meter entry */
2053    x->bm_threshold.b_time = req->bu_threshold.b_time;
2054    GET_TIME(now);
2055    x->bm_start_time = now;
2056    x->bm_threshold.b_packets = req->bu_threshold.b_packets;
2057    x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
2058    x->bm_measured.b_packets = 0;
2059    x->bm_measured.b_bytes = 0;
2060    x->bm_flags = flags;
2061    x->bm_time_next = NULL;
2062    x->bm_time_hash = BW_METER_BUCKETS;
2063
2064    /* Add the new bw_meter entry to the front of entries for this MFC */
2065    x->bm_mfc = mfc;
2066    x->bm_mfc_next = mfc->mfc_bw_meter;
2067    mfc->mfc_bw_meter = x;
2068    schedule_bw_meter(x, &now);
2069    MFC_UNLOCK();
2070
2071    return 0;
2072}
2073
2074static void
2075free_bw_list(struct bw_meter *list)
2076{
2077    while (list != NULL) {
2078	struct bw_meter *x = list;
2079
2080	list = list->bm_mfc_next;
2081	unschedule_bw_meter(x);
2082	free(x, M_BWMETER);
2083    }
2084}
2085
2086/*
2087 * Delete one or multiple bw_meter entries
2088 */
2089static int
2090del_bw_upcall(struct bw_upcall *req)
2091{
2092    struct mfc *mfc;
2093    struct bw_meter *x;
2094
2095    if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2096	return EOPNOTSUPP;
2097
2098    MFC_LOCK();
2099    /* Find the corresponding MFC entry */
2100    mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2101    if (mfc == NULL) {
2102	MFC_UNLOCK();
2103	return EADDRNOTAVAIL;
2104    } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2105	/*
2106	 * Delete all bw_meter entries for this mfc
2107	 */
2108	struct bw_meter *list;
2109
2110	list = mfc->mfc_bw_meter;
2111	mfc->mfc_bw_meter = NULL;
2112	free_bw_list(list);
2113	MFC_UNLOCK();
2114	return 0;
2115    } else {			/* Delete a single bw_meter entry */
2116	struct bw_meter *prev;
2117	uint32_t flags = 0;
2118
2119	flags = compute_bw_meter_flags(req);
2120
2121	/* Find the bw_meter entry to delete */
2122	for (prev = NULL, x = mfc->mfc_bw_meter; x != NULL;
2123	     prev = x, x = x->bm_mfc_next) {
2124	    if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2125			       &req->bu_threshold.b_time, ==)) &&
2126		(x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2127		(x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2128		(x->bm_flags & BW_METER_USER_FLAGS) == flags)
2129		break;
2130	}
2131	if (x != NULL) { /* Delete entry from the list for this MFC */
2132	    if (prev != NULL)
2133		prev->bm_mfc_next = x->bm_mfc_next;	/* remove from middle*/
2134	    else
2135		x->bm_mfc->mfc_bw_meter = x->bm_mfc_next;/* new head of list */
2136
2137	    unschedule_bw_meter(x);
2138	    MFC_UNLOCK();
2139	    /* Free the bw_meter entry */
2140	    free(x, M_BWMETER);
2141	    return 0;
2142	} else {
2143	    MFC_UNLOCK();
2144	    return EINVAL;
2145	}
2146    }
2147    /* NOTREACHED */
2148}
2149
2150/*
2151 * Perform bandwidth measurement processing that may result in an upcall
2152 */
2153static void
2154bw_meter_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2155{
2156    struct timeval delta;
2157
2158    MFC_LOCK_ASSERT();
2159
2160    delta = *nowp;
2161    BW_TIMEVALDECR(&delta, &x->bm_start_time);
2162
2163    if (x->bm_flags & BW_METER_GEQ) {
2164	/*
2165	 * Processing for ">=" type of bw_meter entry
2166	 */
2167	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2168	    /* Reset the bw_meter entry */
2169	    x->bm_start_time = *nowp;
2170	    x->bm_measured.b_packets = 0;
2171	    x->bm_measured.b_bytes = 0;
2172	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2173	}
2174
2175	/* Record that a packet is received */
2176	x->bm_measured.b_packets++;
2177	x->bm_measured.b_bytes += plen;
2178
2179	/*
2180	 * Test if we should deliver an upcall
2181	 */
2182	if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2183	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2184		 (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2185		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2186		 (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2187		/* Prepare an upcall for delivery */
2188		bw_meter_prepare_upcall(x, nowp);
2189		x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2190	    }
2191	}
2192    } else if (x->bm_flags & BW_METER_LEQ) {
2193	/*
2194	 * Processing for "<=" type of bw_meter entry
2195	 */
2196	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2197	    /*
2198	     * We are behind time with the multicast forwarding table
2199	     * scanning for "<=" type of bw_meter entries, so test now
2200	     * if we should deliver an upcall.
2201	     */
2202	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2203		 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2204		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2205		 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2206		/* Prepare an upcall for delivery */
2207		bw_meter_prepare_upcall(x, nowp);
2208	    }
2209	    /* Reschedule the bw_meter entry */
2210	    unschedule_bw_meter(x);
2211	    schedule_bw_meter(x, nowp);
2212	}
2213
2214	/* Record that a packet is received */
2215	x->bm_measured.b_packets++;
2216	x->bm_measured.b_bytes += plen;
2217
2218	/*
2219	 * Test if we should restart the measuring interval
2220	 */
2221	if ((x->bm_flags & BW_METER_UNIT_PACKETS &&
2222	     x->bm_measured.b_packets <= x->bm_threshold.b_packets) ||
2223	    (x->bm_flags & BW_METER_UNIT_BYTES &&
2224	     x->bm_measured.b_bytes <= x->bm_threshold.b_bytes)) {
2225	    /* Don't restart the measuring interval */
2226	} else {
2227	    /* Do restart the measuring interval */
2228	    /*
2229	     * XXX: note that we don't unschedule and schedule, because this
2230	     * might be too much overhead per packet. Instead, when we process
2231	     * all entries for a given timer hash bin, we check whether it is
2232	     * really a timeout. If not, we reschedule at that time.
2233	     */
2234	    x->bm_start_time = *nowp;
2235	    x->bm_measured.b_packets = 0;
2236	    x->bm_measured.b_bytes = 0;
2237	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2238	}
2239    }
2240}
2241
2242/*
2243 * Prepare a bandwidth-related upcall
2244 */
2245static void
2246bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2247{
2248    struct timeval delta;
2249    struct bw_upcall *u;
2250
2251    MFC_LOCK_ASSERT();
2252
2253    /*
2254     * Compute the measured time interval
2255     */
2256    delta = *nowp;
2257    BW_TIMEVALDECR(&delta, &x->bm_start_time);
2258
2259    /*
2260     * If there are too many pending upcalls, deliver them now
2261     */
2262    if (bw_upcalls_n >= BW_UPCALLS_MAX)
2263	bw_upcalls_send();
2264
2265    /*
2266     * Set the bw_upcall entry
2267     */
2268    u = &bw_upcalls[bw_upcalls_n++];
2269    u->bu_src = x->bm_mfc->mfc_origin;
2270    u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2271    u->bu_threshold.b_time = x->bm_threshold.b_time;
2272    u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2273    u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2274    u->bu_measured.b_time = delta;
2275    u->bu_measured.b_packets = x->bm_measured.b_packets;
2276    u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2277    u->bu_flags = 0;
2278    if (x->bm_flags & BW_METER_UNIT_PACKETS)
2279	u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2280    if (x->bm_flags & BW_METER_UNIT_BYTES)
2281	u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2282    if (x->bm_flags & BW_METER_GEQ)
2283	u->bu_flags |= BW_UPCALL_GEQ;
2284    if (x->bm_flags & BW_METER_LEQ)
2285	u->bu_flags |= BW_UPCALL_LEQ;
2286}
2287
2288/*
2289 * Send the pending bandwidth-related upcalls
2290 */
2291static void
2292bw_upcalls_send(void)
2293{
2294    struct mbuf *m;
2295    int len = bw_upcalls_n * sizeof(bw_upcalls[0]);
2296    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2297    static struct igmpmsg igmpmsg = { 0,		/* unused1 */
2298				      0,		/* unused2 */
2299				      IGMPMSG_BW_UPCALL,/* im_msgtype */
2300				      0,		/* im_mbz  */
2301				      0,		/* im_vif  */
2302				      0,		/* unused3 */
2303				      { 0 },		/* im_src  */
2304				      { 0 } };		/* im_dst  */
2305
2306    MFC_LOCK_ASSERT();
2307
2308    if (bw_upcalls_n == 0)
2309	return;			/* No pending upcalls */
2310
2311    bw_upcalls_n = 0;
2312
2313    /*
2314     * Allocate a new mbuf, initialize it with the header and
2315     * the payload for the pending calls.
2316     */
2317    MGETHDR(m, M_DONTWAIT, MT_DATA);
2318    if (m == NULL) {
2319	log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2320	return;
2321    }
2322
2323    m->m_len = m->m_pkthdr.len = 0;
2324    m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2325    m_copyback(m, sizeof(struct igmpmsg), len, (caddr_t)&bw_upcalls[0]);
2326
2327    /*
2328     * Send the upcalls
2329     * XXX do we need to set the address in k_igmpsrc ?
2330     */
2331    mrtstat.mrts_upcalls++;
2332    if (socket_send(ip_mrouter, m, &k_igmpsrc) < 0) {
2333	log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2334	++mrtstat.mrts_upq_sockfull;
2335    }
2336}
2337
2338/*
2339 * Compute the timeout hash value for the bw_meter entries
2340 */
2341#define	BW_METER_TIMEHASH(bw_meter, hash)				\
2342    do {								\
2343	struct timeval next_timeval = (bw_meter)->bm_start_time;	\
2344									\
2345	BW_TIMEVALADD(&next_timeval, &(bw_meter)->bm_threshold.b_time); \
2346	(hash) = next_timeval.tv_sec;					\
2347	if (next_timeval.tv_usec)					\
2348	    (hash)++; /* XXX: make sure we don't timeout early */	\
2349	(hash) %= BW_METER_BUCKETS;					\
2350    } while (0)
2351
2352/*
2353 * Schedule a timer to process periodically bw_meter entry of type "<="
2354 * by linking the entry in the proper hash bucket.
2355 */
2356static void
2357schedule_bw_meter(struct bw_meter *x, struct timeval *nowp)
2358{
2359    int time_hash;
2360
2361    MFC_LOCK_ASSERT();
2362
2363    if (!(x->bm_flags & BW_METER_LEQ))
2364	return;		/* XXX: we schedule timers only for "<=" entries */
2365
2366    /*
2367     * Reset the bw_meter entry
2368     */
2369    x->bm_start_time = *nowp;
2370    x->bm_measured.b_packets = 0;
2371    x->bm_measured.b_bytes = 0;
2372    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2373
2374    /*
2375     * Compute the timeout hash value and insert the entry
2376     */
2377    BW_METER_TIMEHASH(x, time_hash);
2378    x->bm_time_next = bw_meter_timers[time_hash];
2379    bw_meter_timers[time_hash] = x;
2380    x->bm_time_hash = time_hash;
2381}
2382
2383/*
2384 * Unschedule the periodic timer that processes bw_meter entry of type "<="
2385 * by removing the entry from the proper hash bucket.
2386 */
2387static void
2388unschedule_bw_meter(struct bw_meter *x)
2389{
2390    int time_hash;
2391    struct bw_meter *prev, *tmp;
2392
2393    MFC_LOCK_ASSERT();
2394
2395    if (!(x->bm_flags & BW_METER_LEQ))
2396	return;		/* XXX: we schedule timers only for "<=" entries */
2397
2398    /*
2399     * Compute the timeout hash value and delete the entry
2400     */
2401    time_hash = x->bm_time_hash;
2402    if (time_hash >= BW_METER_BUCKETS)
2403	return;		/* Entry was not scheduled */
2404
2405    for (prev = NULL, tmp = bw_meter_timers[time_hash];
2406	     tmp != NULL; prev = tmp, tmp = tmp->bm_time_next)
2407	if (tmp == x)
2408	    break;
2409
2410    if (tmp == NULL)
2411	panic("unschedule_bw_meter: bw_meter entry not found");
2412
2413    if (prev != NULL)
2414	prev->bm_time_next = x->bm_time_next;
2415    else
2416	bw_meter_timers[time_hash] = x->bm_time_next;
2417
2418    x->bm_time_next = NULL;
2419    x->bm_time_hash = BW_METER_BUCKETS;
2420}
2421
2422
2423/*
2424 * Process all "<=" type of bw_meter that should be processed now,
2425 * and for each entry prepare an upcall if necessary. Each processed
2426 * entry is rescheduled again for the (periodic) processing.
2427 *
2428 * This is run periodically (once per second normally). On each round,
2429 * all the potentially matching entries are in the hash slot that we are
2430 * looking at.
2431 */
2432static void
2433bw_meter_process()
2434{
2435    static uint32_t last_tv_sec;	/* last time we processed this */
2436
2437    uint32_t loops;
2438    int i;
2439    struct timeval now, process_endtime;
2440
2441    GET_TIME(now);
2442    if (last_tv_sec == now.tv_sec)
2443	return;		/* nothing to do */
2444
2445    loops = now.tv_sec - last_tv_sec;
2446    last_tv_sec = now.tv_sec;
2447    if (loops > BW_METER_BUCKETS)
2448	loops = BW_METER_BUCKETS;
2449
2450    MFC_LOCK();
2451    /*
2452     * Process all bins of bw_meter entries from the one after the last
2453     * processed to the current one. On entry, i points to the last bucket
2454     * visited, so we need to increment i at the beginning of the loop.
2455     */
2456    for (i = (now.tv_sec - loops) % BW_METER_BUCKETS; loops > 0; loops--) {
2457	struct bw_meter *x, *tmp_list;
2458
2459	if (++i >= BW_METER_BUCKETS)
2460	    i = 0;
2461
2462	/* Disconnect the list of bw_meter entries from the bin */
2463	tmp_list = bw_meter_timers[i];
2464	bw_meter_timers[i] = NULL;
2465
2466	/* Process the list of bw_meter entries */
2467	while (tmp_list != NULL) {
2468	    x = tmp_list;
2469	    tmp_list = tmp_list->bm_time_next;
2470
2471	    /* Test if the time interval is over */
2472	    process_endtime = x->bm_start_time;
2473	    BW_TIMEVALADD(&process_endtime, &x->bm_threshold.b_time);
2474	    if (BW_TIMEVALCMP(&process_endtime, &now, >)) {
2475		/* Not yet: reschedule, but don't reset */
2476		int time_hash;
2477
2478		BW_METER_TIMEHASH(x, time_hash);
2479		if (time_hash == i && process_endtime.tv_sec == now.tv_sec) {
2480		    /*
2481		     * XXX: somehow the bin processing is a bit ahead of time.
2482		     * Put the entry in the next bin.
2483		     */
2484		    if (++time_hash >= BW_METER_BUCKETS)
2485			time_hash = 0;
2486		}
2487		x->bm_time_next = bw_meter_timers[time_hash];
2488		bw_meter_timers[time_hash] = x;
2489		x->bm_time_hash = time_hash;
2490
2491		continue;
2492	    }
2493
2494	    /*
2495	     * Test if we should deliver an upcall
2496	     */
2497	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2498		 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2499		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2500		 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2501		/* Prepare an upcall for delivery */
2502		bw_meter_prepare_upcall(x, &now);
2503	    }
2504
2505	    /*
2506	     * Reschedule for next processing
2507	     */
2508	    schedule_bw_meter(x, &now);
2509	}
2510    }
2511
2512    /* Send all upcalls that are pending delivery */
2513    bw_upcalls_send();
2514
2515    MFC_UNLOCK();
2516}
2517
2518/*
2519 * A periodic function for sending all upcalls that are pending delivery
2520 */
2521static void
2522expire_bw_upcalls_send(void *unused)
2523{
2524    MFC_LOCK();
2525    bw_upcalls_send();
2526    MFC_UNLOCK();
2527
2528    callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
2529	expire_bw_upcalls_send, NULL);
2530}
2531
2532/*
2533 * A periodic function for periodic scanning of the multicast forwarding
2534 * table for processing all "<=" bw_meter entries.
2535 */
2536static void
2537expire_bw_meter_process(void *unused)
2538{
2539    if (mrt_api_config & MRT_MFC_BW_UPCALL)
2540	bw_meter_process();
2541
2542    callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
2543}
2544
2545/*
2546 * End of bandwidth monitoring code
2547 */
2548
2549/*
2550 * Send the packet up to the user daemon, or eventually do kernel encapsulation
2551 *
2552 */
2553static int
2554pim_register_send(struct ip *ip, struct vif *vifp,
2555	struct mbuf *m, struct mfc *rt)
2556{
2557    struct mbuf *mb_copy, *mm;
2558
2559    if (mrtdebug & DEBUG_PIM)
2560	log(LOG_DEBUG, "pim_register_send: ");
2561
2562    /*
2563     * Do not send IGMP_WHOLEPKT notifications to userland, if the
2564     * rendezvous point was unspecified, and we were told not to.
2565     */
2566    if (pim_squelch_wholepkt != 0 && (mrt_api_config & MRT_MFC_RP) &&
2567	(rt->mfc_rp.s_addr == INADDR_ANY))
2568	return 0;
2569
2570    mb_copy = pim_register_prepare(ip, m);
2571    if (mb_copy == NULL)
2572	return ENOBUFS;
2573
2574    /*
2575     * Send all the fragments. Note that the mbuf for each fragment
2576     * is freed by the sending machinery.
2577     */
2578    for (mm = mb_copy; mm; mm = mb_copy) {
2579	mb_copy = mm->m_nextpkt;
2580	mm->m_nextpkt = 0;
2581	mm = m_pullup(mm, sizeof(struct ip));
2582	if (mm != NULL) {
2583	    ip = mtod(mm, struct ip *);
2584	    if ((mrt_api_config & MRT_MFC_RP) &&
2585		(rt->mfc_rp.s_addr != INADDR_ANY)) {
2586		pim_register_send_rp(ip, vifp, mm, rt);
2587	    } else {
2588		pim_register_send_upcall(ip, vifp, mm, rt);
2589	    }
2590	}
2591    }
2592
2593    return 0;
2594}
2595
2596/*
2597 * Return a copy of the data packet that is ready for PIM Register
2598 * encapsulation.
2599 * XXX: Note that in the returned copy the IP header is a valid one.
2600 */
2601static struct mbuf *
2602pim_register_prepare(struct ip *ip, struct mbuf *m)
2603{
2604    struct mbuf *mb_copy = NULL;
2605    int mtu;
2606
2607    /* Take care of delayed checksums */
2608    if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2609	in_delayed_cksum(m);
2610	m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2611    }
2612
2613    /*
2614     * Copy the old packet & pullup its IP header into the
2615     * new mbuf so we can modify it.
2616     */
2617    mb_copy = m_copypacket(m, M_DONTWAIT);
2618    if (mb_copy == NULL)
2619	return NULL;
2620    mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2621    if (mb_copy == NULL)
2622	return NULL;
2623
2624    /* take care of the TTL */
2625    ip = mtod(mb_copy, struct ip *);
2626    --ip->ip_ttl;
2627
2628    /* Compute the MTU after the PIM Register encapsulation */
2629    mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2630
2631    if (ip->ip_len <= mtu) {
2632	/* Turn the IP header into a valid one */
2633	ip->ip_len = htons(ip->ip_len);
2634	ip->ip_off = htons(ip->ip_off);
2635	ip->ip_sum = 0;
2636	ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2637    } else {
2638	/* Fragment the packet */
2639	if (ip_fragment(ip, &mb_copy, mtu, 0, CSUM_DELAY_IP) != 0) {
2640	    m_freem(mb_copy);
2641	    return NULL;
2642	}
2643    }
2644    return mb_copy;
2645}
2646
2647/*
2648 * Send an upcall with the data packet to the user-level process.
2649 */
2650static int
2651pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2652	struct mbuf *mb_copy, struct mfc *rt)
2653{
2654    struct mbuf *mb_first;
2655    int len = ntohs(ip->ip_len);
2656    struct igmpmsg *im;
2657    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2658
2659    VIF_LOCK_ASSERT();
2660
2661    /*
2662     * Add a new mbuf with an upcall header
2663     */
2664    MGETHDR(mb_first, M_DONTWAIT, MT_DATA);
2665    if (mb_first == NULL) {
2666	m_freem(mb_copy);
2667	return ENOBUFS;
2668    }
2669    mb_first->m_data += max_linkhdr;
2670    mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2671    mb_first->m_len = sizeof(struct igmpmsg);
2672    mb_first->m_next = mb_copy;
2673
2674    /* Send message to routing daemon */
2675    im = mtod(mb_first, struct igmpmsg *);
2676    im->im_msgtype	= IGMPMSG_WHOLEPKT;
2677    im->im_mbz		= 0;
2678    im->im_vif		= vifp - viftable;
2679    im->im_src		= ip->ip_src;
2680    im->im_dst		= ip->ip_dst;
2681
2682    k_igmpsrc.sin_addr	= ip->ip_src;
2683
2684    mrtstat.mrts_upcalls++;
2685
2686    if (socket_send(ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2687	if (mrtdebug & DEBUG_PIM)
2688	    log(LOG_WARNING,
2689		"mcast: pim_register_send_upcall: ip_mrouter socket queue full");
2690	++mrtstat.mrts_upq_sockfull;
2691	return ENOBUFS;
2692    }
2693
2694    /* Keep statistics */
2695    pimstat.pims_snd_registers_msgs++;
2696    pimstat.pims_snd_registers_bytes += len;
2697
2698    return 0;
2699}
2700
2701/*
2702 * Encapsulate the data packet in PIM Register message and send it to the RP.
2703 */
2704static int
2705pim_register_send_rp(struct ip *ip, struct vif *vifp,
2706	struct mbuf *mb_copy, struct mfc *rt)
2707{
2708    struct mbuf *mb_first;
2709    struct ip *ip_outer;
2710    struct pim_encap_pimhdr *pimhdr;
2711    int len = ntohs(ip->ip_len);
2712    vifi_t vifi = rt->mfc_parent;
2713
2714    VIF_LOCK_ASSERT();
2715
2716    if ((vifi >= numvifs) || (viftable[vifi].v_lcl_addr.s_addr == 0)) {
2717	m_freem(mb_copy);
2718	return EADDRNOTAVAIL;		/* The iif vif is invalid */
2719    }
2720
2721    /*
2722     * Add a new mbuf with the encapsulating header
2723     */
2724    MGETHDR(mb_first, M_DONTWAIT, MT_DATA);
2725    if (mb_first == NULL) {
2726	m_freem(mb_copy);
2727	return ENOBUFS;
2728    }
2729    mb_first->m_data += max_linkhdr;
2730    mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2731    mb_first->m_next = mb_copy;
2732
2733    mb_first->m_pkthdr.len = len + mb_first->m_len;
2734
2735    /*
2736     * Fill in the encapsulating IP and PIM header
2737     */
2738    ip_outer = mtod(mb_first, struct ip *);
2739    *ip_outer = pim_encap_iphdr;
2740    ip_outer->ip_id = ip_newid();
2741    ip_outer->ip_len = len + sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2742    ip_outer->ip_src = viftable[vifi].v_lcl_addr;
2743    ip_outer->ip_dst = rt->mfc_rp;
2744    /*
2745     * Copy the inner header TOS to the outer header, and take care of the
2746     * IP_DF bit.
2747     */
2748    ip_outer->ip_tos = ip->ip_tos;
2749    if (ntohs(ip->ip_off) & IP_DF)
2750	ip_outer->ip_off |= IP_DF;
2751    pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2752					 + sizeof(pim_encap_iphdr));
2753    *pimhdr = pim_encap_pimhdr;
2754    /* If the iif crosses a border, set the Border-bit */
2755    if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & mrt_api_config)
2756	pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
2757
2758    mb_first->m_data += sizeof(pim_encap_iphdr);
2759    pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
2760    mb_first->m_data -= sizeof(pim_encap_iphdr);
2761
2762    send_packet(vifp, mb_first);
2763
2764    /* Keep statistics */
2765    pimstat.pims_snd_registers_msgs++;
2766    pimstat.pims_snd_registers_bytes += len;
2767
2768    return 0;
2769}
2770
2771/*
2772 * pim_encapcheck() is called by the encap[46]_input() path at runtime to
2773 * determine if a packet is for PIM; allowing PIM to be dynamically loaded
2774 * into the kernel.
2775 */
2776static int
2777pim_encapcheck(const struct mbuf *m, int off, int proto, void *arg)
2778{
2779
2780#ifdef DIAGNOSTIC
2781    KASSERT(proto == IPPROTO_PIM, ("not for IPPROTO_PIM"));
2782#endif
2783    if (proto != IPPROTO_PIM)
2784	return 0;	/* not for us; reject the datagram. */
2785
2786    return 64;		/* claim the datagram. */
2787}
2788
2789/*
2790 * PIM-SMv2 and PIM-DM messages processing.
2791 * Receives and verifies the PIM control messages, and passes them
2792 * up to the listening socket, using rip_input().
2793 * The only message with special processing is the PIM_REGISTER message
2794 * (used by PIM-SM): the PIM header is stripped off, and the inner packet
2795 * is passed to if_simloop().
2796 */
2797void
2798pim_input(struct mbuf *m, int off)
2799{
2800    struct ip *ip = mtod(m, struct ip *);
2801    struct pim *pim;
2802    int minlen;
2803    int datalen = ip->ip_len;
2804    int ip_tos;
2805    int iphlen = off;
2806
2807    /* Keep statistics */
2808    pimstat.pims_rcv_total_msgs++;
2809    pimstat.pims_rcv_total_bytes += datalen;
2810
2811    /*
2812     * Validate lengths
2813     */
2814    if (datalen < PIM_MINLEN) {
2815	pimstat.pims_rcv_tooshort++;
2816	log(LOG_ERR, "pim_input: packet size too small %d from %lx\n",
2817	    datalen, (u_long)ip->ip_src.s_addr);
2818	m_freem(m);
2819	return;
2820    }
2821
2822    /*
2823     * If the packet is at least as big as a REGISTER, go agead
2824     * and grab the PIM REGISTER header size, to avoid another
2825     * possible m_pullup() later.
2826     *
2827     * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
2828     * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
2829     */
2830    minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
2831    /*
2832     * Get the IP and PIM headers in contiguous memory, and
2833     * possibly the PIM REGISTER header.
2834     */
2835    if ((m->m_flags & M_EXT || m->m_len < minlen) &&
2836	(m = m_pullup(m, minlen)) == 0) {
2837	log(LOG_ERR, "pim_input: m_pullup failure\n");
2838	return;
2839    }
2840    /* m_pullup() may have given us a new mbuf so reset ip. */
2841    ip = mtod(m, struct ip *);
2842    ip_tos = ip->ip_tos;
2843
2844    /* adjust mbuf to point to the PIM header */
2845    m->m_data += iphlen;
2846    m->m_len  -= iphlen;
2847    pim = mtod(m, struct pim *);
2848
2849    /*
2850     * Validate checksum. If PIM REGISTER, exclude the data packet.
2851     *
2852     * XXX: some older PIMv2 implementations don't make this distinction,
2853     * so for compatibility reason perform the checksum over part of the
2854     * message, and if error, then over the whole message.
2855     */
2856    if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
2857	/* do nothing, checksum okay */
2858    } else if (in_cksum(m, datalen)) {
2859	pimstat.pims_rcv_badsum++;
2860	if (mrtdebug & DEBUG_PIM)
2861	    log(LOG_DEBUG, "pim_input: invalid checksum");
2862	m_freem(m);
2863	return;
2864    }
2865
2866    /* PIM version check */
2867    if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
2868	pimstat.pims_rcv_badversion++;
2869	log(LOG_ERR, "pim_input: incorrect version %d, expecting %d\n",
2870	    PIM_VT_V(pim->pim_vt), PIM_VERSION);
2871	m_freem(m);
2872	return;
2873    }
2874
2875    /* restore mbuf back to the outer IP */
2876    m->m_data -= iphlen;
2877    m->m_len  += iphlen;
2878
2879    if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
2880	/*
2881	 * Since this is a REGISTER, we'll make a copy of the register
2882	 * headers ip + pim + u_int32 + encap_ip, to be passed up to the
2883	 * routing daemon.
2884	 */
2885	struct sockaddr_in dst = { sizeof(dst), AF_INET };
2886	struct mbuf *mcp;
2887	struct ip *encap_ip;
2888	u_int32_t *reghdr;
2889	struct ifnet *vifp;
2890
2891	VIF_LOCK();
2892	if ((reg_vif_num >= numvifs) || (reg_vif_num == VIFI_INVALID)) {
2893	    VIF_UNLOCK();
2894	    if (mrtdebug & DEBUG_PIM)
2895		log(LOG_DEBUG,
2896		    "pim_input: register vif not set: %d\n", reg_vif_num);
2897	    m_freem(m);
2898	    return;
2899	}
2900	/* XXX need refcnt? */
2901	vifp = viftable[reg_vif_num].v_ifp;
2902	VIF_UNLOCK();
2903
2904	/*
2905	 * Validate length
2906	 */
2907	if (datalen < PIM_REG_MINLEN) {
2908	    pimstat.pims_rcv_tooshort++;
2909	    pimstat.pims_rcv_badregisters++;
2910	    log(LOG_ERR,
2911		"pim_input: register packet size too small %d from %lx\n",
2912		datalen, (u_long)ip->ip_src.s_addr);
2913	    m_freem(m);
2914	    return;
2915	}
2916
2917	reghdr = (u_int32_t *)(pim + 1);
2918	encap_ip = (struct ip *)(reghdr + 1);
2919
2920	if (mrtdebug & DEBUG_PIM) {
2921	    log(LOG_DEBUG,
2922		"pim_input[register], encap_ip: %lx -> %lx, encap_ip len %d\n",
2923		(u_long)ntohl(encap_ip->ip_src.s_addr),
2924		(u_long)ntohl(encap_ip->ip_dst.s_addr),
2925		ntohs(encap_ip->ip_len));
2926	}
2927
2928	/* verify the version number of the inner packet */
2929	if (encap_ip->ip_v != IPVERSION) {
2930	    pimstat.pims_rcv_badregisters++;
2931	    if (mrtdebug & DEBUG_PIM) {
2932		log(LOG_DEBUG, "pim_input: invalid IP version (%d) "
2933		    "of the inner packet\n", encap_ip->ip_v);
2934	    }
2935	    m_freem(m);
2936	    return;
2937	}
2938
2939	/* verify the inner packet is destined to a mcast group */
2940	if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
2941	    pimstat.pims_rcv_badregisters++;
2942	    if (mrtdebug & DEBUG_PIM)
2943		log(LOG_DEBUG,
2944		    "pim_input: inner packet of register is not "
2945		    "multicast %lx\n",
2946		    (u_long)ntohl(encap_ip->ip_dst.s_addr));
2947	    m_freem(m);
2948	    return;
2949	}
2950
2951	/* If a NULL_REGISTER, pass it to the daemon */
2952	if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
2953	    goto pim_input_to_daemon;
2954
2955	/*
2956	 * Copy the TOS from the outer IP header to the inner IP header.
2957	 */
2958	if (encap_ip->ip_tos != ip_tos) {
2959	    /* Outer TOS -> inner TOS */
2960	    encap_ip->ip_tos = ip_tos;
2961	    /* Recompute the inner header checksum. Sigh... */
2962
2963	    /* adjust mbuf to point to the inner IP header */
2964	    m->m_data += (iphlen + PIM_MINLEN);
2965	    m->m_len  -= (iphlen + PIM_MINLEN);
2966
2967	    encap_ip->ip_sum = 0;
2968	    encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
2969
2970	    /* restore mbuf to point back to the outer IP header */
2971	    m->m_data -= (iphlen + PIM_MINLEN);
2972	    m->m_len  += (iphlen + PIM_MINLEN);
2973	}
2974
2975	/*
2976	 * Decapsulate the inner IP packet and loopback to forward it
2977	 * as a normal multicast packet. Also, make a copy of the
2978	 *     outer_iphdr + pimhdr + reghdr + encap_iphdr
2979	 * to pass to the daemon later, so it can take the appropriate
2980	 * actions (e.g., send back PIM_REGISTER_STOP).
2981	 * XXX: here m->m_data points to the outer IP header.
2982	 */
2983	mcp = m_copy(m, 0, iphlen + PIM_REG_MINLEN);
2984	if (mcp == NULL) {
2985	    log(LOG_ERR,
2986		"pim_input: pim register: could not copy register head\n");
2987	    m_freem(m);
2988	    return;
2989	}
2990
2991	/* Keep statistics */
2992	/* XXX: registers_bytes include only the encap. mcast pkt */
2993	pimstat.pims_rcv_registers_msgs++;
2994	pimstat.pims_rcv_registers_bytes += ntohs(encap_ip->ip_len);
2995
2996	/*
2997	 * forward the inner ip packet; point m_data at the inner ip.
2998	 */
2999	m_adj(m, iphlen + PIM_MINLEN);
3000
3001	if (mrtdebug & DEBUG_PIM) {
3002	    log(LOG_DEBUG,
3003		"pim_input: forwarding decapsulated register: "
3004		"src %lx, dst %lx, vif %d\n",
3005		(u_long)ntohl(encap_ip->ip_src.s_addr),
3006		(u_long)ntohl(encap_ip->ip_dst.s_addr),
3007		reg_vif_num);
3008	}
3009	/* NB: vifp was collected above; can it change on us? */
3010	if_simloop(vifp, m, dst.sin_family, 0);
3011
3012	/* prepare the register head to send to the mrouting daemon */
3013	m = mcp;
3014    }
3015
3016pim_input_to_daemon:
3017    /*
3018     * Pass the PIM message up to the daemon; if it is a Register message,
3019     * pass the 'head' only up to the daemon. This includes the
3020     * outer IP header, PIM header, PIM-Register header and the
3021     * inner IP header.
3022     * XXX: the outer IP header pkt size of a Register is not adjust to
3023     * reflect the fact that the inner multicast data is truncated.
3024     */
3025    rip_input(m, iphlen);
3026
3027    return;
3028}
3029
3030/*
3031 * XXX: This is common code for dealing with initialization for both
3032 * the IPv4 and IPv6 multicast forwarding paths. It could do with cleanup.
3033 */
3034static int
3035ip_mroute_modevent(module_t mod, int type, void *unused)
3036{
3037    switch (type) {
3038    case MOD_LOAD:
3039	MROUTER_LOCK_INIT();
3040	MFC_LOCK_INIT();
3041	VIF_LOCK_INIT();
3042	ip_mrouter_reset();
3043	TUNABLE_ULONG_FETCH("net.inet.pim.squelch_wholepkt",
3044	    &pim_squelch_wholepkt);
3045
3046	pim_encap_cookie = encap_attach_func(AF_INET, IPPROTO_PIM,
3047	    pim_encapcheck, &in_pim_protosw, NULL);
3048	if (pim_encap_cookie == NULL) {
3049		printf("ip_mroute: unable to attach pim encap\n");
3050		VIF_LOCK_DESTROY();
3051		MFC_LOCK_DESTROY();
3052		MROUTER_LOCK_DESTROY();
3053		return (EINVAL);
3054	}
3055
3056#ifdef INET6
3057	pim6_encap_cookie = encap_attach_func(AF_INET6, IPPROTO_PIM,
3058	    pim_encapcheck, (struct protosw *)&in6_pim_protosw, NULL);
3059	if (pim6_encap_cookie == NULL) {
3060		printf("ip_mroute: unable to attach pim6 encap\n");
3061		if (pim_encap_cookie) {
3062		    encap_detach(pim_encap_cookie);
3063		    pim_encap_cookie = NULL;
3064		}
3065		VIF_LOCK_DESTROY();
3066		MFC_LOCK_DESTROY();
3067		MROUTER_LOCK_DESTROY();
3068		return (EINVAL);
3069	}
3070#endif
3071
3072	ip_mcast_src = X_ip_mcast_src;
3073	ip_mforward = X_ip_mforward;
3074	ip_mrouter_done = X_ip_mrouter_done;
3075	ip_mrouter_get = X_ip_mrouter_get;
3076	ip_mrouter_set = X_ip_mrouter_set;
3077
3078#ifdef INET6
3079	ip6_mforward = X_ip6_mforward;
3080	ip6_mrouter_done = X_ip6_mrouter_done;
3081	ip6_mrouter_get = X_ip6_mrouter_get;
3082	ip6_mrouter_set = X_ip6_mrouter_set;
3083	mrt6_ioctl = X_mrt6_ioctl;
3084#endif
3085
3086	ip_rsvp_force_done = X_ip_rsvp_force_done;
3087	ip_rsvp_vif = X_ip_rsvp_vif;
3088
3089	legal_vif_num = X_legal_vif_num;
3090	mrt_ioctl = X_mrt_ioctl;
3091	rsvp_input_p = X_rsvp_input;
3092	break;
3093
3094    case MOD_UNLOAD:
3095	/*
3096	 * Typically module unload happens after the user-level
3097	 * process has shutdown the kernel services (the check
3098	 * below insures someone can't just yank the module out
3099	 * from under a running process).  But if the module is
3100	 * just loaded and then unloaded w/o starting up a user
3101	 * process we still need to cleanup.
3102	 */
3103	if (ip_mrouter
3104#ifdef INET6
3105	    || ip6_mrouter
3106#endif
3107	)
3108	    return EINVAL;
3109
3110#ifdef INET6
3111	if (pim6_encap_cookie) {
3112	    encap_detach(pim6_encap_cookie);
3113	    pim6_encap_cookie = NULL;
3114	}
3115	X_ip6_mrouter_done();
3116	ip6_mforward = NULL;
3117	ip6_mrouter_done = NULL;
3118	ip6_mrouter_get = NULL;
3119	ip6_mrouter_set = NULL;
3120	mrt6_ioctl = NULL;
3121#endif
3122
3123	if (pim_encap_cookie) {
3124	    encap_detach(pim_encap_cookie);
3125	    pim_encap_cookie = NULL;
3126	}
3127	X_ip_mrouter_done();
3128	ip_mcast_src = NULL;
3129	ip_mforward = NULL;
3130	ip_mrouter_done = NULL;
3131	ip_mrouter_get = NULL;
3132	ip_mrouter_set = NULL;
3133
3134	ip_rsvp_force_done = NULL;
3135	ip_rsvp_vif = NULL;
3136
3137	legal_vif_num = NULL;
3138	mrt_ioctl = NULL;
3139	rsvp_input_p = NULL;
3140
3141	VIF_LOCK_DESTROY();
3142	MFC_LOCK_DESTROY();
3143	MROUTER_LOCK_DESTROY();
3144	break;
3145
3146    default:
3147	return EOPNOTSUPP;
3148    }
3149    return 0;
3150}
3151
3152static moduledata_t ip_mroutemod = {
3153    "ip_mroute",
3154    ip_mroute_modevent,
3155    0
3156};
3157DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PSEUDO, SI_ORDER_ANY);
3158