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