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