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