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