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