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