The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netinet/ip_mroute.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: ec1bf5c4e3a9c85b7caee1b347267b7e


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.