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