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