ip_mroute.c revision 183550
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
56#include <sys/cdefs.h>
57__FBSDID("$FreeBSD: head/sys/netinet/ip_mroute.c 183550 2008-10-02 15:37:58Z zec $");
58
59#include "opt_inet.h"
60#include "opt_inet6.h"
61#include "opt_mac.h"
62#include "opt_mrouting.h"
63
64#define _PIM_VT 1
65
66#include <sys/param.h>
67#include <sys/kernel.h>
68#include <sys/lock.h>
69#include <sys/malloc.h>
70#include <sys/mbuf.h>
71#include <sys/module.h>
72#include <sys/priv.h>
73#include <sys/protosw.h>
74#include <sys/signalvar.h>
75#include <sys/socket.h>
76#include <sys/socketvar.h>
77#include <sys/sockio.h>
78#include <sys/sx.h>
79#include <sys/sysctl.h>
80#include <sys/syslog.h>
81#include <sys/systm.h>
82#include <sys/time.h>
83#include <sys/vimage.h>
84#include <net/if.h>
85#include <net/netisr.h>
86#include <net/route.h>
87#include <netinet/in.h>
88#include <netinet/igmp.h>
89#include <netinet/in_systm.h>
90#include <netinet/in_var.h>
91#include <netinet/ip.h>
92#include <netinet/ip_encap.h>
93#include <netinet/ip_mroute.h>
94#include <netinet/ip_var.h>
95#include <netinet/ip_options.h>
96#include <netinet/pim.h>
97#include <netinet/pim_var.h>
98#include <netinet/udp.h>
99#ifdef INET6
100#include <netinet/ip6.h>
101#include <netinet6/in6_var.h>
102#include <netinet6/ip6_mroute.h>
103#include <netinet6/ip6_var.h>
104#endif
105#include <machine/in_cksum.h>
106
107#include <security/mac/mac_framework.h>
108
109/*
110 * Control debugging code for rsvp and multicast routing code.
111 * Can only set them with the debugger.
112 */
113static u_int    rsvpdebug;		/* non-zero enables debugging	*/
114
115static u_int	mrtdebug;		/* any set of the flags below	*/
116#define		DEBUG_MFC	0x02
117#define		DEBUG_FORWARD	0x04
118#define		DEBUG_EXPIRE	0x08
119#define		DEBUG_XMIT	0x10
120#define		DEBUG_PIM	0x20
121
122#define		VIFI_INVALID	((vifi_t) -1)
123
124#define M_HASCL(m)	((m)->m_flags & M_EXT)
125
126static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast routing tables");
127
128/*
129 * Locking.  We use two locks: one for the virtual interface table and
130 * one for the forwarding table.  These locks may be nested in which case
131 * the VIF lock must always be taken first.  Note that each lock is used
132 * to cover not only the specific data structure but also related data
133 * structures.  It may be better to add more fine-grained locking later;
134 * it's not clear how performance-critical this code is.
135 *
136 * XXX: This module could particularly benefit from being cleaned
137 *      up to use the <sys/queue.h> macros.
138 *
139 */
140
141static struct mrtstat	mrtstat;
142SYSCTL_STRUCT(_net_inet_ip, OID_AUTO, mrtstat, CTLFLAG_RW,
143    &mrtstat, mrtstat,
144    "Multicast Routing Statistics (struct mrtstat, netinet/ip_mroute.h)");
145
146static struct mfc	*mfctable[MFCTBLSIZ];
147SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, mfctable, CTLFLAG_RD,
148    &mfctable, sizeof(mfctable), "S,*mfc[MFCTBLSIZ]",
149    "Multicast Forwarding Table (struct *mfc[MFCTBLSIZ], netinet/ip_mroute.h)");
150
151static struct mtx mrouter_mtx;
152#define	MROUTER_LOCK()		mtx_lock(&mrouter_mtx)
153#define	MROUTER_UNLOCK()	mtx_unlock(&mrouter_mtx)
154#define	MROUTER_LOCK_ASSERT()	mtx_assert(&mrouter_mtx, MA_OWNED)
155#define	MROUTER_LOCK_INIT()	\
156	mtx_init(&mrouter_mtx, "IPv4 multicast forwarding", NULL, MTX_DEF)
157#define	MROUTER_LOCK_DESTROY()	mtx_destroy(&mrouter_mtx)
158
159static struct mtx mfc_mtx;
160#define	MFC_LOCK()	mtx_lock(&mfc_mtx)
161#define	MFC_UNLOCK()	mtx_unlock(&mfc_mtx)
162#define	MFC_LOCK_ASSERT()	mtx_assert(&mfc_mtx, MA_OWNED)
163#define	MFC_LOCK_INIT()	mtx_init(&mfc_mtx, "mroute mfc table", NULL, MTX_DEF)
164#define	MFC_LOCK_DESTROY()	mtx_destroy(&mfc_mtx)
165
166static struct vif	viftable[MAXVIFS];
167SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, viftable, CTLFLAG_RD,
168    &viftable, sizeof(viftable), "S,vif[MAXVIFS]",
169    "Multicast Virtual Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
170
171static struct mtx vif_mtx;
172#define	VIF_LOCK()	mtx_lock(&vif_mtx)
173#define	VIF_UNLOCK()	mtx_unlock(&vif_mtx)
174#define	VIF_LOCK_ASSERT()	mtx_assert(&vif_mtx, MA_OWNED)
175#define	VIF_LOCK_INIT()	mtx_init(&vif_mtx, "mroute vif table", NULL, MTX_DEF)
176#define	VIF_LOCK_DESTROY()	mtx_destroy(&vif_mtx)
177
178static u_char		nexpire[MFCTBLSIZ];
179
180static eventhandler_tag if_detach_event_tag = NULL;
181
182static struct callout expire_upcalls_ch;
183
184#define		EXPIRE_TIMEOUT	(hz / 4)	/* 4x / second		*/
185#define		UPCALL_EXPIRE	6		/* number of timeouts	*/
186
187#define ENCAP_TTL 64
188
189/*
190 * Bandwidth meter variables and constants
191 */
192static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
193/*
194 * Pending timeouts are stored in a hash table, the key being the
195 * expiration time. Periodically, the entries are analysed and processed.
196 */
197#define BW_METER_BUCKETS	1024
198static struct bw_meter *bw_meter_timers[BW_METER_BUCKETS];
199static struct callout bw_meter_ch;
200#define BW_METER_PERIOD (hz)		/* periodical handling of bw meters */
201
202/*
203 * Pending upcalls are stored in a vector which is flushed when
204 * full, or periodically
205 */
206static struct bw_upcall	bw_upcalls[BW_UPCALLS_MAX];
207static u_int	bw_upcalls_n; /* # of pending upcalls */
208static struct callout bw_upcalls_ch;
209#define BW_UPCALLS_PERIOD (hz)		/* periodical flush of bw upcalls */
210
211static struct pimstat pimstat;
212
213SYSCTL_NODE(_net_inet, IPPROTO_PIM, pim, CTLFLAG_RW, 0, "PIM");
214SYSCTL_STRUCT(_net_inet_pim, PIMCTL_STATS, stats, CTLFLAG_RD,
215    &pimstat, pimstat,
216    "PIM Statistics (struct pimstat, netinet/pim_var.h)");
217
218static u_long	pim_squelch_wholepkt = 0;
219SYSCTL_ULONG(_net_inet_pim, OID_AUTO, squelch_wholepkt, CTLFLAG_RW,
220    &pim_squelch_wholepkt, 0,
221    "Disable IGMP_WHOLEPKT notifications if rendezvous point is unspecified");
222
223extern  struct domain inetdomain;
224struct protosw in_pim_protosw = {
225	.pr_type =		SOCK_RAW,
226	.pr_domain =		&inetdomain,
227	.pr_protocol =		IPPROTO_PIM,
228	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_LASTHDR,
229	.pr_input =		pim_input,
230	.pr_output =		(pr_output_t*)rip_output,
231	.pr_ctloutput =		rip_ctloutput,
232	.pr_usrreqs =		&rip_usrreqs
233};
234static const struct encaptab *pim_encap_cookie;
235
236#ifdef INET6
237/* ip6_mroute.c glue */
238extern struct in6_protosw in6_pim_protosw;
239static const struct encaptab *pim6_encap_cookie;
240
241extern int X_ip6_mrouter_set(struct socket *, struct sockopt *);
242extern int X_ip6_mrouter_get(struct socket *, struct sockopt *);
243extern int X_ip6_mrouter_done(void);
244extern int X_ip6_mforward(struct ip6_hdr *, struct ifnet *, struct mbuf *);
245extern int X_mrt6_ioctl(int, caddr_t);
246#endif
247
248static int pim_encapcheck(const struct mbuf *, int, int, void *);
249
250/*
251 * Note: the PIM Register encapsulation adds the following in front of a
252 * data packet:
253 *
254 * struct pim_encap_hdr {
255 *    struct ip ip;
256 *    struct pim_encap_pimhdr  pim;
257 * }
258 *
259 */
260
261struct pim_encap_pimhdr {
262	struct pim pim;
263	uint32_t   flags;
264};
265
266static struct ip pim_encap_iphdr = {
267#if BYTE_ORDER == LITTLE_ENDIAN
268	sizeof(struct ip) >> 2,
269	IPVERSION,
270#else
271	IPVERSION,
272	sizeof(struct ip) >> 2,
273#endif
274	0,			/* tos */
275	sizeof(struct ip),	/* total length */
276	0,			/* id */
277	0,			/* frag offset */
278	ENCAP_TTL,
279	IPPROTO_PIM,
280	0,			/* checksum */
281};
282
283static struct pim_encap_pimhdr pim_encap_pimhdr = {
284    {
285	PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
286	0,			/* reserved */
287	0,			/* checksum */
288    },
289    0				/* flags */
290};
291
292static struct ifnet multicast_register_if;
293static vifi_t reg_vif_num = VIFI_INVALID;
294
295/*
296 * Private variables.
297 */
298static vifi_t	   numvifs;
299
300static u_long	X_ip_mcast_src(int vifi);
301static int	X_ip_mforward(struct ip *ip, struct ifnet *ifp,
302			struct mbuf *m, struct ip_moptions *imo);
303static int	X_ip_mrouter_done(void);
304static int	X_ip_mrouter_get(struct socket *so, struct sockopt *m);
305static int	X_ip_mrouter_set(struct socket *so, struct sockopt *m);
306static int	X_legal_vif_num(int vif);
307static int	X_mrt_ioctl(int cmd, caddr_t data, int fibnum);
308
309static int get_sg_cnt(struct sioc_sg_req *);
310static int get_vif_cnt(struct sioc_vif_req *);
311static void if_detached_event(void *arg __unused, struct ifnet *);
312static int ip_mrouter_init(struct socket *, int);
313static int add_vif(struct vifctl *);
314static int del_vif_locked(vifi_t);
315static int del_vif(vifi_t);
316static int add_mfc(struct mfcctl2 *);
317static int del_mfc(struct mfcctl2 *);
318static int set_api_config(uint32_t *); /* chose API capabilities */
319static int socket_send(struct socket *, struct mbuf *, struct sockaddr_in *);
320static int set_assert(int);
321static void expire_upcalls(void *);
322static int ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
323static void phyint_send(struct ip *, struct vif *, struct mbuf *);
324static void send_packet(struct vif *, struct mbuf *);
325
326/*
327 * Bandwidth monitoring
328 */
329static void free_bw_list(struct bw_meter *list);
330static int add_bw_upcall(struct bw_upcall *);
331static int del_bw_upcall(struct bw_upcall *);
332static void bw_meter_receive_packet(struct bw_meter *x, int plen,
333		struct timeval *nowp);
334static void bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp);
335static void bw_upcalls_send(void);
336static void schedule_bw_meter(struct bw_meter *x, struct timeval *nowp);
337static void unschedule_bw_meter(struct bw_meter *x);
338static void bw_meter_process(void);
339static void expire_bw_upcalls_send(void *);
340static void expire_bw_meter_process(void *);
341
342static int pim_register_send(struct ip *, struct vif *,
343		struct mbuf *, struct mfc *);
344static int pim_register_send_rp(struct ip *, struct vif *,
345		struct mbuf *, struct mfc *);
346static int pim_register_send_upcall(struct ip *, struct vif *,
347		struct mbuf *, struct mfc *);
348static struct mbuf *pim_register_prepare(struct ip *, struct mbuf *);
349
350/*
351 * whether or not special PIM assert processing is enabled.
352 */
353static int pim_assert;
354/*
355 * Rate limit for assert notification messages, in usec
356 */
357#define ASSERT_MSG_TIME		3000000
358
359/*
360 * Kernel multicast routing API capabilities and setup.
361 * If more API capabilities are added to the kernel, they should be
362 * recorded in `mrt_api_support'.
363 */
364static const uint32_t mrt_api_support = (MRT_MFC_FLAGS_DISABLE_WRONGVIF |
365					 MRT_MFC_FLAGS_BORDER_VIF |
366					 MRT_MFC_RP |
367					 MRT_MFC_BW_UPCALL);
368static uint32_t mrt_api_config = 0;
369
370/*
371 * Hash function for a source, group entry
372 */
373#define MFCHASH(a, g) MFCHASHMOD(((a) >> 20) ^ ((a) >> 10) ^ (a) ^ \
374			((g) >> 20) ^ ((g) >> 10) ^ (g))
375
376/*
377 * Find a route for a given origin IP address and Multicast group address
378 * Statistics are updated by the caller if needed
379 * (mrtstat.mrts_mfc_lookups and mrtstat.mrts_mfc_misses)
380 */
381static struct mfc *
382mfc_find(in_addr_t o, in_addr_t g)
383{
384    struct mfc *rt;
385
386    MFC_LOCK_ASSERT();
387
388    for (rt = mfctable[MFCHASH(o,g)]; rt; rt = rt->mfc_next)
389	if ((rt->mfc_origin.s_addr == o) &&
390		(rt->mfc_mcastgrp.s_addr == g) && (rt->mfc_stall == NULL))
391	    break;
392    return rt;
393}
394
395/*
396 * Macros to compute elapsed time efficiently
397 * Borrowed from Van Jacobson's scheduling code
398 */
399#define TV_DELTA(a, b, delta) {					\
400	int xxs;						\
401	delta = (a).tv_usec - (b).tv_usec;			\
402	if ((xxs = (a).tv_sec - (b).tv_sec)) {			\
403		switch (xxs) {					\
404		case 2:						\
405		      delta += 1000000;				\
406		      /* FALLTHROUGH */				\
407		case 1:						\
408		      delta += 1000000;				\
409		      break;					\
410		default:					\
411		      delta += (1000000 * xxs);			\
412		}						\
413	}							\
414}
415
416#define TV_LT(a, b) (((a).tv_usec < (b).tv_usec && \
417	      (a).tv_sec <= (b).tv_sec) || (a).tv_sec < (b).tv_sec)
418
419/*
420 * Handle MRT setsockopt commands to modify the multicast routing tables.
421 */
422static int
423X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
424{
425    INIT_VNET_INET(curvnet);
426    int	error, optval;
427    vifi_t	vifi;
428    struct	vifctl vifc;
429    struct	mfcctl2 mfc;
430    struct	bw_upcall bw_upcall;
431    uint32_t	i;
432
433    if (so != V_ip_mrouter && sopt->sopt_name != MRT_INIT)
434	return EPERM;
435
436    error = 0;
437    switch (sopt->sopt_name) {
438    case MRT_INIT:
439	error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
440	if (error)
441	    break;
442	error = ip_mrouter_init(so, optval);
443	break;
444
445    case MRT_DONE:
446	error = ip_mrouter_done();
447	break;
448
449    case MRT_ADD_VIF:
450	error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
451	if (error)
452	    break;
453	error = add_vif(&vifc);
454	break;
455
456    case MRT_DEL_VIF:
457	error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
458	if (error)
459	    break;
460	error = del_vif(vifi);
461	break;
462
463    case MRT_ADD_MFC:
464    case MRT_DEL_MFC:
465	/*
466	 * select data size depending on API version.
467	 */
468	if (sopt->sopt_name == MRT_ADD_MFC &&
469		mrt_api_config & MRT_API_FLAGS_ALL) {
470	    error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl2),
471				sizeof(struct mfcctl2));
472	} else {
473	    error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl),
474				sizeof(struct mfcctl));
475	    bzero((caddr_t)&mfc + sizeof(struct mfcctl),
476			sizeof(mfc) - sizeof(struct mfcctl));
477	}
478	if (error)
479	    break;
480	if (sopt->sopt_name == MRT_ADD_MFC)
481	    error = add_mfc(&mfc);
482	else
483	    error = del_mfc(&mfc);
484	break;
485
486    case MRT_ASSERT:
487	error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
488	if (error)
489	    break;
490	set_assert(optval);
491	break;
492
493    case MRT_API_CONFIG:
494	error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
495	if (!error)
496	    error = set_api_config(&i);
497	if (!error)
498	    error = sooptcopyout(sopt, &i, sizeof i);
499	break;
500
501    case MRT_ADD_BW_UPCALL:
502    case MRT_DEL_BW_UPCALL:
503	error = sooptcopyin(sopt, &bw_upcall, sizeof bw_upcall,
504				sizeof bw_upcall);
505	if (error)
506	    break;
507	if (sopt->sopt_name == MRT_ADD_BW_UPCALL)
508	    error = add_bw_upcall(&bw_upcall);
509	else
510	    error = del_bw_upcall(&bw_upcall);
511	break;
512
513    default:
514	error = EOPNOTSUPP;
515	break;
516    }
517    return error;
518}
519
520/*
521 * Handle MRT getsockopt commands
522 */
523static int
524X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
525{
526    int error;
527    static int version = 0x0305; /* !!! why is this here? XXX */
528
529    switch (sopt->sopt_name) {
530    case MRT_VERSION:
531	error = sooptcopyout(sopt, &version, sizeof version);
532	break;
533
534    case MRT_ASSERT:
535	error = sooptcopyout(sopt, &pim_assert, sizeof pim_assert);
536	break;
537
538    case MRT_API_SUPPORT:
539	error = sooptcopyout(sopt, &mrt_api_support, sizeof mrt_api_support);
540	break;
541
542    case MRT_API_CONFIG:
543	error = sooptcopyout(sopt, &mrt_api_config, sizeof mrt_api_config);
544	break;
545
546    default:
547	error = EOPNOTSUPP;
548	break;
549    }
550    return error;
551}
552
553/*
554 * Handle ioctl commands to obtain information from the cache
555 */
556static int
557X_mrt_ioctl(int cmd, caddr_t data, int fibnum)
558{
559    int error = 0;
560
561    /*
562     * Currently the only function calling this ioctl routine is rtioctl().
563     * Typically, only root can create the raw socket in order to execute
564     * this ioctl method, however the request might be coming from a prison
565     */
566    error = priv_check(curthread, PRIV_NETINET_MROUTE);
567    if (error)
568	return (error);
569    switch (cmd) {
570    case (SIOCGETVIFCNT):
571	error = get_vif_cnt((struct sioc_vif_req *)data);
572	break;
573
574    case (SIOCGETSGCNT):
575	error = get_sg_cnt((struct sioc_sg_req *)data);
576	break;
577
578    default:
579	error = EINVAL;
580	break;
581    }
582    return error;
583}
584
585/*
586 * returns the packet, byte, rpf-failure count for the source group provided
587 */
588static int
589get_sg_cnt(struct sioc_sg_req *req)
590{
591    struct mfc *rt;
592
593    MFC_LOCK();
594    rt = mfc_find(req->src.s_addr, req->grp.s_addr);
595    if (rt == NULL) {
596	MFC_UNLOCK();
597	req->pktcnt = req->bytecnt = req->wrong_if = 0xffffffff;
598	return EADDRNOTAVAIL;
599    }
600    req->pktcnt = rt->mfc_pkt_cnt;
601    req->bytecnt = rt->mfc_byte_cnt;
602    req->wrong_if = rt->mfc_wrong_if;
603    MFC_UNLOCK();
604    return 0;
605}
606
607/*
608 * returns the input and output packet and byte counts on the vif provided
609 */
610static int
611get_vif_cnt(struct sioc_vif_req *req)
612{
613    vifi_t vifi = req->vifi;
614
615    VIF_LOCK();
616    if (vifi >= numvifs) {
617	VIF_UNLOCK();
618	return EINVAL;
619    }
620
621    req->icount = viftable[vifi].v_pkt_in;
622    req->ocount = viftable[vifi].v_pkt_out;
623    req->ibytes = viftable[vifi].v_bytes_in;
624    req->obytes = viftable[vifi].v_bytes_out;
625    VIF_UNLOCK();
626
627    return 0;
628}
629
630static void
631ip_mrouter_reset(void)
632{
633    bzero((caddr_t)mfctable, sizeof(mfctable));
634    bzero((caddr_t)nexpire, sizeof(nexpire));
635
636    pim_assert = 0;
637    mrt_api_config = 0;
638
639    callout_init(&expire_upcalls_ch, CALLOUT_MPSAFE);
640
641    bw_upcalls_n = 0;
642    bzero((caddr_t)bw_meter_timers, sizeof(bw_meter_timers));
643    callout_init(&bw_upcalls_ch, CALLOUT_MPSAFE);
644    callout_init(&bw_meter_ch, CALLOUT_MPSAFE);
645}
646
647static void
648if_detached_event(void *arg __unused, struct ifnet *ifp)
649{
650    INIT_VNET_INET(curvnet);
651    vifi_t vifi;
652    int i;
653    struct mfc *mfc;
654    struct mfc *nmfc;
655    struct mfc **ppmfc;	/* Pointer to previous node's next-pointer */
656    struct rtdetq *pq;
657    struct rtdetq *npq;
658
659    MROUTER_LOCK();
660    if (V_ip_mrouter == NULL) {
661	MROUTER_UNLOCK();
662    }
663
664    /*
665     * Tear down multicast forwarder state associated with this ifnet.
666     * 1. Walk the vif list, matching vifs against this ifnet.
667     * 2. Walk the multicast forwarding cache (mfc) looking for
668     *    inner matches with this vif's index.
669     * 3. Free any pending mbufs for this mfc.
670     * 4. Free the associated mfc entry and state associated with this vif.
671     *    Be very careful about unlinking from a singly-linked list whose
672     *    "head node" is a pointer in a simple array.
673     * 5. Free vif state. This should disable ALLMULTI on the interface.
674     */
675    VIF_LOCK();
676    MFC_LOCK();
677    for (vifi = 0; vifi < numvifs; vifi++) {
678	if (viftable[vifi].v_ifp != ifp)
679		continue;
680	for (i = 0; i < MFCTBLSIZ; i++) {
681	    ppmfc = &mfctable[i];
682	    for (mfc = mfctable[i]; mfc != NULL; ) {
683		nmfc = mfc->mfc_next;
684		if (mfc->mfc_parent == vifi) {
685		    for (pq = mfc->mfc_stall; pq != NULL; ) {
686			npq = pq->next;
687			m_freem(pq->m);
688			free(pq, M_MRTABLE);
689			pq = npq;
690		    }
691		    free_bw_list(mfc->mfc_bw_meter);
692		    free(mfc, M_MRTABLE);
693		    *ppmfc = nmfc;
694		} else {
695		    ppmfc = &mfc->mfc_next;
696		}
697		mfc = nmfc;
698	    }
699	}
700	del_vif_locked(vifi);
701    }
702    MFC_UNLOCK();
703    VIF_UNLOCK();
704
705    MROUTER_UNLOCK();
706}
707
708/*
709 * Enable multicast routing
710 */
711static int
712ip_mrouter_init(struct socket *so, int version)
713{
714    INIT_VNET_INET(curvnet);
715
716    if (mrtdebug)
717	log(LOG_DEBUG, "ip_mrouter_init: so_type = %d, pr_protocol = %d\n",
718	    so->so_type, so->so_proto->pr_protocol);
719
720    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_IGMP)
721	return EOPNOTSUPP;
722
723    if (version != 1)
724	return ENOPROTOOPT;
725
726    MROUTER_LOCK();
727
728    if (V_ip_mrouter != NULL) {
729	MROUTER_UNLOCK();
730	return EADDRINUSE;
731    }
732
733    if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
734        if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
735    if (if_detach_event_tag == NULL) {
736	MROUTER_UNLOCK();
737	return (ENOMEM);
738    }
739
740    callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
741
742    callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
743	expire_bw_upcalls_send, NULL);
744    callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
745
746    V_ip_mrouter = so;
747
748    MROUTER_UNLOCK();
749
750    if (mrtdebug)
751	log(LOG_DEBUG, "ip_mrouter_init\n");
752
753    return 0;
754}
755
756/*
757 * Disable multicast routing
758 */
759static int
760X_ip_mrouter_done(void)
761{
762    INIT_VNET_INET(curvnet);
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 (V_ip_mrouter == NULL) {
773	MROUTER_UNLOCK();
774	return EINVAL;
775    }
776
777    /*
778     * Detach/disable hooks to the reset of the system.
779     */
780    V_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    INIT_VNET_INET(curvnet);
1295    struct mfc *rt;
1296    int error;
1297    vifi_t vifi;
1298
1299    if (mrtdebug & DEBUG_FORWARD)
1300	log(LOG_DEBUG, "ip_mforward: src %lx, dst %lx, ifp %p\n",
1301	    (u_long)ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr),
1302	    (void *)ifp);
1303
1304    if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1305		((u_char *)(ip + 1))[1] != IPOPT_LSRR ) {
1306	/*
1307	 * Packet arrived via a physical interface or
1308	 * an encapsulated tunnel or a register_vif.
1309	 */
1310    } else {
1311	/*
1312	 * Packet arrived through a source-route tunnel.
1313	 * Source-route tunnels are no longer supported.
1314	 */
1315	static int last_log;
1316	if (last_log != time_uptime) {
1317	    last_log = time_uptime;
1318	    log(LOG_ERR,
1319		"ip_mforward: received source-routed packet from %lx\n",
1320		(u_long)ntohl(ip->ip_src.s_addr));
1321	}
1322	return 1;
1323    }
1324
1325    VIF_LOCK();
1326    MFC_LOCK();
1327    if (imo && ((vifi = imo->imo_multicast_vif) < numvifs)) {
1328	if (ip->ip_ttl < MAXTTL)
1329	    ip->ip_ttl++;	/* compensate for -1 in *_send routines */
1330	if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1331	    struct vif *vifp = viftable + vifi;
1332
1333	    printf("Sending IPPROTO_RSVP from %lx to %lx on vif %d (%s%s)\n",
1334		(long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr),
1335		vifi,
1336		(vifp->v_flags & VIFF_TUNNEL) ? "tunnel on " : "",
1337		vifp->v_ifp->if_xname);
1338	}
1339	error = ip_mdq(m, ifp, NULL, vifi);
1340	MFC_UNLOCK();
1341	VIF_UNLOCK();
1342	return error;
1343    }
1344    if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1345	printf("Warning: IPPROTO_RSVP from %lx to %lx without vif option\n",
1346	    (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr));
1347	if (!imo)
1348	    printf("In fact, no options were specified at all\n");
1349    }
1350
1351    /*
1352     * Don't forward a packet with time-to-live of zero or one,
1353     * or a packet destined to a local-only group.
1354     */
1355    if (ip->ip_ttl <= 1 || IN_LOCAL_GROUP(ntohl(ip->ip_dst.s_addr))) {
1356	MFC_UNLOCK();
1357	VIF_UNLOCK();
1358	return 0;
1359    }
1360
1361    /*
1362     * Determine forwarding vifs from the forwarding cache table
1363     */
1364    ++mrtstat.mrts_mfc_lookups;
1365    rt = mfc_find(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1366
1367    /* Entry exists, so forward if necessary */
1368    if (rt != NULL) {
1369	error = ip_mdq(m, ifp, rt, -1);
1370	MFC_UNLOCK();
1371	VIF_UNLOCK();
1372	return error;
1373    } else {
1374	/*
1375	 * If we don't have a route for packet's origin,
1376	 * Make a copy of the packet & send message to routing daemon
1377	 */
1378
1379	struct mbuf *mb0;
1380	struct rtdetq *rte;
1381	u_long hash;
1382	int hlen = ip->ip_hl << 2;
1383
1384	++mrtstat.mrts_mfc_misses;
1385
1386	mrtstat.mrts_no_route++;
1387	if (mrtdebug & (DEBUG_FORWARD | DEBUG_MFC))
1388	    log(LOG_DEBUG, "ip_mforward: no rte s %lx g %lx\n",
1389		(u_long)ntohl(ip->ip_src.s_addr),
1390		(u_long)ntohl(ip->ip_dst.s_addr));
1391
1392	/*
1393	 * Allocate mbufs early so that we don't do extra work if we are
1394	 * just going to fail anyway.  Make sure to pullup the header so
1395	 * that other people can't step on it.
1396	 */
1397	rte = (struct rtdetq *)malloc((sizeof *rte), M_MRTABLE, M_NOWAIT);
1398	if (rte == NULL) {
1399	    MFC_UNLOCK();
1400	    VIF_UNLOCK();
1401	    return ENOBUFS;
1402	}
1403	mb0 = m_copypacket(m, M_DONTWAIT);
1404	if (mb0 && (M_HASCL(mb0) || mb0->m_len < hlen))
1405	    mb0 = m_pullup(mb0, hlen);
1406	if (mb0 == NULL) {
1407	    free(rte, M_MRTABLE);
1408	    MFC_UNLOCK();
1409	    VIF_UNLOCK();
1410	    return ENOBUFS;
1411	}
1412
1413	/* is there an upcall waiting for this flow ? */
1414	hash = MFCHASH(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1415	for (rt = mfctable[hash]; rt; rt = rt->mfc_next) {
1416	    if ((ip->ip_src.s_addr == rt->mfc_origin.s_addr) &&
1417		    (ip->ip_dst.s_addr == rt->mfc_mcastgrp.s_addr) &&
1418		    (rt->mfc_stall != NULL))
1419		break;
1420	}
1421
1422	if (rt == NULL) {
1423	    int i;
1424	    struct igmpmsg *im;
1425	    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1426	    struct mbuf *mm;
1427
1428	    /*
1429	     * Locate the vifi for the incoming interface for this packet.
1430	     * If none found, drop packet.
1431	     */
1432	    for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1433		;
1434	    if (vifi >= numvifs)	/* vif not found, drop packet */
1435		goto non_fatal;
1436
1437	    /* no upcall, so make a new entry */
1438	    rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1439	    if (rt == NULL)
1440		goto fail;
1441	    /* Make a copy of the header to send to the user level process */
1442	    mm = m_copy(mb0, 0, hlen);
1443	    if (mm == NULL)
1444		goto fail1;
1445
1446	    /*
1447	     * Send message to routing daemon to install
1448	     * a route into the kernel table
1449	     */
1450
1451	    im = mtod(mm, struct igmpmsg *);
1452	    im->im_msgtype = IGMPMSG_NOCACHE;
1453	    im->im_mbz = 0;
1454	    im->im_vif = vifi;
1455
1456	    mrtstat.mrts_upcalls++;
1457
1458	    k_igmpsrc.sin_addr = ip->ip_src;
1459	    if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1460		log(LOG_WARNING, "ip_mforward: ip_mrouter socket queue full\n");
1461		++mrtstat.mrts_upq_sockfull;
1462fail1:
1463		free(rt, M_MRTABLE);
1464fail:
1465		free(rte, M_MRTABLE);
1466		m_freem(mb0);
1467		MFC_UNLOCK();
1468		VIF_UNLOCK();
1469		return ENOBUFS;
1470	    }
1471
1472	    /* insert new entry at head of hash chain */
1473	    rt->mfc_origin.s_addr     = ip->ip_src.s_addr;
1474	    rt->mfc_mcastgrp.s_addr   = ip->ip_dst.s_addr;
1475	    rt->mfc_expire	      = UPCALL_EXPIRE;
1476	    nexpire[hash]++;
1477	    for (i = 0; i < numvifs; i++) {
1478		rt->mfc_ttls[i] = 0;
1479		rt->mfc_flags[i] = 0;
1480	    }
1481	    rt->mfc_parent = -1;
1482
1483	    rt->mfc_rp.s_addr = INADDR_ANY; /* clear the RP address */
1484
1485	    rt->mfc_bw_meter = NULL;
1486
1487	    /* link into table */
1488	    rt->mfc_next   = mfctable[hash];
1489	    mfctable[hash] = rt;
1490	    rt->mfc_stall = rte;
1491
1492	} else {
1493	    /* determine if q has overflowed */
1494	    int npkts = 0;
1495	    struct rtdetq **p;
1496
1497	    /*
1498	     * XXX ouch! we need to append to the list, but we
1499	     * only have a pointer to the front, so we have to
1500	     * scan the entire list every time.
1501	     */
1502	    for (p = &rt->mfc_stall; *p != NULL; p = &(*p)->next)
1503		npkts++;
1504
1505	    if (npkts > MAX_UPQ) {
1506		mrtstat.mrts_upq_ovflw++;
1507non_fatal:
1508		free(rte, M_MRTABLE);
1509		m_freem(mb0);
1510		MFC_UNLOCK();
1511		VIF_UNLOCK();
1512		return 0;
1513	    }
1514
1515	    /* Add this entry to the end of the queue */
1516	    *p = rte;
1517	}
1518
1519	rte->m			= mb0;
1520	rte->ifp		= ifp;
1521	rte->next		= NULL;
1522
1523	MFC_UNLOCK();
1524	VIF_UNLOCK();
1525
1526	return 0;
1527    }
1528}
1529
1530/*
1531 * Clean up the cache entry if upcall is not serviced
1532 */
1533static void
1534expire_upcalls(void *unused)
1535{
1536    struct rtdetq *rte;
1537    struct mfc *mfc, **nptr;
1538    int i;
1539
1540    MFC_LOCK();
1541    for (i = 0; i < MFCTBLSIZ; i++) {
1542	if (nexpire[i] == 0)
1543	    continue;
1544	nptr = &mfctable[i];
1545	for (mfc = *nptr; mfc != NULL; mfc = *nptr) {
1546	    /*
1547	     * Skip real cache entries
1548	     * Make sure it wasn't marked to not expire (shouldn't happen)
1549	     * If it expires now
1550	     */
1551	    if (mfc->mfc_stall != NULL && mfc->mfc_expire != 0 &&
1552		    --mfc->mfc_expire == 0) {
1553		if (mrtdebug & DEBUG_EXPIRE)
1554		    log(LOG_DEBUG, "expire_upcalls: expiring (%lx %lx)\n",
1555			(u_long)ntohl(mfc->mfc_origin.s_addr),
1556			(u_long)ntohl(mfc->mfc_mcastgrp.s_addr));
1557		/*
1558		 * drop all the packets
1559		 * free the mbuf with the pkt, if, timing info
1560		 */
1561		for (rte = mfc->mfc_stall; rte; ) {
1562		    struct rtdetq *n = rte->next;
1563
1564		    m_freem(rte->m);
1565		    free(rte, M_MRTABLE);
1566		    rte = n;
1567		}
1568		++mrtstat.mrts_cache_cleanups;
1569		nexpire[i]--;
1570
1571		/*
1572		 * free the bw_meter entries
1573		 */
1574		while (mfc->mfc_bw_meter != NULL) {
1575		    struct bw_meter *x = mfc->mfc_bw_meter;
1576
1577		    mfc->mfc_bw_meter = x->bm_mfc_next;
1578		    free(x, M_BWMETER);
1579		}
1580
1581		*nptr = mfc->mfc_next;
1582		free(mfc, M_MRTABLE);
1583	    } else {
1584		nptr = &mfc->mfc_next;
1585	    }
1586	}
1587    }
1588    MFC_UNLOCK();
1589
1590    callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
1591}
1592
1593/*
1594 * Packet forwarding routine once entry in the cache is made
1595 */
1596static int
1597ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1598{
1599    INIT_VNET_INET(curvnet);
1600    struct ip  *ip = mtod(m, struct ip *);
1601    vifi_t vifi;
1602    int plen = ip->ip_len;
1603
1604    VIF_LOCK_ASSERT();
1605
1606    /*
1607     * If xmt_vif is not -1, send on only the requested vif.
1608     *
1609     * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1610     */
1611    if (xmt_vif < numvifs) {
1612	if (viftable[xmt_vif].v_flags & VIFF_REGISTER)
1613		pim_register_send(ip, viftable + xmt_vif, m, rt);
1614	else
1615		phyint_send(ip, viftable + xmt_vif, m);
1616	return 1;
1617    }
1618
1619    /*
1620     * Don't forward if it didn't arrive from the parent vif for its origin.
1621     */
1622    vifi = rt->mfc_parent;
1623    if ((vifi >= numvifs) || (viftable[vifi].v_ifp != ifp)) {
1624	/* came in the wrong interface */
1625	if (mrtdebug & DEBUG_FORWARD)
1626	    log(LOG_DEBUG, "wrong if: ifp %p vifi %d vififp %p\n",
1627		(void *)ifp, vifi, (void *)viftable[vifi].v_ifp);
1628	++mrtstat.mrts_wrong_if;
1629	++rt->mfc_wrong_if;
1630	/*
1631	 * If we are doing PIM assert processing, send a message
1632	 * to the routing daemon.
1633	 *
1634	 * XXX: A PIM-SM router needs the WRONGVIF detection so it
1635	 * can complete the SPT switch, regardless of the type
1636	 * of the iif (broadcast media, GRE tunnel, etc).
1637	 */
1638	if (pim_assert && (vifi < numvifs) && viftable[vifi].v_ifp) {
1639	    struct timeval now;
1640	    u_long delta;
1641
1642	    if (ifp == &multicast_register_if)
1643		pimstat.pims_rcv_registers_wrongiif++;
1644
1645	    /* Get vifi for the incoming packet */
1646	    for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1647		;
1648	    if (vifi >= numvifs)
1649		return 0;	/* The iif is not found: ignore the packet. */
1650
1651	    if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1652		return 0;	/* WRONGVIF disabled: ignore the packet */
1653
1654	    GET_TIME(now);
1655
1656	    TV_DELTA(now, rt->mfc_last_assert, delta);
1657
1658	    if (delta > ASSERT_MSG_TIME) {
1659		struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1660		struct igmpmsg *im;
1661		int hlen = ip->ip_hl << 2;
1662		struct mbuf *mm = m_copy(m, 0, hlen);
1663
1664		if (mm && (M_HASCL(mm) || mm->m_len < hlen))
1665		    mm = m_pullup(mm, hlen);
1666		if (mm == NULL)
1667		    return ENOBUFS;
1668
1669		rt->mfc_last_assert = now;
1670
1671		im = mtod(mm, struct igmpmsg *);
1672		im->im_msgtype	= IGMPMSG_WRONGVIF;
1673		im->im_mbz		= 0;
1674		im->im_vif		= vifi;
1675
1676		mrtstat.mrts_upcalls++;
1677
1678		k_igmpsrc.sin_addr = im->im_src;
1679		if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1680		    log(LOG_WARNING,
1681			"ip_mforward: ip_mrouter socket queue full\n");
1682		    ++mrtstat.mrts_upq_sockfull;
1683		    return ENOBUFS;
1684		}
1685	    }
1686	}
1687	return 0;
1688    }
1689
1690    /* If I sourced this packet, it counts as output, else it was input. */
1691    if (ip->ip_src.s_addr == viftable[vifi].v_lcl_addr.s_addr) {
1692	viftable[vifi].v_pkt_out++;
1693	viftable[vifi].v_bytes_out += plen;
1694    } else {
1695	viftable[vifi].v_pkt_in++;
1696	viftable[vifi].v_bytes_in += plen;
1697    }
1698    rt->mfc_pkt_cnt++;
1699    rt->mfc_byte_cnt += plen;
1700
1701    /*
1702     * For each vif, decide if a copy of the packet should be forwarded.
1703     * Forward if:
1704     *		- the ttl exceeds the vif's threshold
1705     *		- there are group members downstream on interface
1706     */
1707    for (vifi = 0; vifi < numvifs; vifi++)
1708	if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1709	    viftable[vifi].v_pkt_out++;
1710	    viftable[vifi].v_bytes_out += plen;
1711	    if (viftable[vifi].v_flags & VIFF_REGISTER)
1712		pim_register_send(ip, viftable + vifi, m, rt);
1713	    else
1714		phyint_send(ip, viftable + vifi, m);
1715	}
1716
1717    /*
1718     * Perform upcall-related bw measuring.
1719     */
1720    if (rt->mfc_bw_meter != NULL) {
1721	struct bw_meter *x;
1722	struct timeval now;
1723
1724	GET_TIME(now);
1725	MFC_LOCK_ASSERT();
1726	for (x = rt->mfc_bw_meter; x != NULL; x = x->bm_mfc_next)
1727	    bw_meter_receive_packet(x, plen, &now);
1728    }
1729
1730    return 0;
1731}
1732
1733/*
1734 * check if a vif number is legal/ok. This is used by ip_output.
1735 */
1736static int
1737X_legal_vif_num(int vif)
1738{
1739    /* XXX unlocked, matter? */
1740    return (vif >= 0 && vif < numvifs);
1741}
1742
1743/*
1744 * Return the local address used by this vif
1745 */
1746static u_long
1747X_ip_mcast_src(int vifi)
1748{
1749    /* XXX unlocked, matter? */
1750    if (vifi >= 0 && vifi < numvifs)
1751	return viftable[vifi].v_lcl_addr.s_addr;
1752    else
1753	return INADDR_ANY;
1754}
1755
1756static void
1757phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1758{
1759    struct mbuf *mb_copy;
1760    int hlen = ip->ip_hl << 2;
1761
1762    VIF_LOCK_ASSERT();
1763
1764    /*
1765     * Make a new reference to the packet; make sure that
1766     * the IP header is actually copied, not just referenced,
1767     * so that ip_output() only scribbles on the copy.
1768     */
1769    mb_copy = m_copypacket(m, M_DONTWAIT);
1770    if (mb_copy && (M_HASCL(mb_copy) || mb_copy->m_len < hlen))
1771	mb_copy = m_pullup(mb_copy, hlen);
1772    if (mb_copy == NULL)
1773	return;
1774
1775    send_packet(vifp, mb_copy);
1776}
1777
1778static void
1779send_packet(struct vif *vifp, struct mbuf *m)
1780{
1781	struct ip_moptions imo;
1782	struct in_multi *imm[2];
1783	int error;
1784
1785	VIF_LOCK_ASSERT();
1786
1787	imo.imo_multicast_ifp  = vifp->v_ifp;
1788	imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1789	imo.imo_multicast_loop = 1;
1790	imo.imo_multicast_vif  = -1;
1791	imo.imo_num_memberships = 0;
1792	imo.imo_max_memberships = 2;
1793	imo.imo_membership  = &imm[0];
1794
1795	/*
1796	 * Re-entrancy should not be a problem here, because
1797	 * the packets that we send out and are looped back at us
1798	 * should get rejected because they appear to come from
1799	 * the loopback interface, thus preventing looping.
1800	 */
1801	error = ip_output(m, NULL, &vifp->v_route, IP_FORWARDING, &imo, NULL);
1802	if (mrtdebug & DEBUG_XMIT) {
1803	    log(LOG_DEBUG, "phyint_send on vif %td err %d\n",
1804		vifp - viftable, error);
1805	}
1806}
1807
1808static int
1809X_ip_rsvp_vif(struct socket *so, struct sockopt *sopt)
1810{
1811    INIT_VNET_INET(curvnet);
1812    int error, vifi;
1813
1814    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
1815	return EOPNOTSUPP;
1816
1817    error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
1818    if (error)
1819	return error;
1820
1821    VIF_LOCK();
1822
1823    if (vifi < 0 || vifi >= numvifs) {	/* Error if vif is invalid */
1824	VIF_UNLOCK();
1825	return EADDRNOTAVAIL;
1826    }
1827
1828    if (sopt->sopt_name == IP_RSVP_VIF_ON) {
1829	/* Check if socket is available. */
1830	if (viftable[vifi].v_rsvpd != NULL) {
1831	    VIF_UNLOCK();
1832	    return EADDRINUSE;
1833	}
1834
1835	viftable[vifi].v_rsvpd = so;
1836	/* This may seem silly, but we need to be sure we don't over-increment
1837	 * the RSVP counter, in case something slips up.
1838	 */
1839	if (!viftable[vifi].v_rsvp_on) {
1840	    viftable[vifi].v_rsvp_on = 1;
1841	    V_rsvp_on++;
1842	}
1843    } else { /* must be VIF_OFF */
1844	/*
1845	 * XXX as an additional consistency check, one could make sure
1846	 * that viftable[vifi].v_rsvpd == so, otherwise passing so as
1847	 * first parameter is pretty useless.
1848	 */
1849	viftable[vifi].v_rsvpd = NULL;
1850	/*
1851	 * This may seem silly, but we need to be sure we don't over-decrement
1852	 * the RSVP counter, in case something slips up.
1853	 */
1854	if (viftable[vifi].v_rsvp_on) {
1855	    viftable[vifi].v_rsvp_on = 0;
1856	    V_rsvp_on--;
1857	}
1858    }
1859    VIF_UNLOCK();
1860    return 0;
1861}
1862
1863static void
1864X_ip_rsvp_force_done(struct socket *so)
1865{
1866    INIT_VNET_INET(curvnet);
1867    int vifi;
1868
1869    /* Don't bother if it is not the right type of socket. */
1870    if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
1871	return;
1872
1873    VIF_LOCK();
1874
1875    /* The socket may be attached to more than one vif...this
1876     * is perfectly legal.
1877     */
1878    for (vifi = 0; vifi < numvifs; vifi++) {
1879	if (viftable[vifi].v_rsvpd == so) {
1880	    viftable[vifi].v_rsvpd = NULL;
1881	    /* This may seem silly, but we need to be sure we don't
1882	     * over-decrement the RSVP counter, in case something slips up.
1883	     */
1884	    if (viftable[vifi].v_rsvp_on) {
1885		viftable[vifi].v_rsvp_on = 0;
1886		V_rsvp_on--;
1887	    }
1888	}
1889    }
1890
1891    VIF_UNLOCK();
1892}
1893
1894static void
1895X_rsvp_input(struct mbuf *m, int off)
1896{
1897    INIT_VNET_INET(curvnet);
1898    int vifi;
1899    struct ip *ip = mtod(m, struct ip *);
1900    struct sockaddr_in rsvp_src = { sizeof rsvp_src, AF_INET };
1901    struct ifnet *ifp;
1902
1903    if (rsvpdebug)
1904	printf("rsvp_input: rsvp_on %d\n", V_rsvp_on);
1905
1906    /* Can still get packets with rsvp_on = 0 if there is a local member
1907     * of the group to which the RSVP packet is addressed.  But in this
1908     * case we want to throw the packet away.
1909     */
1910    if (!V_rsvp_on) {
1911	m_freem(m);
1912	return;
1913    }
1914
1915    if (rsvpdebug)
1916	printf("rsvp_input: check vifs\n");
1917
1918#ifdef DIAGNOSTIC
1919    M_ASSERTPKTHDR(m);
1920#endif
1921
1922    ifp = m->m_pkthdr.rcvif;
1923
1924    VIF_LOCK();
1925    /* Find which vif the packet arrived on. */
1926    for (vifi = 0; vifi < numvifs; vifi++)
1927	if (viftable[vifi].v_ifp == ifp)
1928	    break;
1929
1930    if (vifi == numvifs || viftable[vifi].v_rsvpd == NULL) {
1931	/*
1932	 * Drop the lock here to avoid holding it across rip_input.
1933	 * This could make rsvpdebug printfs wrong.  If you care,
1934	 * record the state of stuff before dropping the lock.
1935	 */
1936	VIF_UNLOCK();
1937	/*
1938	 * If the old-style non-vif-associated socket is set,
1939	 * then use it.  Otherwise, drop packet since there
1940	 * is no specific socket for this vif.
1941	 */
1942	if (V_ip_rsvpd != NULL) {
1943	    if (rsvpdebug)
1944		printf("rsvp_input: Sending packet up old-style socket\n");
1945	    rip_input(m, off);  /* xxx */
1946	} else {
1947	    if (rsvpdebug && vifi == numvifs)
1948		printf("rsvp_input: Can't find vif for packet.\n");
1949	    else if (rsvpdebug && viftable[vifi].v_rsvpd == NULL)
1950		printf("rsvp_input: No socket defined for vif %d\n",vifi);
1951	    m_freem(m);
1952	}
1953	return;
1954    }
1955    rsvp_src.sin_addr = ip->ip_src;
1956
1957    if (rsvpdebug && m)
1958	printf("rsvp_input: m->m_len = %d, sbspace() = %ld\n",
1959	       m->m_len,sbspace(&(viftable[vifi].v_rsvpd->so_rcv)));
1960
1961    if (socket_send(viftable[vifi].v_rsvpd, m, &rsvp_src) < 0) {
1962	if (rsvpdebug)
1963	    printf("rsvp_input: Failed to append to socket\n");
1964    } else {
1965	if (rsvpdebug)
1966	    printf("rsvp_input: send packet up\n");
1967    }
1968    VIF_UNLOCK();
1969}
1970
1971/*
1972 * Code for bandwidth monitors
1973 */
1974
1975/*
1976 * Define common interface for timeval-related methods
1977 */
1978#define	BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
1979#define	BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
1980#define	BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
1981
1982static uint32_t
1983compute_bw_meter_flags(struct bw_upcall *req)
1984{
1985    uint32_t flags = 0;
1986
1987    if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
1988	flags |= BW_METER_UNIT_PACKETS;
1989    if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
1990	flags |= BW_METER_UNIT_BYTES;
1991    if (req->bu_flags & BW_UPCALL_GEQ)
1992	flags |= BW_METER_GEQ;
1993    if (req->bu_flags & BW_UPCALL_LEQ)
1994	flags |= BW_METER_LEQ;
1995
1996    return flags;
1997}
1998
1999/*
2000 * Add a bw_meter entry
2001 */
2002static int
2003add_bw_upcall(struct bw_upcall *req)
2004{
2005    struct mfc *mfc;
2006    struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
2007		BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
2008    struct timeval now;
2009    struct bw_meter *x;
2010    uint32_t flags;
2011
2012    if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2013	return EOPNOTSUPP;
2014
2015    /* Test if the flags are valid */
2016    if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
2017	return EINVAL;
2018    if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
2019	return EINVAL;
2020    if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2021	    == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2022	return EINVAL;
2023
2024    /* Test if the threshold time interval is valid */
2025    if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
2026	return EINVAL;
2027
2028    flags = compute_bw_meter_flags(req);
2029
2030    /*
2031     * Find if we have already same bw_meter entry
2032     */
2033    MFC_LOCK();
2034    mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2035    if (mfc == NULL) {
2036	MFC_UNLOCK();
2037	return EADDRNOTAVAIL;
2038    }
2039    for (x = mfc->mfc_bw_meter; x != NULL; x = x->bm_mfc_next) {
2040	if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2041			   &req->bu_threshold.b_time, ==)) &&
2042	    (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2043	    (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2044	    (x->bm_flags & BW_METER_USER_FLAGS) == flags)  {
2045	    MFC_UNLOCK();
2046	    return 0;		/* XXX Already installed */
2047	}
2048    }
2049
2050    /* Allocate the new bw_meter entry */
2051    x = (struct bw_meter *)malloc(sizeof(*x), M_BWMETER, M_NOWAIT);
2052    if (x == NULL) {
2053	MFC_UNLOCK();
2054	return ENOBUFS;
2055    }
2056
2057    /* Set the new bw_meter entry */
2058    x->bm_threshold.b_time = req->bu_threshold.b_time;
2059    GET_TIME(now);
2060    x->bm_start_time = now;
2061    x->bm_threshold.b_packets = req->bu_threshold.b_packets;
2062    x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
2063    x->bm_measured.b_packets = 0;
2064    x->bm_measured.b_bytes = 0;
2065    x->bm_flags = flags;
2066    x->bm_time_next = NULL;
2067    x->bm_time_hash = BW_METER_BUCKETS;
2068
2069    /* Add the new bw_meter entry to the front of entries for this MFC */
2070    x->bm_mfc = mfc;
2071    x->bm_mfc_next = mfc->mfc_bw_meter;
2072    mfc->mfc_bw_meter = x;
2073    schedule_bw_meter(x, &now);
2074    MFC_UNLOCK();
2075
2076    return 0;
2077}
2078
2079static void
2080free_bw_list(struct bw_meter *list)
2081{
2082    while (list != NULL) {
2083	struct bw_meter *x = list;
2084
2085	list = list->bm_mfc_next;
2086	unschedule_bw_meter(x);
2087	free(x, M_BWMETER);
2088    }
2089}
2090
2091/*
2092 * Delete one or multiple bw_meter entries
2093 */
2094static int
2095del_bw_upcall(struct bw_upcall *req)
2096{
2097    struct mfc *mfc;
2098    struct bw_meter *x;
2099
2100    if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2101	return EOPNOTSUPP;
2102
2103    MFC_LOCK();
2104    /* Find the corresponding MFC entry */
2105    mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2106    if (mfc == NULL) {
2107	MFC_UNLOCK();
2108	return EADDRNOTAVAIL;
2109    } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2110	/*
2111	 * Delete all bw_meter entries for this mfc
2112	 */
2113	struct bw_meter *list;
2114
2115	list = mfc->mfc_bw_meter;
2116	mfc->mfc_bw_meter = NULL;
2117	free_bw_list(list);
2118	MFC_UNLOCK();
2119	return 0;
2120    } else {			/* Delete a single bw_meter entry */
2121	struct bw_meter *prev;
2122	uint32_t flags = 0;
2123
2124	flags = compute_bw_meter_flags(req);
2125
2126	/* Find the bw_meter entry to delete */
2127	for (prev = NULL, x = mfc->mfc_bw_meter; x != NULL;
2128	     prev = x, x = x->bm_mfc_next) {
2129	    if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2130			       &req->bu_threshold.b_time, ==)) &&
2131		(x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2132		(x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2133		(x->bm_flags & BW_METER_USER_FLAGS) == flags)
2134		break;
2135	}
2136	if (x != NULL) { /* Delete entry from the list for this MFC */
2137	    if (prev != NULL)
2138		prev->bm_mfc_next = x->bm_mfc_next;	/* remove from middle*/
2139	    else
2140		x->bm_mfc->mfc_bw_meter = x->bm_mfc_next;/* new head of list */
2141
2142	    unschedule_bw_meter(x);
2143	    MFC_UNLOCK();
2144	    /* Free the bw_meter entry */
2145	    free(x, M_BWMETER);
2146	    return 0;
2147	} else {
2148	    MFC_UNLOCK();
2149	    return EINVAL;
2150	}
2151    }
2152    /* NOTREACHED */
2153}
2154
2155/*
2156 * Perform bandwidth measurement processing that may result in an upcall
2157 */
2158static void
2159bw_meter_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2160{
2161    struct timeval delta;
2162
2163    MFC_LOCK_ASSERT();
2164
2165    delta = *nowp;
2166    BW_TIMEVALDECR(&delta, &x->bm_start_time);
2167
2168    if (x->bm_flags & BW_METER_GEQ) {
2169	/*
2170	 * Processing for ">=" type of bw_meter entry
2171	 */
2172	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2173	    /* Reset the bw_meter entry */
2174	    x->bm_start_time = *nowp;
2175	    x->bm_measured.b_packets = 0;
2176	    x->bm_measured.b_bytes = 0;
2177	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2178	}
2179
2180	/* Record that a packet is received */
2181	x->bm_measured.b_packets++;
2182	x->bm_measured.b_bytes += plen;
2183
2184	/*
2185	 * Test if we should deliver an upcall
2186	 */
2187	if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2188	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2189		 (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2190		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2191		 (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2192		/* Prepare an upcall for delivery */
2193		bw_meter_prepare_upcall(x, nowp);
2194		x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2195	    }
2196	}
2197    } else if (x->bm_flags & BW_METER_LEQ) {
2198	/*
2199	 * Processing for "<=" type of bw_meter entry
2200	 */
2201	if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2202	    /*
2203	     * We are behind time with the multicast forwarding table
2204	     * scanning for "<=" type of bw_meter entries, so test now
2205	     * if we should deliver an upcall.
2206	     */
2207	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2208		 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2209		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2210		 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2211		/* Prepare an upcall for delivery */
2212		bw_meter_prepare_upcall(x, nowp);
2213	    }
2214	    /* Reschedule the bw_meter entry */
2215	    unschedule_bw_meter(x);
2216	    schedule_bw_meter(x, nowp);
2217	}
2218
2219	/* Record that a packet is received */
2220	x->bm_measured.b_packets++;
2221	x->bm_measured.b_bytes += plen;
2222
2223	/*
2224	 * Test if we should restart the measuring interval
2225	 */
2226	if ((x->bm_flags & BW_METER_UNIT_PACKETS &&
2227	     x->bm_measured.b_packets <= x->bm_threshold.b_packets) ||
2228	    (x->bm_flags & BW_METER_UNIT_BYTES &&
2229	     x->bm_measured.b_bytes <= x->bm_threshold.b_bytes)) {
2230	    /* Don't restart the measuring interval */
2231	} else {
2232	    /* Do restart the measuring interval */
2233	    /*
2234	     * XXX: note that we don't unschedule and schedule, because this
2235	     * might be too much overhead per packet. Instead, when we process
2236	     * all entries for a given timer hash bin, we check whether it is
2237	     * really a timeout. If not, we reschedule at that time.
2238	     */
2239	    x->bm_start_time = *nowp;
2240	    x->bm_measured.b_packets = 0;
2241	    x->bm_measured.b_bytes = 0;
2242	    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2243	}
2244    }
2245}
2246
2247/*
2248 * Prepare a bandwidth-related upcall
2249 */
2250static void
2251bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2252{
2253    struct timeval delta;
2254    struct bw_upcall *u;
2255
2256    MFC_LOCK_ASSERT();
2257
2258    /*
2259     * Compute the measured time interval
2260     */
2261    delta = *nowp;
2262    BW_TIMEVALDECR(&delta, &x->bm_start_time);
2263
2264    /*
2265     * If there are too many pending upcalls, deliver them now
2266     */
2267    if (bw_upcalls_n >= BW_UPCALLS_MAX)
2268	bw_upcalls_send();
2269
2270    /*
2271     * Set the bw_upcall entry
2272     */
2273    u = &bw_upcalls[bw_upcalls_n++];
2274    u->bu_src = x->bm_mfc->mfc_origin;
2275    u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2276    u->bu_threshold.b_time = x->bm_threshold.b_time;
2277    u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2278    u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2279    u->bu_measured.b_time = delta;
2280    u->bu_measured.b_packets = x->bm_measured.b_packets;
2281    u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2282    u->bu_flags = 0;
2283    if (x->bm_flags & BW_METER_UNIT_PACKETS)
2284	u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2285    if (x->bm_flags & BW_METER_UNIT_BYTES)
2286	u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2287    if (x->bm_flags & BW_METER_GEQ)
2288	u->bu_flags |= BW_UPCALL_GEQ;
2289    if (x->bm_flags & BW_METER_LEQ)
2290	u->bu_flags |= BW_UPCALL_LEQ;
2291}
2292
2293/*
2294 * Send the pending bandwidth-related upcalls
2295 */
2296static void
2297bw_upcalls_send(void)
2298{
2299    INIT_VNET_INET(curvnet);
2300    struct mbuf *m;
2301    int len = bw_upcalls_n * sizeof(bw_upcalls[0]);
2302    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2303    static struct igmpmsg igmpmsg = { 0,		/* unused1 */
2304				      0,		/* unused2 */
2305				      IGMPMSG_BW_UPCALL,/* im_msgtype */
2306				      0,		/* im_mbz  */
2307				      0,		/* im_vif  */
2308				      0,		/* unused3 */
2309				      { 0 },		/* im_src  */
2310				      { 0 } };		/* im_dst  */
2311
2312    MFC_LOCK_ASSERT();
2313
2314    if (bw_upcalls_n == 0)
2315	return;			/* No pending upcalls */
2316
2317    bw_upcalls_n = 0;
2318
2319    /*
2320     * Allocate a new mbuf, initialize it with the header and
2321     * the payload for the pending calls.
2322     */
2323    MGETHDR(m, M_DONTWAIT, MT_DATA);
2324    if (m == NULL) {
2325	log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2326	return;
2327    }
2328
2329    m->m_len = m->m_pkthdr.len = 0;
2330    m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2331    m_copyback(m, sizeof(struct igmpmsg), len, (caddr_t)&bw_upcalls[0]);
2332
2333    /*
2334     * Send the upcalls
2335     * XXX do we need to set the address in k_igmpsrc ?
2336     */
2337    mrtstat.mrts_upcalls++;
2338    if (socket_send(V_ip_mrouter, m, &k_igmpsrc) < 0) {
2339	log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2340	++mrtstat.mrts_upq_sockfull;
2341    }
2342}
2343
2344/*
2345 * Compute the timeout hash value for the bw_meter entries
2346 */
2347#define	BW_METER_TIMEHASH(bw_meter, hash)				\
2348    do {								\
2349	struct timeval next_timeval = (bw_meter)->bm_start_time;	\
2350									\
2351	BW_TIMEVALADD(&next_timeval, &(bw_meter)->bm_threshold.b_time); \
2352	(hash) = next_timeval.tv_sec;					\
2353	if (next_timeval.tv_usec)					\
2354	    (hash)++; /* XXX: make sure we don't timeout early */	\
2355	(hash) %= BW_METER_BUCKETS;					\
2356    } while (0)
2357
2358/*
2359 * Schedule a timer to process periodically bw_meter entry of type "<="
2360 * by linking the entry in the proper hash bucket.
2361 */
2362static void
2363schedule_bw_meter(struct bw_meter *x, struct timeval *nowp)
2364{
2365    int time_hash;
2366
2367    MFC_LOCK_ASSERT();
2368
2369    if (!(x->bm_flags & BW_METER_LEQ))
2370	return;		/* XXX: we schedule timers only for "<=" entries */
2371
2372    /*
2373     * Reset the bw_meter entry
2374     */
2375    x->bm_start_time = *nowp;
2376    x->bm_measured.b_packets = 0;
2377    x->bm_measured.b_bytes = 0;
2378    x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2379
2380    /*
2381     * Compute the timeout hash value and insert the entry
2382     */
2383    BW_METER_TIMEHASH(x, time_hash);
2384    x->bm_time_next = bw_meter_timers[time_hash];
2385    bw_meter_timers[time_hash] = x;
2386    x->bm_time_hash = time_hash;
2387}
2388
2389/*
2390 * Unschedule the periodic timer that processes bw_meter entry of type "<="
2391 * by removing the entry from the proper hash bucket.
2392 */
2393static void
2394unschedule_bw_meter(struct bw_meter *x)
2395{
2396    int time_hash;
2397    struct bw_meter *prev, *tmp;
2398
2399    MFC_LOCK_ASSERT();
2400
2401    if (!(x->bm_flags & BW_METER_LEQ))
2402	return;		/* XXX: we schedule timers only for "<=" entries */
2403
2404    /*
2405     * Compute the timeout hash value and delete the entry
2406     */
2407    time_hash = x->bm_time_hash;
2408    if (time_hash >= BW_METER_BUCKETS)
2409	return;		/* Entry was not scheduled */
2410
2411    for (prev = NULL, tmp = bw_meter_timers[time_hash];
2412	     tmp != NULL; prev = tmp, tmp = tmp->bm_time_next)
2413	if (tmp == x)
2414	    break;
2415
2416    if (tmp == NULL)
2417	panic("unschedule_bw_meter: bw_meter entry not found");
2418
2419    if (prev != NULL)
2420	prev->bm_time_next = x->bm_time_next;
2421    else
2422	bw_meter_timers[time_hash] = x->bm_time_next;
2423
2424    x->bm_time_next = NULL;
2425    x->bm_time_hash = BW_METER_BUCKETS;
2426}
2427
2428
2429/*
2430 * Process all "<=" type of bw_meter that should be processed now,
2431 * and for each entry prepare an upcall if necessary. Each processed
2432 * entry is rescheduled again for the (periodic) processing.
2433 *
2434 * This is run periodically (once per second normally). On each round,
2435 * all the potentially matching entries are in the hash slot that we are
2436 * looking at.
2437 */
2438static void
2439bw_meter_process()
2440{
2441    static uint32_t last_tv_sec;	/* last time we processed this */
2442
2443    uint32_t loops;
2444    int i;
2445    struct timeval now, process_endtime;
2446
2447    GET_TIME(now);
2448    if (last_tv_sec == now.tv_sec)
2449	return;		/* nothing to do */
2450
2451    loops = now.tv_sec - last_tv_sec;
2452    last_tv_sec = now.tv_sec;
2453    if (loops > BW_METER_BUCKETS)
2454	loops = BW_METER_BUCKETS;
2455
2456    MFC_LOCK();
2457    /*
2458     * Process all bins of bw_meter entries from the one after the last
2459     * processed to the current one. On entry, i points to the last bucket
2460     * visited, so we need to increment i at the beginning of the loop.
2461     */
2462    for (i = (now.tv_sec - loops) % BW_METER_BUCKETS; loops > 0; loops--) {
2463	struct bw_meter *x, *tmp_list;
2464
2465	if (++i >= BW_METER_BUCKETS)
2466	    i = 0;
2467
2468	/* Disconnect the list of bw_meter entries from the bin */
2469	tmp_list = bw_meter_timers[i];
2470	bw_meter_timers[i] = NULL;
2471
2472	/* Process the list of bw_meter entries */
2473	while (tmp_list != NULL) {
2474	    x = tmp_list;
2475	    tmp_list = tmp_list->bm_time_next;
2476
2477	    /* Test if the time interval is over */
2478	    process_endtime = x->bm_start_time;
2479	    BW_TIMEVALADD(&process_endtime, &x->bm_threshold.b_time);
2480	    if (BW_TIMEVALCMP(&process_endtime, &now, >)) {
2481		/* Not yet: reschedule, but don't reset */
2482		int time_hash;
2483
2484		BW_METER_TIMEHASH(x, time_hash);
2485		if (time_hash == i && process_endtime.tv_sec == now.tv_sec) {
2486		    /*
2487		     * XXX: somehow the bin processing is a bit ahead of time.
2488		     * Put the entry in the next bin.
2489		     */
2490		    if (++time_hash >= BW_METER_BUCKETS)
2491			time_hash = 0;
2492		}
2493		x->bm_time_next = bw_meter_timers[time_hash];
2494		bw_meter_timers[time_hash] = x;
2495		x->bm_time_hash = time_hash;
2496
2497		continue;
2498	    }
2499
2500	    /*
2501	     * Test if we should deliver an upcall
2502	     */
2503	    if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2504		 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2505		((x->bm_flags & BW_METER_UNIT_BYTES) &&
2506		 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2507		/* Prepare an upcall for delivery */
2508		bw_meter_prepare_upcall(x, &now);
2509	    }
2510
2511	    /*
2512	     * Reschedule for next processing
2513	     */
2514	    schedule_bw_meter(x, &now);
2515	}
2516    }
2517
2518    /* Send all upcalls that are pending delivery */
2519    bw_upcalls_send();
2520
2521    MFC_UNLOCK();
2522}
2523
2524/*
2525 * A periodic function for sending all upcalls that are pending delivery
2526 */
2527static void
2528expire_bw_upcalls_send(void *unused)
2529{
2530    MFC_LOCK();
2531    bw_upcalls_send();
2532    MFC_UNLOCK();
2533
2534    callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
2535	expire_bw_upcalls_send, NULL);
2536}
2537
2538/*
2539 * A periodic function for periodic scanning of the multicast forwarding
2540 * table for processing all "<=" bw_meter entries.
2541 */
2542static void
2543expire_bw_meter_process(void *unused)
2544{
2545    if (mrt_api_config & MRT_MFC_BW_UPCALL)
2546	bw_meter_process();
2547
2548    callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
2549}
2550
2551/*
2552 * End of bandwidth monitoring code
2553 */
2554
2555/*
2556 * Send the packet up to the user daemon, or eventually do kernel encapsulation
2557 *
2558 */
2559static int
2560pim_register_send(struct ip *ip, struct vif *vifp, struct mbuf *m,
2561    struct mfc *rt)
2562{
2563    struct mbuf *mb_copy, *mm;
2564
2565    if (mrtdebug & DEBUG_PIM)
2566	log(LOG_DEBUG, "pim_register_send: ");
2567
2568    /*
2569     * Do not send IGMP_WHOLEPKT notifications to userland, if the
2570     * rendezvous point was unspecified, and we were told not to.
2571     */
2572    if (pim_squelch_wholepkt != 0 && (mrt_api_config & MRT_MFC_RP) &&
2573	(rt->mfc_rp.s_addr == INADDR_ANY))
2574	return 0;
2575
2576    mb_copy = pim_register_prepare(ip, m);
2577    if (mb_copy == NULL)
2578	return ENOBUFS;
2579
2580    /*
2581     * Send all the fragments. Note that the mbuf for each fragment
2582     * is freed by the sending machinery.
2583     */
2584    for (mm = mb_copy; mm; mm = mb_copy) {
2585	mb_copy = mm->m_nextpkt;
2586	mm->m_nextpkt = 0;
2587	mm = m_pullup(mm, sizeof(struct ip));
2588	if (mm != NULL) {
2589	    ip = mtod(mm, struct ip *);
2590	    if ((mrt_api_config & MRT_MFC_RP) &&
2591		(rt->mfc_rp.s_addr != INADDR_ANY)) {
2592		pim_register_send_rp(ip, vifp, mm, rt);
2593	    } else {
2594		pim_register_send_upcall(ip, vifp, mm, rt);
2595	    }
2596	}
2597    }
2598
2599    return 0;
2600}
2601
2602/*
2603 * Return a copy of the data packet that is ready for PIM Register
2604 * encapsulation.
2605 * XXX: Note that in the returned copy the IP header is a valid one.
2606 */
2607static struct mbuf *
2608pim_register_prepare(struct ip *ip, struct mbuf *m)
2609{
2610    struct mbuf *mb_copy = NULL;
2611    int mtu;
2612
2613    /* Take care of delayed checksums */
2614    if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2615	in_delayed_cksum(m);
2616	m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2617    }
2618
2619    /*
2620     * Copy the old packet & pullup its IP header into the
2621     * new mbuf so we can modify it.
2622     */
2623    mb_copy = m_copypacket(m, M_DONTWAIT);
2624    if (mb_copy == NULL)
2625	return NULL;
2626    mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2627    if (mb_copy == NULL)
2628	return NULL;
2629
2630    /* take care of the TTL */
2631    ip = mtod(mb_copy, struct ip *);
2632    --ip->ip_ttl;
2633
2634    /* Compute the MTU after the PIM Register encapsulation */
2635    mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2636
2637    if (ip->ip_len <= mtu) {
2638	/* Turn the IP header into a valid one */
2639	ip->ip_len = htons(ip->ip_len);
2640	ip->ip_off = htons(ip->ip_off);
2641	ip->ip_sum = 0;
2642	ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2643    } else {
2644	/* Fragment the packet */
2645	if (ip_fragment(ip, &mb_copy, mtu, 0, CSUM_DELAY_IP) != 0) {
2646	    m_freem(mb_copy);
2647	    return NULL;
2648	}
2649    }
2650    return mb_copy;
2651}
2652
2653/*
2654 * Send an upcall with the data packet to the user-level process.
2655 */
2656static int
2657pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2658    struct mbuf *mb_copy, struct mfc *rt)
2659{
2660    INIT_VNET_INET(curvnet);
2661    struct mbuf *mb_first;
2662    int len = ntohs(ip->ip_len);
2663    struct igmpmsg *im;
2664    struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2665
2666    VIF_LOCK_ASSERT();
2667
2668    /*
2669     * Add a new mbuf with an upcall header
2670     */
2671    MGETHDR(mb_first, M_DONTWAIT, MT_DATA);
2672    if (mb_first == NULL) {
2673	m_freem(mb_copy);
2674	return ENOBUFS;
2675    }
2676    mb_first->m_data += max_linkhdr;
2677    mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2678    mb_first->m_len = sizeof(struct igmpmsg);
2679    mb_first->m_next = mb_copy;
2680
2681    /* Send message to routing daemon */
2682    im = mtod(mb_first, struct igmpmsg *);
2683    im->im_msgtype	= IGMPMSG_WHOLEPKT;
2684    im->im_mbz		= 0;
2685    im->im_vif		= vifp - viftable;
2686    im->im_src		= ip->ip_src;
2687    im->im_dst		= ip->ip_dst;
2688
2689    k_igmpsrc.sin_addr	= ip->ip_src;
2690
2691    mrtstat.mrts_upcalls++;
2692
2693    if (socket_send(V_ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2694	if (mrtdebug & DEBUG_PIM)
2695	    log(LOG_WARNING,
2696		"mcast: pim_register_send_upcall: ip_mrouter socket queue full");
2697	++mrtstat.mrts_upq_sockfull;
2698	return ENOBUFS;
2699    }
2700
2701    /* Keep statistics */
2702    pimstat.pims_snd_registers_msgs++;
2703    pimstat.pims_snd_registers_bytes += len;
2704
2705    return 0;
2706}
2707
2708/*
2709 * Encapsulate the data packet in PIM Register message and send it to the RP.
2710 */
2711static int
2712pim_register_send_rp(struct ip *ip, struct vif *vifp, struct mbuf *mb_copy,
2713    struct mfc *rt)
2714{
2715    INIT_VNET_INET(curvnet);
2716    struct mbuf *mb_first;
2717    struct ip *ip_outer;
2718    struct pim_encap_pimhdr *pimhdr;
2719    int len = ntohs(ip->ip_len);
2720    vifi_t vifi = rt->mfc_parent;
2721
2722    VIF_LOCK_ASSERT();
2723
2724    if ((vifi >= numvifs) || (viftable[vifi].v_lcl_addr.s_addr == 0)) {
2725	m_freem(mb_copy);
2726	return EADDRNOTAVAIL;		/* The iif vif is invalid */
2727    }
2728
2729    /*
2730     * Add a new mbuf with the encapsulating header
2731     */
2732    MGETHDR(mb_first, M_DONTWAIT, MT_DATA);
2733    if (mb_first == NULL) {
2734	m_freem(mb_copy);
2735	return ENOBUFS;
2736    }
2737    mb_first->m_data += max_linkhdr;
2738    mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2739    mb_first->m_next = mb_copy;
2740
2741    mb_first->m_pkthdr.len = len + mb_first->m_len;
2742
2743    /*
2744     * Fill in the encapsulating IP and PIM header
2745     */
2746    ip_outer = mtod(mb_first, struct ip *);
2747    *ip_outer = pim_encap_iphdr;
2748    ip_outer->ip_id = ip_newid();
2749    ip_outer->ip_len = len + sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2750    ip_outer->ip_src = viftable[vifi].v_lcl_addr;
2751    ip_outer->ip_dst = rt->mfc_rp;
2752    /*
2753     * Copy the inner header TOS to the outer header, and take care of the
2754     * IP_DF bit.
2755     */
2756    ip_outer->ip_tos = ip->ip_tos;
2757    if (ntohs(ip->ip_off) & IP_DF)
2758	ip_outer->ip_off |= IP_DF;
2759    pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2760					 + sizeof(pim_encap_iphdr));
2761    *pimhdr = pim_encap_pimhdr;
2762    /* If the iif crosses a border, set the Border-bit */
2763    if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & mrt_api_config)
2764	pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
2765
2766    mb_first->m_data += sizeof(pim_encap_iphdr);
2767    pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
2768    mb_first->m_data -= sizeof(pim_encap_iphdr);
2769
2770    send_packet(vifp, mb_first);
2771
2772    /* Keep statistics */
2773    pimstat.pims_snd_registers_msgs++;
2774    pimstat.pims_snd_registers_bytes += len;
2775
2776    return 0;
2777}
2778
2779/*
2780 * pim_encapcheck() is called by the encap[46]_input() path at runtime to
2781 * determine if a packet is for PIM; allowing PIM to be dynamically loaded
2782 * into the kernel.
2783 */
2784static int
2785pim_encapcheck(const struct mbuf *m, int off, int proto, void *arg)
2786{
2787
2788#ifdef DIAGNOSTIC
2789    KASSERT(proto == IPPROTO_PIM, ("not for IPPROTO_PIM"));
2790#endif
2791    if (proto != IPPROTO_PIM)
2792	return 0;	/* not for us; reject the datagram. */
2793
2794    return 64;		/* claim the datagram. */
2795}
2796
2797/*
2798 * PIM-SMv2 and PIM-DM messages processing.
2799 * Receives and verifies the PIM control messages, and passes them
2800 * up to the listening socket, using rip_input().
2801 * The only message with special processing is the PIM_REGISTER message
2802 * (used by PIM-SM): the PIM header is stripped off, and the inner packet
2803 * is passed to if_simloop().
2804 */
2805void
2806pim_input(struct mbuf *m, int off)
2807{
2808    struct ip *ip = mtod(m, struct ip *);
2809    struct pim *pim;
2810    int minlen;
2811    int datalen = ip->ip_len;
2812    int ip_tos;
2813    int iphlen = off;
2814
2815    /* Keep statistics */
2816    pimstat.pims_rcv_total_msgs++;
2817    pimstat.pims_rcv_total_bytes += datalen;
2818
2819    /*
2820     * Validate lengths
2821     */
2822    if (datalen < PIM_MINLEN) {
2823	pimstat.pims_rcv_tooshort++;
2824	log(LOG_ERR, "pim_input: packet size too small %d from %lx\n",
2825	    datalen, (u_long)ip->ip_src.s_addr);
2826	m_freem(m);
2827	return;
2828    }
2829
2830    /*
2831     * If the packet is at least as big as a REGISTER, go agead
2832     * and grab the PIM REGISTER header size, to avoid another
2833     * possible m_pullup() later.
2834     *
2835     * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
2836     * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
2837     */
2838    minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
2839    /*
2840     * Get the IP and PIM headers in contiguous memory, and
2841     * possibly the PIM REGISTER header.
2842     */
2843    if ((m->m_flags & M_EXT || m->m_len < minlen) &&
2844	(m = m_pullup(m, minlen)) == 0) {
2845	log(LOG_ERR, "pim_input: m_pullup failure\n");
2846	return;
2847    }
2848    /* m_pullup() may have given us a new mbuf so reset ip. */
2849    ip = mtod(m, struct ip *);
2850    ip_tos = ip->ip_tos;
2851
2852    /* adjust mbuf to point to the PIM header */
2853    m->m_data += iphlen;
2854    m->m_len  -= iphlen;
2855    pim = mtod(m, struct pim *);
2856
2857    /*
2858     * Validate checksum. If PIM REGISTER, exclude the data packet.
2859     *
2860     * XXX: some older PIMv2 implementations don't make this distinction,
2861     * so for compatibility reason perform the checksum over part of the
2862     * message, and if error, then over the whole message.
2863     */
2864    if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
2865	/* do nothing, checksum okay */
2866    } else if (in_cksum(m, datalen)) {
2867	pimstat.pims_rcv_badsum++;
2868	if (mrtdebug & DEBUG_PIM)
2869	    log(LOG_DEBUG, "pim_input: invalid checksum");
2870	m_freem(m);
2871	return;
2872    }
2873
2874    /* PIM version check */
2875    if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
2876	pimstat.pims_rcv_badversion++;
2877	log(LOG_ERR, "pim_input: incorrect version %d, expecting %d\n",
2878	    PIM_VT_V(pim->pim_vt), PIM_VERSION);
2879	m_freem(m);
2880	return;
2881    }
2882
2883    /* restore mbuf back to the outer IP */
2884    m->m_data -= iphlen;
2885    m->m_len  += iphlen;
2886
2887    if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
2888	/*
2889	 * Since this is a REGISTER, we'll make a copy of the register
2890	 * headers ip + pim + u_int32 + encap_ip, to be passed up to the
2891	 * routing daemon.
2892	 */
2893	struct sockaddr_in dst = { sizeof(dst), AF_INET };
2894	struct mbuf *mcp;
2895	struct ip *encap_ip;
2896	u_int32_t *reghdr;
2897	struct ifnet *vifp;
2898
2899	VIF_LOCK();
2900	if ((reg_vif_num >= numvifs) || (reg_vif_num == VIFI_INVALID)) {
2901	    VIF_UNLOCK();
2902	    if (mrtdebug & DEBUG_PIM)
2903		log(LOG_DEBUG,
2904		    "pim_input: register vif not set: %d\n", reg_vif_num);
2905	    m_freem(m);
2906	    return;
2907	}
2908	/* XXX need refcnt? */
2909	vifp = viftable[reg_vif_num].v_ifp;
2910	VIF_UNLOCK();
2911
2912	/*
2913	 * Validate length
2914	 */
2915	if (datalen < PIM_REG_MINLEN) {
2916	    pimstat.pims_rcv_tooshort++;
2917	    pimstat.pims_rcv_badregisters++;
2918	    log(LOG_ERR,
2919		"pim_input: register packet size too small %d from %lx\n",
2920		datalen, (u_long)ip->ip_src.s_addr);
2921	    m_freem(m);
2922	    return;
2923	}
2924
2925	reghdr = (u_int32_t *)(pim + 1);
2926	encap_ip = (struct ip *)(reghdr + 1);
2927
2928	if (mrtdebug & DEBUG_PIM) {
2929	    log(LOG_DEBUG,
2930		"pim_input[register], encap_ip: %lx -> %lx, encap_ip len %d\n",
2931		(u_long)ntohl(encap_ip->ip_src.s_addr),
2932		(u_long)ntohl(encap_ip->ip_dst.s_addr),
2933		ntohs(encap_ip->ip_len));
2934	}
2935
2936	/* verify the version number of the inner packet */
2937	if (encap_ip->ip_v != IPVERSION) {
2938	    pimstat.pims_rcv_badregisters++;
2939	    if (mrtdebug & DEBUG_PIM) {
2940		log(LOG_DEBUG, "pim_input: invalid IP version (%d) "
2941		    "of the inner packet\n", encap_ip->ip_v);
2942	    }
2943	    m_freem(m);
2944	    return;
2945	}
2946
2947	/* verify the inner packet is destined to a mcast group */
2948	if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
2949	    pimstat.pims_rcv_badregisters++;
2950	    if (mrtdebug & DEBUG_PIM)
2951		log(LOG_DEBUG,
2952		    "pim_input: inner packet of register is not "
2953		    "multicast %lx\n",
2954		    (u_long)ntohl(encap_ip->ip_dst.s_addr));
2955	    m_freem(m);
2956	    return;
2957	}
2958
2959	/* If a NULL_REGISTER, pass it to the daemon */
2960	if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
2961	    goto pim_input_to_daemon;
2962
2963	/*
2964	 * Copy the TOS from the outer IP header to the inner IP header.
2965	 */
2966	if (encap_ip->ip_tos != ip_tos) {
2967	    /* Outer TOS -> inner TOS */
2968	    encap_ip->ip_tos = ip_tos;
2969	    /* Recompute the inner header checksum. Sigh... */
2970
2971	    /* adjust mbuf to point to the inner IP header */
2972	    m->m_data += (iphlen + PIM_MINLEN);
2973	    m->m_len  -= (iphlen + PIM_MINLEN);
2974
2975	    encap_ip->ip_sum = 0;
2976	    encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
2977
2978	    /* restore mbuf to point back to the outer IP header */
2979	    m->m_data -= (iphlen + PIM_MINLEN);
2980	    m->m_len  += (iphlen + PIM_MINLEN);
2981	}
2982
2983	/*
2984	 * Decapsulate the inner IP packet and loopback to forward it
2985	 * as a normal multicast packet. Also, make a copy of the
2986	 *     outer_iphdr + pimhdr + reghdr + encap_iphdr
2987	 * to pass to the daemon later, so it can take the appropriate
2988	 * actions (e.g., send back PIM_REGISTER_STOP).
2989	 * XXX: here m->m_data points to the outer IP header.
2990	 */
2991	mcp = m_copy(m, 0, iphlen + PIM_REG_MINLEN);
2992	if (mcp == NULL) {
2993	    log(LOG_ERR,
2994		"pim_input: pim register: could not copy register head\n");
2995	    m_freem(m);
2996	    return;
2997	}
2998
2999	/* Keep statistics */
3000	/* XXX: registers_bytes include only the encap. mcast pkt */
3001	pimstat.pims_rcv_registers_msgs++;
3002	pimstat.pims_rcv_registers_bytes += ntohs(encap_ip->ip_len);
3003
3004	/*
3005	 * forward the inner ip packet; point m_data at the inner ip.
3006	 */
3007	m_adj(m, iphlen + PIM_MINLEN);
3008
3009	if (mrtdebug & DEBUG_PIM) {
3010	    log(LOG_DEBUG,
3011		"pim_input: forwarding decapsulated register: "
3012		"src %lx, dst %lx, vif %d\n",
3013		(u_long)ntohl(encap_ip->ip_src.s_addr),
3014		(u_long)ntohl(encap_ip->ip_dst.s_addr),
3015		reg_vif_num);
3016	}
3017	/* NB: vifp was collected above; can it change on us? */
3018	if_simloop(vifp, m, dst.sin_family, 0);
3019
3020	/* prepare the register head to send to the mrouting daemon */
3021	m = mcp;
3022    }
3023
3024pim_input_to_daemon:
3025    /*
3026     * Pass the PIM message up to the daemon; if it is a Register message,
3027     * pass the 'head' only up to the daemon. This includes the
3028     * outer IP header, PIM header, PIM-Register header and the
3029     * inner IP header.
3030     * XXX: the outer IP header pkt size of a Register is not adjust to
3031     * reflect the fact that the inner multicast data is truncated.
3032     */
3033    rip_input(m, iphlen);
3034
3035    return;
3036}
3037
3038/*
3039 * XXX: This is common code for dealing with initialization for both
3040 * the IPv4 and IPv6 multicast forwarding paths. It could do with cleanup.
3041 */
3042static int
3043ip_mroute_modevent(module_t mod, int type, void *unused)
3044{
3045    INIT_VNET_INET(curvnet);
3046
3047    switch (type) {
3048    case MOD_LOAD:
3049	MROUTER_LOCK_INIT();
3050	MFC_LOCK_INIT();
3051	VIF_LOCK_INIT();
3052	ip_mrouter_reset();
3053	TUNABLE_ULONG_FETCH("net.inet.pim.squelch_wholepkt",
3054	    &pim_squelch_wholepkt);
3055
3056	pim_encap_cookie = encap_attach_func(AF_INET, IPPROTO_PIM,
3057	    pim_encapcheck, &in_pim_protosw, NULL);
3058	if (pim_encap_cookie == NULL) {
3059		printf("ip_mroute: unable to attach pim encap\n");
3060		VIF_LOCK_DESTROY();
3061		MFC_LOCK_DESTROY();
3062		MROUTER_LOCK_DESTROY();
3063		return (EINVAL);
3064	}
3065
3066#ifdef INET6
3067	pim6_encap_cookie = encap_attach_func(AF_INET6, IPPROTO_PIM,
3068	    pim_encapcheck, (struct protosw *)&in6_pim_protosw, NULL);
3069	if (pim6_encap_cookie == NULL) {
3070		printf("ip_mroute: unable to attach pim6 encap\n");
3071		if (pim_encap_cookie) {
3072		    encap_detach(pim_encap_cookie);
3073		    pim_encap_cookie = NULL;
3074		}
3075		VIF_LOCK_DESTROY();
3076		MFC_LOCK_DESTROY();
3077		MROUTER_LOCK_DESTROY();
3078		return (EINVAL);
3079	}
3080#endif
3081
3082	ip_mcast_src = X_ip_mcast_src;
3083	ip_mforward = X_ip_mforward;
3084	ip_mrouter_done = X_ip_mrouter_done;
3085	ip_mrouter_get = X_ip_mrouter_get;
3086	ip_mrouter_set = X_ip_mrouter_set;
3087
3088#ifdef INET6
3089	ip6_mforward = X_ip6_mforward;
3090	ip6_mrouter_done = X_ip6_mrouter_done;
3091	ip6_mrouter_get = X_ip6_mrouter_get;
3092	ip6_mrouter_set = X_ip6_mrouter_set;
3093	mrt6_ioctl = X_mrt6_ioctl;
3094#endif
3095
3096	ip_rsvp_force_done = X_ip_rsvp_force_done;
3097	ip_rsvp_vif = X_ip_rsvp_vif;
3098
3099	legal_vif_num = X_legal_vif_num;
3100	mrt_ioctl = X_mrt_ioctl;
3101	rsvp_input_p = X_rsvp_input;
3102	break;
3103
3104    case MOD_UNLOAD:
3105	/*
3106	 * Typically module unload happens after the user-level
3107	 * process has shutdown the kernel services (the check
3108	 * below insures someone can't just yank the module out
3109	 * from under a running process).  But if the module is
3110	 * just loaded and then unloaded w/o starting up a user
3111	 * process we still need to cleanup.
3112	 */
3113	if (V_ip_mrouter
3114#ifdef INET6
3115	    || ip6_mrouter
3116#endif
3117	)
3118	    return EINVAL;
3119
3120#ifdef INET6
3121	if (pim6_encap_cookie) {
3122	    encap_detach(pim6_encap_cookie);
3123	    pim6_encap_cookie = NULL;
3124	}
3125	X_ip6_mrouter_done();
3126	ip6_mforward = NULL;
3127	ip6_mrouter_done = NULL;
3128	ip6_mrouter_get = NULL;
3129	ip6_mrouter_set = NULL;
3130	mrt6_ioctl = NULL;
3131#endif
3132
3133	if (pim_encap_cookie) {
3134	    encap_detach(pim_encap_cookie);
3135	    pim_encap_cookie = NULL;
3136	}
3137	X_ip_mrouter_done();
3138	ip_mcast_src = NULL;
3139	ip_mforward = NULL;
3140	ip_mrouter_done = NULL;
3141	ip_mrouter_get = NULL;
3142	ip_mrouter_set = NULL;
3143
3144	ip_rsvp_force_done = NULL;
3145	ip_rsvp_vif = NULL;
3146
3147	legal_vif_num = NULL;
3148	mrt_ioctl = NULL;
3149	rsvp_input_p = NULL;
3150
3151	VIF_LOCK_DESTROY();
3152	MFC_LOCK_DESTROY();
3153	MROUTER_LOCK_DESTROY();
3154	break;
3155
3156    default:
3157	return EOPNOTSUPP;
3158    }
3159    return 0;
3160}
3161
3162static moduledata_t ip_mroutemod = {
3163    "ip_mroute",
3164    ip_mroute_modevent,
3165    0
3166};
3167DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PSEUDO, SI_ORDER_ANY);
3168