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