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/netinet6/in6_mcast.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) 2009 Bruce Simpson.
    3  * All rights reserved.
    4  *
    5  * Redistribution and use in source and binary forms, with or without
    6  * modification, are permitted provided that the following conditions
    7  * are met:
    8  * 1. Redistributions of source code must retain the above copyright
    9  *    notice, this list of conditions and the following disclaimer.
   10  * 2. Redistributions in binary form must reproduce the above copyright
   11  *    notice, this list of conditions and the following disclaimer in the
   12  *    documentation and/or other materials provided with the distribution.
   13  * 3. The name of the author may not be used to endorse or promote
   14  *    products derived from this software without specific prior written
   15  *    permission.
   16  *
   17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   27  * SUCH DAMAGE.
   28  */
   29 
   30 /*
   31  * IPv6 multicast socket, group, and socket option processing module.
   32  * Normative references: RFC 2292, RFC 3492, RFC 3542, RFC 3678, RFC 3810.
   33  */
   34 
   35 #include <sys/cdefs.h>
   36 __FBSDID("$FreeBSD: releng/8.4/sys/netinet6/in6_mcast.c 254632 2013-08-22 00:51:56Z delphij $");
   37 
   38 #include "opt_inet6.h"
   39 
   40 #include <sys/param.h>
   41 #include <sys/systm.h>
   42 #include <sys/kernel.h>
   43 #include <sys/malloc.h>
   44 #include <sys/mbuf.h>
   45 #include <sys/protosw.h>
   46 #include <sys/socket.h>
   47 #include <sys/socketvar.h>
   48 #include <sys/protosw.h>
   49 #include <sys/sysctl.h>
   50 #include <sys/priv.h>
   51 #include <sys/ktr.h>
   52 #include <sys/tree.h>
   53 
   54 #include <net/if.h>
   55 #include <net/if_dl.h>
   56 #include <net/route.h>
   57 #include <net/vnet.h>
   58 
   59 #include <netinet/in.h>
   60 #include <netinet/in_var.h>
   61 #include <netinet6/in6_var.h>
   62 #include <netinet/ip6.h>
   63 #include <netinet/icmp6.h>
   64 #include <netinet6/ip6_var.h>
   65 #include <netinet/in_pcb.h>
   66 #include <netinet/tcp_var.h>
   67 #include <netinet6/nd6.h>
   68 #include <netinet6/mld6_var.h>
   69 #include <netinet6/scope6_var.h>
   70 
   71 #ifndef KTR_MLD
   72 #define KTR_MLD KTR_INET6
   73 #endif
   74 
   75 #ifndef __SOCKUNION_DECLARED
   76 union sockunion {
   77         struct sockaddr_storage ss;
   78         struct sockaddr         sa;
   79         struct sockaddr_dl      sdl;
   80         struct sockaddr_in6     sin6;
   81 };
   82 typedef union sockunion sockunion_t;
   83 #define __SOCKUNION_DECLARED
   84 #endif /* __SOCKUNION_DECLARED */
   85 
   86 static MALLOC_DEFINE(M_IN6MFILTER, "in6_mfilter",
   87     "IPv6 multicast PCB-layer source filter");
   88 static MALLOC_DEFINE(M_IP6MADDR, "in6_multi", "IPv6 multicast group");
   89 static MALLOC_DEFINE(M_IP6MOPTS, "ip6_moptions", "IPv6 multicast options");
   90 static MALLOC_DEFINE(M_IP6MSOURCE, "ip6_msource",
   91     "IPv6 multicast MLD-layer source filter");
   92 
   93 RB_GENERATE(ip6_msource_tree, ip6_msource, im6s_link, ip6_msource_cmp);
   94 
   95 /*
   96  * Locking:
   97  * - Lock order is: Giant, INP_WLOCK, IN6_MULTI_LOCK, MLD_LOCK, IF_ADDR_LOCK.
   98  * - The IF_ADDR_LOCK is implicitly taken by in6m_lookup() earlier, however
   99  *   it can be taken by code in net/if.c also.
  100  * - ip6_moptions and in6_mfilter are covered by the INP_WLOCK.
  101  *
  102  * struct in6_multi is covered by IN6_MULTI_LOCK. There isn't strictly
  103  * any need for in6_multi itself to be virtualized -- it is bound to an ifp
  104  * anyway no matter what happens.
  105  */
  106 struct mtx in6_multi_mtx;
  107 MTX_SYSINIT(in6_multi_mtx, &in6_multi_mtx, "in6_multi_mtx", MTX_DEF);
  108 
  109 static void     im6f_commit(struct in6_mfilter *);
  110 static int      im6f_get_source(struct in6_mfilter *imf,
  111                     const struct sockaddr_in6 *psin,
  112                     struct in6_msource **);
  113 static struct in6_msource *
  114                 im6f_graft(struct in6_mfilter *, const uint8_t,
  115                     const struct sockaddr_in6 *);
  116 static void     im6f_leave(struct in6_mfilter *);
  117 static int      im6f_prune(struct in6_mfilter *, const struct sockaddr_in6 *);
  118 static void     im6f_purge(struct in6_mfilter *);
  119 static void     im6f_rollback(struct in6_mfilter *);
  120 static void     im6f_reap(struct in6_mfilter *);
  121 static int      im6o_grow(struct ip6_moptions *);
  122 static size_t   im6o_match_group(const struct ip6_moptions *,
  123                     const struct ifnet *, const struct sockaddr *);
  124 static struct in6_msource *
  125                 im6o_match_source(const struct ip6_moptions *, const size_t,
  126                     const struct sockaddr *);
  127 static void     im6s_merge(struct ip6_msource *ims,
  128                     const struct in6_msource *lims, const int rollback);
  129 static int      in6_mc_get(struct ifnet *, const struct in6_addr *,
  130                     struct in6_multi **);
  131 static int      in6m_get_source(struct in6_multi *inm,
  132                     const struct in6_addr *addr, const int noalloc,
  133                     struct ip6_msource **pims);
  134 static int      in6m_is_ifp_detached(const struct in6_multi *);
  135 static int      in6m_merge(struct in6_multi *, /*const*/ struct in6_mfilter *);
  136 static void     in6m_purge(struct in6_multi *);
  137 static void     in6m_reap(struct in6_multi *);
  138 static struct ip6_moptions *
  139                 in6p_findmoptions(struct inpcb *);
  140 static int      in6p_get_source_filters(struct inpcb *, struct sockopt *);
  141 static int      in6p_join_group(struct inpcb *, struct sockopt *);
  142 static int      in6p_leave_group(struct inpcb *, struct sockopt *);
  143 static struct ifnet *
  144                 in6p_lookup_mcast_ifp(const struct inpcb *,
  145                     const struct sockaddr_in6 *);
  146 static int      in6p_block_unblock_source(struct inpcb *, struct sockopt *);
  147 static int      in6p_set_multicast_if(struct inpcb *, struct sockopt *);
  148 static int      in6p_set_source_filters(struct inpcb *, struct sockopt *);
  149 static int      sysctl_ip6_mcast_filters(SYSCTL_HANDLER_ARGS);
  150 
  151 SYSCTL_DECL(_net_inet6_ip6);    /* XXX Not in any common header. */
  152 
  153 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, mcast, CTLFLAG_RW, 0, "IPv6 multicast");
  154 
  155 static u_long in6_mcast_maxgrpsrc = IPV6_MAX_GROUP_SRC_FILTER;
  156 SYSCTL_ULONG(_net_inet6_ip6_mcast, OID_AUTO, maxgrpsrc,
  157     CTLFLAG_RW | CTLFLAG_TUN, &in6_mcast_maxgrpsrc, 0,
  158     "Max source filters per group");
  159 TUNABLE_ULONG("net.inet6.ip6.mcast.maxgrpsrc", &in6_mcast_maxgrpsrc);
  160 
  161 static u_long in6_mcast_maxsocksrc = IPV6_MAX_SOCK_SRC_FILTER;
  162 SYSCTL_ULONG(_net_inet6_ip6_mcast, OID_AUTO, maxsocksrc,
  163     CTLFLAG_RW | CTLFLAG_TUN, &in6_mcast_maxsocksrc, 0,
  164     "Max source filters per socket");
  165 TUNABLE_ULONG("net.inet6.ip6.mcast.maxsocksrc", &in6_mcast_maxsocksrc);
  166 
  167 /* TODO Virtualize this switch. */
  168 int in6_mcast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
  169 SYSCTL_INT(_net_inet6_ip6_mcast, OID_AUTO, loop, CTLFLAG_RW | CTLFLAG_TUN,
  170     &in6_mcast_loop, 0, "Loopback multicast datagrams by default");
  171 TUNABLE_INT("net.inet6.ip6.mcast.loop", &in6_mcast_loop);
  172 
  173 SYSCTL_NODE(_net_inet6_ip6_mcast, OID_AUTO, filters,
  174     CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_ip6_mcast_filters,
  175     "Per-interface stack-wide source filters");
  176 
  177 /*
  178  * Inline function which wraps assertions for a valid ifp.
  179  * The ifnet layer will set the ifma's ifp pointer to NULL if the ifp
  180  * is detached.
  181  */
  182 static int __inline
  183 in6m_is_ifp_detached(const struct in6_multi *inm)
  184 {
  185         struct ifnet *ifp;
  186 
  187         KASSERT(inm->in6m_ifma != NULL, ("%s: no ifma", __func__));
  188         ifp = inm->in6m_ifma->ifma_ifp;
  189         if (ifp != NULL) {
  190                 /*
  191                  * Sanity check that network-layer notion of ifp is the
  192                  * same as that of link-layer.
  193                  */
  194                 KASSERT(inm->in6m_ifp == ifp, ("%s: bad ifp", __func__));
  195         }
  196 
  197         return (ifp == NULL);
  198 }
  199 
  200 /*
  201  * Initialize an in6_mfilter structure to a known state at t0, t1
  202  * with an empty source filter list.
  203  */
  204 static __inline void
  205 im6f_init(struct in6_mfilter *imf, const int st0, const int st1)
  206 {
  207         memset(imf, 0, sizeof(struct in6_mfilter));
  208         RB_INIT(&imf->im6f_sources);
  209         imf->im6f_st[0] = st0;
  210         imf->im6f_st[1] = st1;
  211 }
  212 
  213 /*
  214  * Resize the ip6_moptions vector to the next power-of-two minus 1.
  215  * May be called with locks held; do not sleep.
  216  */
  217 static int
  218 im6o_grow(struct ip6_moptions *imo)
  219 {
  220         struct in6_multi        **nmships;
  221         struct in6_multi        **omships;
  222         struct in6_mfilter       *nmfilters;
  223         struct in6_mfilter       *omfilters;
  224         size_t                    idx;
  225         size_t                    newmax;
  226         size_t                    oldmax;
  227 
  228         nmships = NULL;
  229         nmfilters = NULL;
  230         omships = imo->im6o_membership;
  231         omfilters = imo->im6o_mfilters;
  232         oldmax = imo->im6o_max_memberships;
  233         newmax = ((oldmax + 1) * 2) - 1;
  234 
  235         if (newmax <= IPV6_MAX_MEMBERSHIPS) {
  236                 nmships = (struct in6_multi **)realloc(omships,
  237                     sizeof(struct in6_multi *) * newmax, M_IP6MOPTS, M_NOWAIT);
  238                 nmfilters = (struct in6_mfilter *)realloc(omfilters,
  239                     sizeof(struct in6_mfilter) * newmax, M_IN6MFILTER,
  240                     M_NOWAIT);
  241                 if (nmships != NULL && nmfilters != NULL) {
  242                         /* Initialize newly allocated source filter heads. */
  243                         for (idx = oldmax; idx < newmax; idx++) {
  244                                 im6f_init(&nmfilters[idx], MCAST_UNDEFINED,
  245                                     MCAST_EXCLUDE);
  246                         }
  247                         imo->im6o_max_memberships = newmax;
  248                         imo->im6o_membership = nmships;
  249                         imo->im6o_mfilters = nmfilters;
  250                 }
  251         }
  252 
  253         if (nmships == NULL || nmfilters == NULL) {
  254                 if (nmships != NULL)
  255                         free(nmships, M_IP6MOPTS);
  256                 if (nmfilters != NULL)
  257                         free(nmfilters, M_IN6MFILTER);
  258                 return (ETOOMANYREFS);
  259         }
  260 
  261         return (0);
  262 }
  263 
  264 /*
  265  * Find an IPv6 multicast group entry for this ip6_moptions instance
  266  * which matches the specified group, and optionally an interface.
  267  * Return its index into the array, or -1 if not found.
  268  */
  269 static size_t
  270 im6o_match_group(const struct ip6_moptions *imo, const struct ifnet *ifp,
  271     const struct sockaddr *group)
  272 {
  273         const struct sockaddr_in6 *gsin6;
  274         struct in6_multi        **pinm;
  275         int               idx;
  276         int               nmships;
  277 
  278         gsin6 = (const struct sockaddr_in6 *)group;
  279 
  280         /* The im6o_membership array may be lazy allocated. */
  281         if (imo->im6o_membership == NULL || imo->im6o_num_memberships == 0)
  282                 return (-1);
  283 
  284         nmships = imo->im6o_num_memberships;
  285         pinm = &imo->im6o_membership[0];
  286         for (idx = 0; idx < nmships; idx++, pinm++) {
  287                 if (*pinm == NULL)
  288                         continue;
  289                 if ((ifp == NULL || ((*pinm)->in6m_ifp == ifp)) &&
  290                     IN6_ARE_ADDR_EQUAL(&(*pinm)->in6m_addr,
  291                     &gsin6->sin6_addr)) {
  292                         break;
  293                 }
  294         }
  295         if (idx >= nmships)
  296                 idx = -1;
  297 
  298         return (idx);
  299 }
  300 
  301 /*
  302  * Find an IPv6 multicast source entry for this imo which matches
  303  * the given group index for this socket, and source address.
  304  *
  305  * XXX TODO: The scope ID, if present in src, is stripped before
  306  * any comparison. We SHOULD enforce scope/zone checks where the source
  307  * filter entry has a link scope.
  308  *
  309  * NOTE: This does not check if the entry is in-mode, merely if
  310  * it exists, which may not be the desired behaviour.
  311  */
  312 static struct in6_msource *
  313 im6o_match_source(const struct ip6_moptions *imo, const size_t gidx,
  314     const struct sockaddr *src)
  315 {
  316         struct ip6_msource       find;
  317         struct in6_mfilter      *imf;
  318         struct ip6_msource      *ims;
  319         const sockunion_t       *psa;
  320 
  321         KASSERT(src->sa_family == AF_INET6, ("%s: !AF_INET6", __func__));
  322         KASSERT(gidx != -1 && gidx < imo->im6o_num_memberships,
  323             ("%s: invalid index %d\n", __func__, (int)gidx));
  324 
  325         /* The im6o_mfilters array may be lazy allocated. */
  326         if (imo->im6o_mfilters == NULL)
  327                 return (NULL);
  328         imf = &imo->im6o_mfilters[gidx];
  329 
  330         psa = (const sockunion_t *)src;
  331         find.im6s_addr = psa->sin6.sin6_addr;
  332         in6_clearscope(&find.im6s_addr);                /* XXX */
  333         ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
  334 
  335         return ((struct in6_msource *)ims);
  336 }
  337 
  338 /*
  339  * Perform filtering for multicast datagrams on a socket by group and source.
  340  *
  341  * Returns 0 if a datagram should be allowed through, or various error codes
  342  * if the socket was not a member of the group, or the source was muted, etc.
  343  */
  344 int
  345 im6o_mc_filter(const struct ip6_moptions *imo, const struct ifnet *ifp,
  346     const struct sockaddr *group, const struct sockaddr *src)
  347 {
  348         size_t gidx;
  349         struct in6_msource *ims;
  350         int mode;
  351 
  352         KASSERT(ifp != NULL, ("%s: null ifp", __func__));
  353 
  354         gidx = im6o_match_group(imo, ifp, group);
  355         if (gidx == -1)
  356                 return (MCAST_NOTGMEMBER);
  357 
  358         /*
  359          * Check if the source was included in an (S,G) join.
  360          * Allow reception on exclusive memberships by default,
  361          * reject reception on inclusive memberships by default.
  362          * Exclude source only if an in-mode exclude filter exists.
  363          * Include source only if an in-mode include filter exists.
  364          * NOTE: We are comparing group state here at MLD t1 (now)
  365          * with socket-layer t0 (since last downcall).
  366          */
  367         mode = imo->im6o_mfilters[gidx].im6f_st[1];
  368         ims = im6o_match_source(imo, gidx, src);
  369 
  370         if ((ims == NULL && mode == MCAST_INCLUDE) ||
  371             (ims != NULL && ims->im6sl_st[0] != mode))
  372                 return (MCAST_NOTSMEMBER);
  373 
  374         return (MCAST_PASS);
  375 }
  376 
  377 /*
  378  * Find and return a reference to an in6_multi record for (ifp, group),
  379  * and bump its reference count.
  380  * If one does not exist, try to allocate it, and update link-layer multicast
  381  * filters on ifp to listen for group.
  382  * Assumes the IN6_MULTI lock is held across the call.
  383  * Return 0 if successful, otherwise return an appropriate error code.
  384  */
  385 static int
  386 in6_mc_get(struct ifnet *ifp, const struct in6_addr *group,
  387     struct in6_multi **pinm)
  388 {
  389         struct sockaddr_in6      gsin6;
  390         struct ifmultiaddr      *ifma;
  391         struct in6_multi        *inm;
  392         int                      error;
  393 
  394         error = 0;
  395 
  396         /*
  397          * XXX: Accesses to ifma_protospec must be covered by IF_ADDR_LOCK;
  398          * if_addmulti() takes this mutex itself, so we must drop and
  399          * re-acquire around the call.
  400          */
  401         IN6_MULTI_LOCK_ASSERT();
  402         IF_ADDR_WLOCK(ifp);
  403 
  404         inm = in6m_lookup_locked(ifp, group);
  405         if (inm != NULL) {
  406                 /*
  407                  * If we already joined this group, just bump the
  408                  * refcount and return it.
  409                  */
  410                 KASSERT(inm->in6m_refcount >= 1,
  411                     ("%s: bad refcount %d", __func__, inm->in6m_refcount));
  412                 ++inm->in6m_refcount;
  413                 *pinm = inm;
  414                 goto out_locked;
  415         }
  416 
  417         memset(&gsin6, 0, sizeof(gsin6));
  418         gsin6.sin6_family = AF_INET6;
  419         gsin6.sin6_len = sizeof(struct sockaddr_in6);
  420         gsin6.sin6_addr = *group;
  421 
  422         /*
  423          * Check if a link-layer group is already associated
  424          * with this network-layer group on the given ifnet.
  425          */
  426         IF_ADDR_WUNLOCK(ifp);
  427         error = if_addmulti(ifp, (struct sockaddr *)&gsin6, &ifma);
  428         if (error != 0)
  429                 return (error);
  430         IF_ADDR_WLOCK(ifp);
  431 
  432         /*
  433          * If something other than netinet6 is occupying the link-layer
  434          * group, print a meaningful error message and back out of
  435          * the allocation.
  436          * Otherwise, bump the refcount on the existing network-layer
  437          * group association and return it.
  438          */
  439         if (ifma->ifma_protospec != NULL) {
  440                 inm = (struct in6_multi *)ifma->ifma_protospec;
  441 #ifdef INVARIANTS
  442                 KASSERT(ifma->ifma_addr != NULL, ("%s: no ifma_addr",
  443                     __func__));
  444                 KASSERT(ifma->ifma_addr->sa_family == AF_INET6,
  445                     ("%s: ifma not AF_INET6", __func__));
  446                 KASSERT(inm != NULL, ("%s: no ifma_protospec", __func__));
  447                 if (inm->in6m_ifma != ifma || inm->in6m_ifp != ifp ||
  448                     !IN6_ARE_ADDR_EQUAL(&inm->in6m_addr, group))
  449                         panic("%s: ifma %p is inconsistent with %p (%p)",
  450                             __func__, ifma, inm, group);
  451 #endif
  452                 ++inm->in6m_refcount;
  453                 *pinm = inm;
  454                 goto out_locked;
  455         }
  456 
  457         IF_ADDR_WLOCK_ASSERT(ifp);
  458 
  459         /*
  460          * A new in6_multi record is needed; allocate and initialize it.
  461          * We DO NOT perform an MLD join as the in6_ layer may need to
  462          * push an initial source list down to MLD to support SSM.
  463          *
  464          * The initial source filter state is INCLUDE, {} as per the RFC.
  465          * Pending state-changes per group are subject to a bounds check.
  466          */
  467         inm = malloc(sizeof(*inm), M_IP6MADDR, M_NOWAIT | M_ZERO);
  468         if (inm == NULL) {
  469                 if_delmulti_ifma(ifma);
  470                 error = ENOMEM;
  471                 goto out_locked;
  472         }
  473         inm->in6m_addr = *group;
  474         inm->in6m_ifp = ifp;
  475         inm->in6m_mli = MLD_IFINFO(ifp);
  476         inm->in6m_ifma = ifma;
  477         inm->in6m_refcount = 1;
  478         inm->in6m_state = MLD_NOT_MEMBER;
  479         IFQ_SET_MAXLEN(&inm->in6m_scq, MLD_MAX_STATE_CHANGES);
  480 
  481         inm->in6m_st[0].iss_fmode = MCAST_UNDEFINED;
  482         inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
  483         RB_INIT(&inm->in6m_srcs);
  484 
  485         ifma->ifma_protospec = inm;
  486         *pinm = inm;
  487 
  488 out_locked:
  489         IF_ADDR_WUNLOCK(ifp);
  490         return (error);
  491 }
  492 
  493 /*
  494  * Drop a reference to an in6_multi record.
  495  *
  496  * If the refcount drops to 0, free the in6_multi record and
  497  * delete the underlying link-layer membership.
  498  */
  499 void
  500 in6m_release_locked(struct in6_multi *inm)
  501 {
  502         struct ifmultiaddr *ifma;
  503 
  504         IN6_MULTI_LOCK_ASSERT();
  505 
  506         CTR2(KTR_MLD, "%s: refcount is %d", __func__, inm->in6m_refcount);
  507 
  508         if (--inm->in6m_refcount > 0) {
  509                 CTR2(KTR_MLD, "%s: refcount is now %d", __func__,
  510                     inm->in6m_refcount);
  511                 return;
  512         }
  513 
  514         CTR2(KTR_MLD, "%s: freeing inm %p", __func__, inm);
  515 
  516         ifma = inm->in6m_ifma;
  517 
  518         /* XXX this access is not covered by IF_ADDR_LOCK */
  519         CTR2(KTR_MLD, "%s: purging ifma %p", __func__, ifma);
  520         KASSERT(ifma->ifma_protospec == inm,
  521             ("%s: ifma_protospec != inm", __func__));
  522         ifma->ifma_protospec = NULL;
  523 
  524         in6m_purge(inm);
  525 
  526         free(inm, M_IP6MADDR);
  527 
  528         if_delmulti_ifma(ifma);
  529 }
  530 
  531 /*
  532  * Clear recorded source entries for a group.
  533  * Used by the MLD code. Caller must hold the IN6_MULTI lock.
  534  * FIXME: Should reap.
  535  */
  536 void
  537 in6m_clear_recorded(struct in6_multi *inm)
  538 {
  539         struct ip6_msource      *ims;
  540 
  541         IN6_MULTI_LOCK_ASSERT();
  542 
  543         RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
  544                 if (ims->im6s_stp) {
  545                         ims->im6s_stp = 0;
  546                         --inm->in6m_st[1].iss_rec;
  547                 }
  548         }
  549         KASSERT(inm->in6m_st[1].iss_rec == 0,
  550             ("%s: iss_rec %d not 0", __func__, inm->in6m_st[1].iss_rec));
  551 }
  552 
  553 /*
  554  * Record a source as pending for a Source-Group MLDv2 query.
  555  * This lives here as it modifies the shared tree.
  556  *
  557  * inm is the group descriptor.
  558  * naddr is the address of the source to record in network-byte order.
  559  *
  560  * If the net.inet6.mld.sgalloc sysctl is non-zero, we will
  561  * lazy-allocate a source node in response to an SG query.
  562  * Otherwise, no allocation is performed. This saves some memory
  563  * with the trade-off that the source will not be reported to the
  564  * router if joined in the window between the query response and
  565  * the group actually being joined on the local host.
  566  *
  567  * VIMAGE: XXX: Currently the mld_sgalloc feature has been removed.
  568  * This turns off the allocation of a recorded source entry if
  569  * the group has not been joined.
  570  *
  571  * Return 0 if the source didn't exist or was already marked as recorded.
  572  * Return 1 if the source was marked as recorded by this function.
  573  * Return <0 if any error occured (negated errno code).
  574  */
  575 int
  576 in6m_record_source(struct in6_multi *inm, const struct in6_addr *addr)
  577 {
  578         struct ip6_msource       find;
  579         struct ip6_msource      *ims, *nims;
  580 
  581         IN6_MULTI_LOCK_ASSERT();
  582 
  583         find.im6s_addr = *addr;
  584         ims = RB_FIND(ip6_msource_tree, &inm->in6m_srcs, &find);
  585         if (ims && ims->im6s_stp)
  586                 return (0);
  587         if (ims == NULL) {
  588                 if (inm->in6m_nsrc == in6_mcast_maxgrpsrc)
  589                         return (-ENOSPC);
  590                 nims = malloc(sizeof(struct ip6_msource), M_IP6MSOURCE,
  591                     M_NOWAIT | M_ZERO);
  592                 if (nims == NULL)
  593                         return (-ENOMEM);
  594                 nims->im6s_addr = find.im6s_addr;
  595                 RB_INSERT(ip6_msource_tree, &inm->in6m_srcs, nims);
  596                 ++inm->in6m_nsrc;
  597                 ims = nims;
  598         }
  599 
  600         /*
  601          * Mark the source as recorded and update the recorded
  602          * source count.
  603          */
  604         ++ims->im6s_stp;
  605         ++inm->in6m_st[1].iss_rec;
  606 
  607         return (1);
  608 }
  609 
  610 /*
  611  * Return a pointer to an in6_msource owned by an in6_mfilter,
  612  * given its source address.
  613  * Lazy-allocate if needed. If this is a new entry its filter state is
  614  * undefined at t0.
  615  *
  616  * imf is the filter set being modified.
  617  * addr is the source address.
  618  *
  619  * SMPng: May be called with locks held; malloc must not block.
  620  */
  621 static int
  622 im6f_get_source(struct in6_mfilter *imf, const struct sockaddr_in6 *psin,
  623     struct in6_msource **plims)
  624 {
  625         struct ip6_msource       find;
  626         struct ip6_msource      *ims, *nims;
  627         struct in6_msource      *lims;
  628         int                      error;
  629 
  630         error = 0;
  631         ims = NULL;
  632         lims = NULL;
  633 
  634         find.im6s_addr = psin->sin6_addr;
  635         ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
  636         lims = (struct in6_msource *)ims;
  637         if (lims == NULL) {
  638                 if (imf->im6f_nsrc == in6_mcast_maxsocksrc)
  639                         return (ENOSPC);
  640                 nims = malloc(sizeof(struct in6_msource), M_IN6MFILTER,
  641                     M_NOWAIT | M_ZERO);
  642                 if (nims == NULL)
  643                         return (ENOMEM);
  644                 lims = (struct in6_msource *)nims;
  645                 lims->im6s_addr = find.im6s_addr;
  646                 lims->im6sl_st[0] = MCAST_UNDEFINED;
  647                 RB_INSERT(ip6_msource_tree, &imf->im6f_sources, nims);
  648                 ++imf->im6f_nsrc;
  649         }
  650 
  651         *plims = lims;
  652 
  653         return (error);
  654 }
  655 
  656 /*
  657  * Graft a source entry into an existing socket-layer filter set,
  658  * maintaining any required invariants and checking allocations.
  659  *
  660  * The source is marked as being in the new filter mode at t1.
  661  *
  662  * Return the pointer to the new node, otherwise return NULL.
  663  */
  664 static struct in6_msource *
  665 im6f_graft(struct in6_mfilter *imf, const uint8_t st1,
  666     const struct sockaddr_in6 *psin)
  667 {
  668         struct ip6_msource      *nims;
  669         struct in6_msource      *lims;
  670 
  671         nims = malloc(sizeof(struct in6_msource), M_IN6MFILTER,
  672             M_NOWAIT | M_ZERO);
  673         if (nims == NULL)
  674                 return (NULL);
  675         lims = (struct in6_msource *)nims;
  676         lims->im6s_addr = psin->sin6_addr;
  677         lims->im6sl_st[0] = MCAST_UNDEFINED;
  678         lims->im6sl_st[1] = st1;
  679         RB_INSERT(ip6_msource_tree, &imf->im6f_sources, nims);
  680         ++imf->im6f_nsrc;
  681 
  682         return (lims);
  683 }
  684 
  685 /*
  686  * Prune a source entry from an existing socket-layer filter set,
  687  * maintaining any required invariants and checking allocations.
  688  *
  689  * The source is marked as being left at t1, it is not freed.
  690  *
  691  * Return 0 if no error occurred, otherwise return an errno value.
  692  */
  693 static int
  694 im6f_prune(struct in6_mfilter *imf, const struct sockaddr_in6 *psin)
  695 {
  696         struct ip6_msource       find;
  697         struct ip6_msource      *ims;
  698         struct in6_msource      *lims;
  699 
  700         find.im6s_addr = psin->sin6_addr;
  701         ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
  702         if (ims == NULL)
  703                 return (ENOENT);
  704         lims = (struct in6_msource *)ims;
  705         lims->im6sl_st[1] = MCAST_UNDEFINED;
  706         return (0);
  707 }
  708 
  709 /*
  710  * Revert socket-layer filter set deltas at t1 to t0 state.
  711  */
  712 static void
  713 im6f_rollback(struct in6_mfilter *imf)
  714 {
  715         struct ip6_msource      *ims, *tims;
  716         struct in6_msource      *lims;
  717 
  718         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
  719                 lims = (struct in6_msource *)ims;
  720                 if (lims->im6sl_st[0] == lims->im6sl_st[1]) {
  721                         /* no change at t1 */
  722                         continue;
  723                 } else if (lims->im6sl_st[0] != MCAST_UNDEFINED) {
  724                         /* revert change to existing source at t1 */
  725                         lims->im6sl_st[1] = lims->im6sl_st[0];
  726                 } else {
  727                         /* revert source added t1 */
  728                         CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
  729                         RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
  730                         free(ims, M_IN6MFILTER);
  731                         imf->im6f_nsrc--;
  732                 }
  733         }
  734         imf->im6f_st[1] = imf->im6f_st[0];
  735 }
  736 
  737 /*
  738  * Mark socket-layer filter set as INCLUDE {} at t1.
  739  */
  740 static void
  741 im6f_leave(struct in6_mfilter *imf)
  742 {
  743         struct ip6_msource      *ims;
  744         struct in6_msource      *lims;
  745 
  746         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
  747                 lims = (struct in6_msource *)ims;
  748                 lims->im6sl_st[1] = MCAST_UNDEFINED;
  749         }
  750         imf->im6f_st[1] = MCAST_INCLUDE;
  751 }
  752 
  753 /*
  754  * Mark socket-layer filter set deltas as committed.
  755  */
  756 static void
  757 im6f_commit(struct in6_mfilter *imf)
  758 {
  759         struct ip6_msource      *ims;
  760         struct in6_msource      *lims;
  761 
  762         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
  763                 lims = (struct in6_msource *)ims;
  764                 lims->im6sl_st[0] = lims->im6sl_st[1];
  765         }
  766         imf->im6f_st[0] = imf->im6f_st[1];
  767 }
  768 
  769 /*
  770  * Reap unreferenced sources from socket-layer filter set.
  771  */
  772 static void
  773 im6f_reap(struct in6_mfilter *imf)
  774 {
  775         struct ip6_msource      *ims, *tims;
  776         struct in6_msource      *lims;
  777 
  778         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
  779                 lims = (struct in6_msource *)ims;
  780                 if ((lims->im6sl_st[0] == MCAST_UNDEFINED) &&
  781                     (lims->im6sl_st[1] == MCAST_UNDEFINED)) {
  782                         CTR2(KTR_MLD, "%s: free lims %p", __func__, ims);
  783                         RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
  784                         free(ims, M_IN6MFILTER);
  785                         imf->im6f_nsrc--;
  786                 }
  787         }
  788 }
  789 
  790 /*
  791  * Purge socket-layer filter set.
  792  */
  793 static void
  794 im6f_purge(struct in6_mfilter *imf)
  795 {
  796         struct ip6_msource      *ims, *tims;
  797 
  798         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
  799                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
  800                 RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
  801                 free(ims, M_IN6MFILTER);
  802                 imf->im6f_nsrc--;
  803         }
  804         imf->im6f_st[0] = imf->im6f_st[1] = MCAST_UNDEFINED;
  805         KASSERT(RB_EMPTY(&imf->im6f_sources),
  806             ("%s: im6f_sources not empty", __func__));
  807 }
  808 
  809 /*
  810  * Look up a source filter entry for a multicast group.
  811  *
  812  * inm is the group descriptor to work with.
  813  * addr is the IPv6 address to look up.
  814  * noalloc may be non-zero to suppress allocation of sources.
  815  * *pims will be set to the address of the retrieved or allocated source.
  816  *
  817  * SMPng: NOTE: may be called with locks held.
  818  * Return 0 if successful, otherwise return a non-zero error code.
  819  */
  820 static int
  821 in6m_get_source(struct in6_multi *inm, const struct in6_addr *addr,
  822     const int noalloc, struct ip6_msource **pims)
  823 {
  824         struct ip6_msource       find;
  825         struct ip6_msource      *ims, *nims;
  826 #ifdef KTR
  827         char                     ip6tbuf[INET6_ADDRSTRLEN];
  828 #endif
  829 
  830         find.im6s_addr = *addr;
  831         ims = RB_FIND(ip6_msource_tree, &inm->in6m_srcs, &find);
  832         if (ims == NULL && !noalloc) {
  833                 if (inm->in6m_nsrc == in6_mcast_maxgrpsrc)
  834                         return (ENOSPC);
  835                 nims = malloc(sizeof(struct ip6_msource), M_IP6MSOURCE,
  836                     M_NOWAIT | M_ZERO);
  837                 if (nims == NULL)
  838                         return (ENOMEM);
  839                 nims->im6s_addr = *addr;
  840                 RB_INSERT(ip6_msource_tree, &inm->in6m_srcs, nims);
  841                 ++inm->in6m_nsrc;
  842                 ims = nims;
  843                 CTR3(KTR_MLD, "%s: allocated %s as %p", __func__,
  844                     ip6_sprintf(ip6tbuf, addr), ims);
  845         }
  846 
  847         *pims = ims;
  848         return (0);
  849 }
  850 
  851 /*
  852  * Merge socket-layer source into MLD-layer source.
  853  * If rollback is non-zero, perform the inverse of the merge.
  854  */
  855 static void
  856 im6s_merge(struct ip6_msource *ims, const struct in6_msource *lims,
  857     const int rollback)
  858 {
  859         int n = rollback ? -1 : 1;
  860 #ifdef KTR
  861         char ip6tbuf[INET6_ADDRSTRLEN];
  862 
  863         ip6_sprintf(ip6tbuf, &lims->im6s_addr);
  864 #endif
  865 
  866         if (lims->im6sl_st[0] == MCAST_EXCLUDE) {
  867                 CTR3(KTR_MLD, "%s: t1 ex -= %d on %s", __func__, n, ip6tbuf);
  868                 ims->im6s_st[1].ex -= n;
  869         } else if (lims->im6sl_st[0] == MCAST_INCLUDE) {
  870                 CTR3(KTR_MLD, "%s: t1 in -= %d on %s", __func__, n, ip6tbuf);
  871                 ims->im6s_st[1].in -= n;
  872         }
  873 
  874         if (lims->im6sl_st[1] == MCAST_EXCLUDE) {
  875                 CTR3(KTR_MLD, "%s: t1 ex += %d on %s", __func__, n, ip6tbuf);
  876                 ims->im6s_st[1].ex += n;
  877         } else if (lims->im6sl_st[1] == MCAST_INCLUDE) {
  878                 CTR3(KTR_MLD, "%s: t1 in += %d on %s", __func__, n, ip6tbuf);
  879                 ims->im6s_st[1].in += n;
  880         }
  881 }
  882 
  883 /*
  884  * Atomically update the global in6_multi state, when a membership's
  885  * filter list is being updated in any way.
  886  *
  887  * imf is the per-inpcb-membership group filter pointer.
  888  * A fake imf may be passed for in-kernel consumers.
  889  *
  890  * XXX This is a candidate for a set-symmetric-difference style loop
  891  * which would eliminate the repeated lookup from root of ims nodes,
  892  * as they share the same key space.
  893  *
  894  * If any error occurred this function will back out of refcounts
  895  * and return a non-zero value.
  896  */
  897 static int
  898 in6m_merge(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
  899 {
  900         struct ip6_msource      *ims, *nims;
  901         struct in6_msource      *lims;
  902         int                      schanged, error;
  903         int                      nsrc0, nsrc1;
  904 
  905         schanged = 0;
  906         error = 0;
  907         nsrc1 = nsrc0 = 0;
  908 
  909         /*
  910          * Update the source filters first, as this may fail.
  911          * Maintain count of in-mode filters at t0, t1. These are
  912          * used to work out if we transition into ASM mode or not.
  913          * Maintain a count of source filters whose state was
  914          * actually modified by this operation.
  915          */
  916         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
  917                 lims = (struct in6_msource *)ims;
  918                 if (lims->im6sl_st[0] == imf->im6f_st[0]) nsrc0++;
  919                 if (lims->im6sl_st[1] == imf->im6f_st[1]) nsrc1++;
  920                 if (lims->im6sl_st[0] == lims->im6sl_st[1]) continue;
  921                 error = in6m_get_source(inm, &lims->im6s_addr, 0, &nims);
  922                 ++schanged;
  923                 if (error)
  924                         break;
  925                 im6s_merge(nims, lims, 0);
  926         }
  927         if (error) {
  928                 struct ip6_msource *bims;
  929 
  930                 RB_FOREACH_REVERSE_FROM(ims, ip6_msource_tree, nims) {
  931                         lims = (struct in6_msource *)ims;
  932                         if (lims->im6sl_st[0] == lims->im6sl_st[1])
  933                                 continue;
  934                         (void)in6m_get_source(inm, &lims->im6s_addr, 1, &bims);
  935                         if (bims == NULL)
  936                                 continue;
  937                         im6s_merge(bims, lims, 1);
  938                 }
  939                 goto out_reap;
  940         }
  941 
  942         CTR3(KTR_MLD, "%s: imf filters in-mode: %d at t0, %d at t1",
  943             __func__, nsrc0, nsrc1);
  944 
  945         /* Handle transition between INCLUDE {n} and INCLUDE {} on socket. */
  946         if (imf->im6f_st[0] == imf->im6f_st[1] &&
  947             imf->im6f_st[1] == MCAST_INCLUDE) {
  948                 if (nsrc1 == 0) {
  949                         CTR1(KTR_MLD, "%s: --in on inm at t1", __func__);
  950                         --inm->in6m_st[1].iss_in;
  951                 }
  952         }
  953 
  954         /* Handle filter mode transition on socket. */
  955         if (imf->im6f_st[0] != imf->im6f_st[1]) {
  956                 CTR3(KTR_MLD, "%s: imf transition %d to %d",
  957                     __func__, imf->im6f_st[0], imf->im6f_st[1]);
  958 
  959                 if (imf->im6f_st[0] == MCAST_EXCLUDE) {
  960                         CTR1(KTR_MLD, "%s: --ex on inm at t1", __func__);
  961                         --inm->in6m_st[1].iss_ex;
  962                 } else if (imf->im6f_st[0] == MCAST_INCLUDE) {
  963                         CTR1(KTR_MLD, "%s: --in on inm at t1", __func__);
  964                         --inm->in6m_st[1].iss_in;
  965                 }
  966 
  967                 if (imf->im6f_st[1] == MCAST_EXCLUDE) {
  968                         CTR1(KTR_MLD, "%s: ex++ on inm at t1", __func__);
  969                         inm->in6m_st[1].iss_ex++;
  970                 } else if (imf->im6f_st[1] == MCAST_INCLUDE && nsrc1 > 0) {
  971                         CTR1(KTR_MLD, "%s: in++ on inm at t1", __func__);
  972                         inm->in6m_st[1].iss_in++;
  973                 }
  974         }
  975 
  976         /*
  977          * Track inm filter state in terms of listener counts.
  978          * If there are any exclusive listeners, stack-wide
  979          * membership is exclusive.
  980          * Otherwise, if only inclusive listeners, stack-wide is inclusive.
  981          * If no listeners remain, state is undefined at t1,
  982          * and the MLD lifecycle for this group should finish.
  983          */
  984         if (inm->in6m_st[1].iss_ex > 0) {
  985                 CTR1(KTR_MLD, "%s: transition to EX", __func__);
  986                 inm->in6m_st[1].iss_fmode = MCAST_EXCLUDE;
  987         } else if (inm->in6m_st[1].iss_in > 0) {
  988                 CTR1(KTR_MLD, "%s: transition to IN", __func__);
  989                 inm->in6m_st[1].iss_fmode = MCAST_INCLUDE;
  990         } else {
  991                 CTR1(KTR_MLD, "%s: transition to UNDEF", __func__);
  992                 inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
  993         }
  994 
  995         /* Decrement ASM listener count on transition out of ASM mode. */
  996         if (imf->im6f_st[0] == MCAST_EXCLUDE && nsrc0 == 0) {
  997                 if ((imf->im6f_st[1] != MCAST_EXCLUDE) ||
  998                     (imf->im6f_st[1] == MCAST_EXCLUDE && nsrc1 > 0))
  999                         CTR1(KTR_MLD, "%s: --asm on inm at t1", __func__);
 1000                         --inm->in6m_st[1].iss_asm;
 1001         }
 1002 
 1003         /* Increment ASM listener count on transition to ASM mode. */
 1004         if (imf->im6f_st[1] == MCAST_EXCLUDE && nsrc1 == 0) {
 1005                 CTR1(KTR_MLD, "%s: asm++ on inm at t1", __func__);
 1006                 inm->in6m_st[1].iss_asm++;
 1007         }
 1008 
 1009         CTR3(KTR_MLD, "%s: merged imf %p to inm %p", __func__, imf, inm);
 1010         in6m_print(inm);
 1011 
 1012 out_reap:
 1013         if (schanged > 0) {
 1014                 CTR1(KTR_MLD, "%s: sources changed; reaping", __func__);
 1015                 in6m_reap(inm);
 1016         }
 1017         return (error);
 1018 }
 1019 
 1020 /*
 1021  * Mark an in6_multi's filter set deltas as committed.
 1022  * Called by MLD after a state change has been enqueued.
 1023  */
 1024 void
 1025 in6m_commit(struct in6_multi *inm)
 1026 {
 1027         struct ip6_msource      *ims;
 1028 
 1029         CTR2(KTR_MLD, "%s: commit inm %p", __func__, inm);
 1030         CTR1(KTR_MLD, "%s: pre commit:", __func__);
 1031         in6m_print(inm);
 1032 
 1033         RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
 1034                 ims->im6s_st[0] = ims->im6s_st[1];
 1035         }
 1036         inm->in6m_st[0] = inm->in6m_st[1];
 1037 }
 1038 
 1039 /*
 1040  * Reap unreferenced nodes from an in6_multi's filter set.
 1041  */
 1042 static void
 1043 in6m_reap(struct in6_multi *inm)
 1044 {
 1045         struct ip6_msource      *ims, *tims;
 1046 
 1047         RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs, tims) {
 1048                 if (ims->im6s_st[0].ex > 0 || ims->im6s_st[0].in > 0 ||
 1049                     ims->im6s_st[1].ex > 0 || ims->im6s_st[1].in > 0 ||
 1050                     ims->im6s_stp != 0)
 1051                         continue;
 1052                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
 1053                 RB_REMOVE(ip6_msource_tree, &inm->in6m_srcs, ims);
 1054                 free(ims, M_IP6MSOURCE);
 1055                 inm->in6m_nsrc--;
 1056         }
 1057 }
 1058 
 1059 /*
 1060  * Purge all source nodes from an in6_multi's filter set.
 1061  */
 1062 static void
 1063 in6m_purge(struct in6_multi *inm)
 1064 {
 1065         struct ip6_msource      *ims, *tims;
 1066 
 1067         RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs, tims) {
 1068                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
 1069                 RB_REMOVE(ip6_msource_tree, &inm->in6m_srcs, ims);
 1070                 free(ims, M_IP6MSOURCE);
 1071                 inm->in6m_nsrc--;
 1072         }
 1073 }
 1074 
 1075 /*
 1076  * Join a multicast address w/o sources.
 1077  * KAME compatibility entry point.
 1078  *
 1079  * SMPng: Assume no mc locks held by caller.
 1080  */
 1081 struct in6_multi_mship *
 1082 in6_joingroup(struct ifnet *ifp, struct in6_addr *mcaddr,
 1083     int *errorp, int delay)
 1084 {
 1085         struct in6_multi_mship *imm;
 1086         int error;
 1087 
 1088         imm = malloc(sizeof(*imm), M_IP6MADDR, M_NOWAIT);
 1089         if (imm == NULL) {
 1090                 *errorp = ENOBUFS;
 1091                 return (NULL);
 1092         }
 1093 
 1094         delay = (delay * PR_FASTHZ) / hz;
 1095 
 1096         error = in6_mc_join(ifp, mcaddr, NULL, &imm->i6mm_maddr, delay);
 1097         if (error) {
 1098                 *errorp = error;
 1099                 free(imm, M_IP6MADDR);
 1100                 return (NULL);
 1101         }
 1102 
 1103         return (imm);
 1104 }
 1105 
 1106 /*
 1107  * Leave a multicast address w/o sources.
 1108  * KAME compatibility entry point.
 1109  *
 1110  * SMPng: Assume no mc locks held by caller.
 1111  */
 1112 int
 1113 in6_leavegroup(struct in6_multi_mship *imm)
 1114 {
 1115 
 1116         if (imm->i6mm_maddr != NULL)
 1117                 in6_mc_leave(imm->i6mm_maddr, NULL);
 1118         free(imm,  M_IP6MADDR);
 1119         return 0;
 1120 }
 1121 
 1122 /*
 1123  * Join a multicast group; unlocked entry point.
 1124  *
 1125  * SMPng: XXX: in6_mc_join() is called from in6_control() when upper
 1126  * locks are not held. Fortunately, ifp is unlikely to have been detached
 1127  * at this point, so we assume it's OK to recurse.
 1128  */
 1129 int
 1130 in6_mc_join(struct ifnet *ifp, const struct in6_addr *mcaddr,
 1131     /*const*/ struct in6_mfilter *imf, struct in6_multi **pinm,
 1132     const int delay)
 1133 {
 1134         int error;
 1135 
 1136         IN6_MULTI_LOCK();
 1137         error = in6_mc_join_locked(ifp, mcaddr, imf, pinm, delay);
 1138         IN6_MULTI_UNLOCK();
 1139 
 1140         return (error);
 1141 }
 1142 
 1143 /*
 1144  * Join a multicast group; real entry point.
 1145  *
 1146  * Only preserves atomicity at inm level.
 1147  * NOTE: imf argument cannot be const due to sys/tree.h limitations.
 1148  *
 1149  * If the MLD downcall fails, the group is not joined, and an error
 1150  * code is returned.
 1151  */
 1152 int
 1153 in6_mc_join_locked(struct ifnet *ifp, const struct in6_addr *mcaddr,
 1154     /*const*/ struct in6_mfilter *imf, struct in6_multi **pinm,
 1155     const int delay)
 1156 {
 1157         struct in6_mfilter       timf;
 1158         struct in6_multi        *inm;
 1159         int                      error;
 1160 #ifdef KTR
 1161         char                     ip6tbuf[INET6_ADDRSTRLEN];
 1162 #endif
 1163 
 1164 #ifdef INVARIANTS
 1165         /*
 1166          * Sanity: Check scope zone ID was set for ifp, if and
 1167          * only if group is scoped to an interface.
 1168          */
 1169         KASSERT(IN6_IS_ADDR_MULTICAST(mcaddr),
 1170             ("%s: not a multicast address", __func__));
 1171         if (IN6_IS_ADDR_MC_LINKLOCAL(mcaddr) ||
 1172             IN6_IS_ADDR_MC_INTFACELOCAL(mcaddr)) {
 1173                 KASSERT(mcaddr->s6_addr16[1] != 0,
 1174                     ("%s: scope zone ID not set", __func__));
 1175         }
 1176 #endif
 1177 
 1178         IN6_MULTI_LOCK_ASSERT();
 1179 
 1180         CTR4(KTR_MLD, "%s: join %s on %p(%s))", __func__,
 1181             ip6_sprintf(ip6tbuf, mcaddr), ifp, ifp->if_xname);
 1182 
 1183         error = 0;
 1184         inm = NULL;
 1185 
 1186         /*
 1187          * If no imf was specified (i.e. kernel consumer),
 1188          * fake one up and assume it is an ASM join.
 1189          */
 1190         if (imf == NULL) {
 1191                 im6f_init(&timf, MCAST_UNDEFINED, MCAST_EXCLUDE);
 1192                 imf = &timf;
 1193         }
 1194 
 1195         error = in6_mc_get(ifp, mcaddr, &inm);
 1196         if (error) {
 1197                 CTR1(KTR_MLD, "%s: in6_mc_get() failure", __func__);
 1198                 return (error);
 1199         }
 1200 
 1201         CTR1(KTR_MLD, "%s: merge inm state", __func__);
 1202         error = in6m_merge(inm, imf);
 1203         if (error) {
 1204                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
 1205                 goto out_in6m_release;
 1206         }
 1207 
 1208         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
 1209         error = mld_change_state(inm, delay);
 1210         if (error) {
 1211                 CTR1(KTR_MLD, "%s: failed to update source", __func__);
 1212                 goto out_in6m_release;
 1213         }
 1214 
 1215 out_in6m_release:
 1216         if (error) {
 1217                 CTR2(KTR_MLD, "%s: dropping ref on %p", __func__, inm);
 1218                 in6m_release_locked(inm);
 1219         } else {
 1220                 *pinm = inm;
 1221         }
 1222 
 1223         return (error);
 1224 }
 1225 
 1226 /*
 1227  * Leave a multicast group; unlocked entry point.
 1228  */
 1229 int
 1230 in6_mc_leave(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
 1231 {
 1232         struct ifnet *ifp;
 1233         int error;
 1234 
 1235         ifp = inm->in6m_ifp;
 1236 
 1237         IN6_MULTI_LOCK();
 1238         error = in6_mc_leave_locked(inm, imf);
 1239         IN6_MULTI_UNLOCK();
 1240 
 1241         return (error);
 1242 }
 1243 
 1244 /*
 1245  * Leave a multicast group; real entry point.
 1246  * All source filters will be expunged.
 1247  *
 1248  * Only preserves atomicity at inm level.
 1249  *
 1250  * Holding the write lock for the INP which contains imf
 1251  * is highly advisable. We can't assert for it as imf does not
 1252  * contain a back-pointer to the owning inp.
 1253  *
 1254  * Note: This is not the same as in6m_release(*) as this function also
 1255  * makes a state change downcall into MLD.
 1256  */
 1257 int
 1258 in6_mc_leave_locked(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
 1259 {
 1260         struct in6_mfilter       timf;
 1261         int                      error;
 1262 #ifdef KTR
 1263         char                     ip6tbuf[INET6_ADDRSTRLEN];
 1264 #endif
 1265 
 1266         error = 0;
 1267 
 1268         IN6_MULTI_LOCK_ASSERT();
 1269 
 1270         CTR5(KTR_MLD, "%s: leave inm %p, %s/%s, imf %p", __func__,
 1271             inm, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
 1272             (in6m_is_ifp_detached(inm) ? "null" : inm->in6m_ifp->if_xname),
 1273             imf);
 1274 
 1275         /*
 1276          * If no imf was specified (i.e. kernel consumer),
 1277          * fake one up and assume it is an ASM join.
 1278          */
 1279         if (imf == NULL) {
 1280                 im6f_init(&timf, MCAST_EXCLUDE, MCAST_UNDEFINED);
 1281                 imf = &timf;
 1282         }
 1283 
 1284         /*
 1285          * Begin state merge transaction at MLD layer.
 1286          *
 1287          * As this particular invocation should not cause any memory
 1288          * to be allocated, and there is no opportunity to roll back
 1289          * the transaction, it MUST NOT fail.
 1290          */
 1291         CTR1(KTR_MLD, "%s: merge inm state", __func__);
 1292         error = in6m_merge(inm, imf);
 1293         KASSERT(error == 0, ("%s: failed to merge inm state", __func__));
 1294 
 1295         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
 1296         error = mld_change_state(inm, 0);
 1297         if (error)
 1298                 CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
 1299 
 1300         CTR2(KTR_MLD, "%s: dropping ref on %p", __func__, inm);
 1301         in6m_release_locked(inm);
 1302 
 1303         return (error);
 1304 }
 1305 
 1306 /*
 1307  * Block or unblock an ASM multicast source on an inpcb.
 1308  * This implements the delta-based API described in RFC 3678.
 1309  *
 1310  * The delta-based API applies only to exclusive-mode memberships.
 1311  * An MLD downcall will be performed.
 1312  *
 1313  * SMPng: NOTE: Must take Giant as a join may create a new ifma.
 1314  *
 1315  * Return 0 if successful, otherwise return an appropriate error code.
 1316  */
 1317 static int
 1318 in6p_block_unblock_source(struct inpcb *inp, struct sockopt *sopt)
 1319 {
 1320         struct group_source_req          gsr;
 1321         sockunion_t                     *gsa, *ssa;
 1322         struct ifnet                    *ifp;
 1323         struct in6_mfilter              *imf;
 1324         struct ip6_moptions             *imo;
 1325         struct in6_msource              *ims;
 1326         struct in6_multi                        *inm;
 1327         size_t                           idx;
 1328         uint16_t                         fmode;
 1329         int                              error, doblock;
 1330 #ifdef KTR
 1331         char                             ip6tbuf[INET6_ADDRSTRLEN];
 1332 #endif
 1333 
 1334         ifp = NULL;
 1335         error = 0;
 1336         doblock = 0;
 1337 
 1338         memset(&gsr, 0, sizeof(struct group_source_req));
 1339         gsa = (sockunion_t *)&gsr.gsr_group;
 1340         ssa = (sockunion_t *)&gsr.gsr_source;
 1341 
 1342         switch (sopt->sopt_name) {
 1343         case MCAST_BLOCK_SOURCE:
 1344         case MCAST_UNBLOCK_SOURCE:
 1345                 error = sooptcopyin(sopt, &gsr,
 1346                     sizeof(struct group_source_req),
 1347                     sizeof(struct group_source_req));
 1348                 if (error)
 1349                         return (error);
 1350 
 1351                 if (gsa->sin6.sin6_family != AF_INET6 ||
 1352                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
 1353                         return (EINVAL);
 1354 
 1355                 if (ssa->sin6.sin6_family != AF_INET6 ||
 1356                     ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
 1357                         return (EINVAL);
 1358 
 1359                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
 1360                         return (EADDRNOTAVAIL);
 1361 
 1362                 ifp = ifnet_byindex(gsr.gsr_interface);
 1363 
 1364                 if (sopt->sopt_name == MCAST_BLOCK_SOURCE)
 1365                         doblock = 1;
 1366                 break;
 1367 
 1368         default:
 1369                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
 1370                     __func__, sopt->sopt_name);
 1371                 return (EOPNOTSUPP);
 1372                 break;
 1373         }
 1374 
 1375         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
 1376                 return (EINVAL);
 1377 
 1378         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
 1379 
 1380         /*
 1381          * Check if we are actually a member of this group.
 1382          */
 1383         imo = in6p_findmoptions(inp);
 1384         idx = im6o_match_group(imo, ifp, &gsa->sa);
 1385         if (idx == -1 || imo->im6o_mfilters == NULL) {
 1386                 error = EADDRNOTAVAIL;
 1387                 goto out_in6p_locked;
 1388         }
 1389 
 1390         KASSERT(imo->im6o_mfilters != NULL,
 1391             ("%s: im6o_mfilters not allocated", __func__));
 1392         imf = &imo->im6o_mfilters[idx];
 1393         inm = imo->im6o_membership[idx];
 1394 
 1395         /*
 1396          * Attempting to use the delta-based API on an
 1397          * non exclusive-mode membership is an error.
 1398          */
 1399         fmode = imf->im6f_st[0];
 1400         if (fmode != MCAST_EXCLUDE) {
 1401                 error = EINVAL;
 1402                 goto out_in6p_locked;
 1403         }
 1404 
 1405         /*
 1406          * Deal with error cases up-front:
 1407          *  Asked to block, but already blocked; or
 1408          *  Asked to unblock, but nothing to unblock.
 1409          * If adding a new block entry, allocate it.
 1410          */
 1411         ims = im6o_match_source(imo, idx, &ssa->sa);
 1412         if ((ims != NULL && doblock) || (ims == NULL && !doblock)) {
 1413                 CTR3(KTR_MLD, "%s: source %s %spresent", __func__,
 1414                     ip6_sprintf(ip6tbuf, &ssa->sin6.sin6_addr),
 1415                     doblock ? "" : "not ");
 1416                 error = EADDRNOTAVAIL;
 1417                 goto out_in6p_locked;
 1418         }
 1419 
 1420         INP_WLOCK_ASSERT(inp);
 1421 
 1422         /*
 1423          * Begin state merge transaction at socket layer.
 1424          */
 1425         if (doblock) {
 1426                 CTR2(KTR_MLD, "%s: %s source", __func__, "block");
 1427                 ims = im6f_graft(imf, fmode, &ssa->sin6);
 1428                 if (ims == NULL)
 1429                         error = ENOMEM;
 1430         } else {
 1431                 CTR2(KTR_MLD, "%s: %s source", __func__, "allow");
 1432                 error = im6f_prune(imf, &ssa->sin6);
 1433         }
 1434 
 1435         if (error) {
 1436                 CTR1(KTR_MLD, "%s: merge imf state failed", __func__);
 1437                 goto out_im6f_rollback;
 1438         }
 1439 
 1440         /*
 1441          * Begin state merge transaction at MLD layer.
 1442          */
 1443         IN6_MULTI_LOCK();
 1444 
 1445         CTR1(KTR_MLD, "%s: merge inm state", __func__);
 1446         error = in6m_merge(inm, imf);
 1447         if (error) {
 1448                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
 1449                 goto out_im6f_rollback;
 1450         }
 1451 
 1452         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
 1453         error = mld_change_state(inm, 0);
 1454         if (error)
 1455                 CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
 1456 
 1457         IN6_MULTI_UNLOCK();
 1458 
 1459 out_im6f_rollback:
 1460         if (error)
 1461                 im6f_rollback(imf);
 1462         else
 1463                 im6f_commit(imf);
 1464 
 1465         im6f_reap(imf);
 1466 
 1467 out_in6p_locked:
 1468         INP_WUNLOCK(inp);
 1469         return (error);
 1470 }
 1471 
 1472 /*
 1473  * Given an inpcb, return its multicast options structure pointer.  Accepts
 1474  * an unlocked inpcb pointer, but will return it locked.  May sleep.
 1475  *
 1476  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
 1477  * SMPng: NOTE: Returns with the INP write lock held.
 1478  */
 1479 static struct ip6_moptions *
 1480 in6p_findmoptions(struct inpcb *inp)
 1481 {
 1482         struct ip6_moptions      *imo;
 1483         struct in6_multi                **immp;
 1484         struct in6_mfilter       *imfp;
 1485         size_t                    idx;
 1486 
 1487         INP_WLOCK(inp);
 1488         if (inp->in6p_moptions != NULL)
 1489                 return (inp->in6p_moptions);
 1490 
 1491         INP_WUNLOCK(inp);
 1492 
 1493         imo = malloc(sizeof(*imo), M_IP6MOPTS, M_WAITOK);
 1494         immp = malloc(sizeof(*immp) * IPV6_MIN_MEMBERSHIPS, M_IP6MOPTS,
 1495             M_WAITOK | M_ZERO);
 1496         imfp = malloc(sizeof(struct in6_mfilter) * IPV6_MIN_MEMBERSHIPS,
 1497             M_IN6MFILTER, M_WAITOK);
 1498 
 1499         imo->im6o_multicast_ifp = NULL;
 1500         imo->im6o_multicast_hlim = V_ip6_defmcasthlim;
 1501         imo->im6o_multicast_loop = in6_mcast_loop;
 1502         imo->im6o_num_memberships = 0;
 1503         imo->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
 1504         imo->im6o_membership = immp;
 1505 
 1506         /* Initialize per-group source filters. */
 1507         for (idx = 0; idx < IPV6_MIN_MEMBERSHIPS; idx++)
 1508                 im6f_init(&imfp[idx], MCAST_UNDEFINED, MCAST_EXCLUDE);
 1509         imo->im6o_mfilters = imfp;
 1510 
 1511         INP_WLOCK(inp);
 1512         if (inp->in6p_moptions != NULL) {
 1513                 free(imfp, M_IN6MFILTER);
 1514                 free(immp, M_IP6MOPTS);
 1515                 free(imo, M_IP6MOPTS);
 1516                 return (inp->in6p_moptions);
 1517         }
 1518         inp->in6p_moptions = imo;
 1519         return (imo);
 1520 }
 1521 
 1522 /*
 1523  * Discard the IPv6 multicast options (and source filters).
 1524  *
 1525  * SMPng: NOTE: assumes INP write lock is held.
 1526  */
 1527 void
 1528 ip6_freemoptions(struct ip6_moptions *imo)
 1529 {
 1530         struct in6_mfilter      *imf;
 1531         size_t                   idx, nmships;
 1532 
 1533         KASSERT(imo != NULL, ("%s: ip6_moptions is NULL", __func__));
 1534 
 1535         nmships = imo->im6o_num_memberships;
 1536         for (idx = 0; idx < nmships; ++idx) {
 1537                 imf = imo->im6o_mfilters ? &imo->im6o_mfilters[idx] : NULL;
 1538                 if (imf)
 1539                         im6f_leave(imf);
 1540                 /* XXX this will thrash the lock(s) */
 1541                 (void)in6_mc_leave(imo->im6o_membership[idx], imf);
 1542                 if (imf)
 1543                         im6f_purge(imf);
 1544         }
 1545 
 1546         if (imo->im6o_mfilters)
 1547                 free(imo->im6o_mfilters, M_IN6MFILTER);
 1548         free(imo->im6o_membership, M_IP6MOPTS);
 1549         free(imo, M_IP6MOPTS);
 1550 }
 1551 
 1552 /*
 1553  * Atomically get source filters on a socket for an IPv6 multicast group.
 1554  * Called with INP lock held; returns with lock released.
 1555  */
 1556 static int
 1557 in6p_get_source_filters(struct inpcb *inp, struct sockopt *sopt)
 1558 {
 1559         struct __msfilterreq     msfr;
 1560         sockunion_t             *gsa;
 1561         struct ifnet            *ifp;
 1562         struct ip6_moptions     *imo;
 1563         struct in6_mfilter      *imf;
 1564         struct ip6_msource      *ims;
 1565         struct in6_msource      *lims;
 1566         struct sockaddr_in6     *psin;
 1567         struct sockaddr_storage *ptss;
 1568         struct sockaddr_storage *tss;
 1569         int                      error;
 1570         size_t                   idx, nsrcs, ncsrcs;
 1571 
 1572         INP_WLOCK_ASSERT(inp);
 1573 
 1574         imo = inp->in6p_moptions;
 1575         KASSERT(imo != NULL, ("%s: null ip6_moptions", __func__));
 1576 
 1577         INP_WUNLOCK(inp);
 1578 
 1579         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
 1580             sizeof(struct __msfilterreq));
 1581         if (error)
 1582                 return (error);
 1583 
 1584         if (msfr.msfr_group.ss_family != AF_INET6 ||
 1585             msfr.msfr_group.ss_len != sizeof(struct sockaddr_in6))
 1586                 return (EINVAL);
 1587 
 1588         gsa = (sockunion_t *)&msfr.msfr_group;
 1589         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
 1590                 return (EINVAL);
 1591 
 1592         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
 1593                 return (EADDRNOTAVAIL);
 1594         ifp = ifnet_byindex(msfr.msfr_ifindex);
 1595         if (ifp == NULL)
 1596                 return (EADDRNOTAVAIL);
 1597         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
 1598 
 1599         INP_WLOCK(inp);
 1600 
 1601         /*
 1602          * Lookup group on the socket.
 1603          */
 1604         idx = im6o_match_group(imo, ifp, &gsa->sa);
 1605         if (idx == -1 || imo->im6o_mfilters == NULL) {
 1606                 INP_WUNLOCK(inp);
 1607                 return (EADDRNOTAVAIL);
 1608         }
 1609         imf = &imo->im6o_mfilters[idx];
 1610 
 1611         /*
 1612          * Ignore memberships which are in limbo.
 1613          */
 1614         if (imf->im6f_st[1] == MCAST_UNDEFINED) {
 1615                 INP_WUNLOCK(inp);
 1616                 return (EAGAIN);
 1617         }
 1618         msfr.msfr_fmode = imf->im6f_st[1];
 1619 
 1620         /*
 1621          * If the user specified a buffer, copy out the source filter
 1622          * entries to userland gracefully.
 1623          * We only copy out the number of entries which userland
 1624          * has asked for, but we always tell userland how big the
 1625          * buffer really needs to be.
 1626          */
 1627         if (msfr.msfr_nsrcs > in6_mcast_maxsocksrc)
 1628                 msfr.msfr_nsrcs = in6_mcast_maxsocksrc;
 1629         tss = NULL;
 1630         if (msfr.msfr_srcs != NULL && msfr.msfr_nsrcs > 0) {
 1631                 tss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
 1632                     M_TEMP, M_NOWAIT | M_ZERO);
 1633                 if (tss == NULL) {
 1634                         INP_WUNLOCK(inp);
 1635                         return (ENOBUFS);
 1636                 }
 1637         }
 1638 
 1639         /*
 1640          * Count number of sources in-mode at t0.
 1641          * If buffer space exists and remains, copy out source entries.
 1642          */
 1643         nsrcs = msfr.msfr_nsrcs;
 1644         ncsrcs = 0;
 1645         ptss = tss;
 1646         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
 1647                 lims = (struct in6_msource *)ims;
 1648                 if (lims->im6sl_st[0] == MCAST_UNDEFINED ||
 1649                     lims->im6sl_st[0] != imf->im6f_st[0])
 1650                         continue;
 1651                 ++ncsrcs;
 1652                 if (tss != NULL && nsrcs > 0) {
 1653                         psin = (struct sockaddr_in6 *)ptss;
 1654                         psin->sin6_family = AF_INET6;
 1655                         psin->sin6_len = sizeof(struct sockaddr_in6);
 1656                         psin->sin6_addr = lims->im6s_addr;
 1657                         psin->sin6_port = 0;
 1658                         --nsrcs;
 1659                         ++ptss;
 1660                 }
 1661         }
 1662 
 1663         INP_WUNLOCK(inp);
 1664 
 1665         if (tss != NULL) {
 1666                 error = copyout(tss, msfr.msfr_srcs,
 1667                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
 1668                 free(tss, M_TEMP);
 1669                 if (error)
 1670                         return (error);
 1671         }
 1672 
 1673         msfr.msfr_nsrcs = ncsrcs;
 1674         error = sooptcopyout(sopt, &msfr, sizeof(struct __msfilterreq));
 1675 
 1676         return (error);
 1677 }
 1678 
 1679 /*
 1680  * Return the IP multicast options in response to user getsockopt().
 1681  */
 1682 int
 1683 ip6_getmoptions(struct inpcb *inp, struct sockopt *sopt)
 1684 {
 1685         struct ip6_moptions     *im6o;
 1686         int                      error;
 1687         u_int                    optval;
 1688 
 1689         INP_WLOCK(inp);
 1690         im6o = inp->in6p_moptions;
 1691         /*
 1692          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
 1693          * or is a divert socket, reject it.
 1694          */
 1695         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
 1696             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
 1697             inp->inp_socket->so_proto->pr_type != SOCK_DGRAM)) {
 1698                 INP_WUNLOCK(inp);
 1699                 return (EOPNOTSUPP);
 1700         }
 1701 
 1702         error = 0;
 1703         switch (sopt->sopt_name) {
 1704         case IPV6_MULTICAST_IF:
 1705                 if (im6o == NULL || im6o->im6o_multicast_ifp == NULL) {
 1706                         optval = 0;
 1707                 } else {
 1708                         optval = im6o->im6o_multicast_ifp->if_index;
 1709                 }
 1710                 INP_WUNLOCK(inp);
 1711                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
 1712                 break;
 1713 
 1714         case IPV6_MULTICAST_HOPS:
 1715                 if (im6o == NULL)
 1716                         optval = V_ip6_defmcasthlim;
 1717                 else
 1718                         optval = im6o->im6o_multicast_hlim;
 1719                 INP_WUNLOCK(inp);
 1720                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
 1721                 break;
 1722 
 1723         case IPV6_MULTICAST_LOOP:
 1724                 if (im6o == NULL)
 1725                         optval = in6_mcast_loop; /* XXX VIMAGE */
 1726                 else
 1727                         optval = im6o->im6o_multicast_loop;
 1728                 INP_WUNLOCK(inp);
 1729                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
 1730                 break;
 1731 
 1732         case IPV6_MSFILTER:
 1733                 if (im6o == NULL) {
 1734                         error = EADDRNOTAVAIL;
 1735                         INP_WUNLOCK(inp);
 1736                 } else {
 1737                         error = in6p_get_source_filters(inp, sopt);
 1738                 }
 1739                 break;
 1740 
 1741         default:
 1742                 INP_WUNLOCK(inp);
 1743                 error = ENOPROTOOPT;
 1744                 break;
 1745         }
 1746 
 1747         INP_UNLOCK_ASSERT(inp);
 1748 
 1749         return (error);
 1750 }
 1751 
 1752 /*
 1753  * Look up the ifnet to use for a multicast group membership,
 1754  * given the address of an IPv6 group.
 1755  *
 1756  * This routine exists to support legacy IPv6 multicast applications.
 1757  *
 1758  * If inp is non-NULL, use this socket's current FIB number for any
 1759  * required FIB lookup. Look up the group address in the unicast FIB,
 1760  * and use its ifp; usually, this points to the default next-hop.
 1761  * If the FIB lookup fails, return NULL.
 1762  *
 1763  * FUTURE: Support multiple forwarding tables for IPv6.
 1764  *
 1765  * Returns NULL if no ifp could be found.
 1766  */
 1767 static struct ifnet *
 1768 in6p_lookup_mcast_ifp(const struct inpcb *in6p,
 1769     const struct sockaddr_in6 *gsin6)
 1770 {
 1771         struct route_in6         ro6;
 1772         struct ifnet            *ifp;
 1773 
 1774         KASSERT(in6p->inp_vflag & INP_IPV6,
 1775             ("%s: not INP_IPV6 inpcb", __func__));
 1776         KASSERT(gsin6->sin6_family == AF_INET6,
 1777             ("%s: not AF_INET6 group", __func__));
 1778         KASSERT(IN6_IS_ADDR_MULTICAST(&gsin6->sin6_addr),
 1779             ("%s: not multicast", __func__));
 1780 
 1781         ifp = NULL;
 1782         memset(&ro6, 0, sizeof(struct route_in6));
 1783         memcpy(&ro6.ro_dst, gsin6, sizeof(struct sockaddr_in6));
 1784         rtalloc_ign_fib((struct route *)&ro6, 0,
 1785             in6p ? in6p->inp_inc.inc_fibnum : RT_DEFAULT_FIB);
 1786         if (ro6.ro_rt != NULL) {
 1787                 ifp = ro6.ro_rt->rt_ifp;
 1788                 KASSERT(ifp != NULL, ("%s: null ifp", __func__));
 1789                 RTFREE(ro6.ro_rt);
 1790         }
 1791 
 1792         return (ifp);
 1793 }
 1794 
 1795 /*
 1796  * Join an IPv6 multicast group, possibly with a source.
 1797  *
 1798  * FIXME: The KAME use of the unspecified address (::)
 1799  * to join *all* multicast groups is currently unsupported.
 1800  */
 1801 static int
 1802 in6p_join_group(struct inpcb *inp, struct sockopt *sopt)
 1803 {
 1804         struct group_source_req          gsr;
 1805         sockunion_t                     *gsa, *ssa;
 1806         struct ifnet                    *ifp;
 1807         struct in6_mfilter              *imf;
 1808         struct ip6_moptions             *imo;
 1809         struct in6_multi                *inm;
 1810         struct in6_msource              *lims;
 1811         size_t                           idx;
 1812         int                              error, is_new;
 1813 
 1814         ifp = NULL;
 1815         imf = NULL;
 1816         lims = NULL;
 1817         error = 0;
 1818         is_new = 0;
 1819 
 1820         memset(&gsr, 0, sizeof(struct group_source_req));
 1821         gsa = (sockunion_t *)&gsr.gsr_group;
 1822         gsa->ss.ss_family = AF_UNSPEC;
 1823         ssa = (sockunion_t *)&gsr.gsr_source;
 1824         ssa->ss.ss_family = AF_UNSPEC;
 1825 
 1826         /*
 1827          * Chew everything into struct group_source_req.
 1828          * Overwrite the port field if present, as the sockaddr
 1829          * being copied in may be matched with a binary comparison.
 1830          * Ignore passed-in scope ID.
 1831          */
 1832         switch (sopt->sopt_name) {
 1833         case IPV6_JOIN_GROUP: {
 1834                 struct ipv6_mreq mreq;
 1835 
 1836                 error = sooptcopyin(sopt, &mreq, sizeof(struct ipv6_mreq),
 1837                     sizeof(struct ipv6_mreq));
 1838                 if (error)
 1839                         return (error);
 1840 
 1841                 gsa->sin6.sin6_family = AF_INET6;
 1842                 gsa->sin6.sin6_len = sizeof(struct sockaddr_in6);
 1843                 gsa->sin6.sin6_addr = mreq.ipv6mr_multiaddr;
 1844 
 1845                 if (mreq.ipv6mr_interface == 0) {
 1846                         ifp = in6p_lookup_mcast_ifp(inp, &gsa->sin6);
 1847                 } else {
 1848                         if (mreq.ipv6mr_interface < 0 ||
 1849                             V_if_index < mreq.ipv6mr_interface)
 1850                                 return (EADDRNOTAVAIL);
 1851                         ifp = ifnet_byindex(mreq.ipv6mr_interface);
 1852                 }
 1853                 CTR3(KTR_MLD, "%s: ipv6mr_interface = %d, ifp = %p",
 1854                     __func__, mreq.ipv6mr_interface, ifp);
 1855         } break;
 1856 
 1857         case MCAST_JOIN_GROUP:
 1858         case MCAST_JOIN_SOURCE_GROUP:
 1859                 if (sopt->sopt_name == MCAST_JOIN_GROUP) {
 1860                         error = sooptcopyin(sopt, &gsr,
 1861                             sizeof(struct group_req),
 1862                             sizeof(struct group_req));
 1863                 } else if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
 1864                         error = sooptcopyin(sopt, &gsr,
 1865                             sizeof(struct group_source_req),
 1866                             sizeof(struct group_source_req));
 1867                 }
 1868                 if (error)
 1869                         return (error);
 1870 
 1871                 if (gsa->sin6.sin6_family != AF_INET6 ||
 1872                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
 1873                         return (EINVAL);
 1874 
 1875                 if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
 1876                         if (ssa->sin6.sin6_family != AF_INET6 ||
 1877                             ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
 1878                                 return (EINVAL);
 1879                         if (IN6_IS_ADDR_MULTICAST(&ssa->sin6.sin6_addr))
 1880                                 return (EINVAL);
 1881                         /*
 1882                          * TODO: Validate embedded scope ID in source
 1883                          * list entry against passed-in ifp, if and only
 1884                          * if source list filter entry is iface or node local.
 1885                          */
 1886                         in6_clearscope(&ssa->sin6.sin6_addr);
 1887                         ssa->sin6.sin6_port = 0;
 1888                         ssa->sin6.sin6_scope_id = 0;
 1889                 }
 1890 
 1891                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
 1892                         return (EADDRNOTAVAIL);
 1893                 ifp = ifnet_byindex(gsr.gsr_interface);
 1894                 break;
 1895 
 1896         default:
 1897                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
 1898                     __func__, sopt->sopt_name);
 1899                 return (EOPNOTSUPP);
 1900                 break;
 1901         }
 1902 
 1903         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
 1904                 return (EINVAL);
 1905 
 1906         if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0)
 1907                 return (EADDRNOTAVAIL);
 1908 
 1909         gsa->sin6.sin6_port = 0;
 1910         gsa->sin6.sin6_scope_id = 0;
 1911 
 1912         /*
 1913          * Always set the scope zone ID on memberships created from userland.
 1914          * Use the passed-in ifp to do this.
 1915          * XXX The in6_setscope() return value is meaningless.
 1916          * XXX SCOPE6_LOCK() is taken by in6_setscope().
 1917          */
 1918         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
 1919 
 1920         imo = in6p_findmoptions(inp);
 1921         idx = im6o_match_group(imo, ifp, &gsa->sa);
 1922         if (idx == -1) {
 1923                 is_new = 1;
 1924         } else {
 1925                 inm = imo->im6o_membership[idx];
 1926                 imf = &imo->im6o_mfilters[idx];
 1927                 if (ssa->ss.ss_family != AF_UNSPEC) {
 1928                         /*
 1929                          * MCAST_JOIN_SOURCE_GROUP on an exclusive membership
 1930                          * is an error. On an existing inclusive membership,
 1931                          * it just adds the source to the filter list.
 1932                          */
 1933                         if (imf->im6f_st[1] != MCAST_INCLUDE) {
 1934                                 error = EINVAL;
 1935                                 goto out_in6p_locked;
 1936                         }
 1937                         /*
 1938                          * Throw out duplicates.
 1939                          *
 1940                          * XXX FIXME: This makes a naive assumption that
 1941                          * even if entries exist for *ssa in this imf,
 1942                          * they will be rejected as dupes, even if they
 1943                          * are not valid in the current mode (in-mode).
 1944                          *
 1945                          * in6_msource is transactioned just as for anything
 1946                          * else in SSM -- but note naive use of in6m_graft()
 1947                          * below for allocating new filter entries.
 1948                          *
 1949                          * This is only an issue if someone mixes the
 1950                          * full-state SSM API with the delta-based API,
 1951                          * which is discouraged in the relevant RFCs.
 1952                          */
 1953                         lims = im6o_match_source(imo, idx, &ssa->sa);
 1954                         if (lims != NULL /*&&
 1955                             lims->im6sl_st[1] == MCAST_INCLUDE*/) {
 1956                                 error = EADDRNOTAVAIL;
 1957                                 goto out_in6p_locked;
 1958                         }
 1959                 } else {
 1960                         /*
 1961                          * MCAST_JOIN_GROUP alone, on any existing membership,
 1962                          * is rejected, to stop the same inpcb tying up
 1963                          * multiple refs to the in_multi.
 1964                          * On an existing inclusive membership, this is also
 1965                          * an error; if you want to change filter mode,
 1966                          * you must use the userland API setsourcefilter().
 1967                          * XXX We don't reject this for imf in UNDEFINED
 1968                          * state at t1, because allocation of a filter
 1969                          * is atomic with allocation of a membership.
 1970                          */
 1971                         error = EINVAL;
 1972                         goto out_in6p_locked;
 1973                 }
 1974         }
 1975 
 1976         /*
 1977          * Begin state merge transaction at socket layer.
 1978          */
 1979         INP_WLOCK_ASSERT(inp);
 1980 
 1981         if (is_new) {
 1982                 if (imo->im6o_num_memberships == imo->im6o_max_memberships) {
 1983                         error = im6o_grow(imo);
 1984                         if (error)
 1985                                 goto out_in6p_locked;
 1986                 }
 1987                 /*
 1988                  * Allocate the new slot upfront so we can deal with
 1989                  * grafting the new source filter in same code path
 1990                  * as for join-source on existing membership.
 1991                  */
 1992                 idx = imo->im6o_num_memberships;
 1993                 imo->im6o_membership[idx] = NULL;
 1994                 imo->im6o_num_memberships++;
 1995                 KASSERT(imo->im6o_mfilters != NULL,
 1996                     ("%s: im6f_mfilters vector was not allocated", __func__));
 1997                 imf = &imo->im6o_mfilters[idx];
 1998                 KASSERT(RB_EMPTY(&imf->im6f_sources),
 1999                     ("%s: im6f_sources not empty", __func__));
 2000         }
 2001 
 2002         /*
 2003          * Graft new source into filter list for this inpcb's
 2004          * membership of the group. The in6_multi may not have
 2005          * been allocated yet if this is a new membership, however,
 2006          * the in_mfilter slot will be allocated and must be initialized.
 2007          *
 2008          * Note: Grafting of exclusive mode filters doesn't happen
 2009          * in this path.
 2010          * XXX: Should check for non-NULL lims (node exists but may
 2011          * not be in-mode) for interop with full-state API.
 2012          */
 2013         if (ssa->ss.ss_family != AF_UNSPEC) {
 2014                 /* Membership starts in IN mode */
 2015                 if (is_new) {
 2016                         CTR1(KTR_MLD, "%s: new join w/source", __func__);
 2017                         im6f_init(imf, MCAST_UNDEFINED, MCAST_INCLUDE);
 2018                 } else {
 2019                         CTR2(KTR_MLD, "%s: %s source", __func__, "allow");
 2020                 }
 2021                 lims = im6f_graft(imf, MCAST_INCLUDE, &ssa->sin6);
 2022                 if (lims == NULL) {
 2023                         CTR1(KTR_MLD, "%s: merge imf state failed",
 2024                             __func__);
 2025                         error = ENOMEM;
 2026                         goto out_im6o_free;
 2027                 }
 2028         } else {
 2029                 /* No address specified; Membership starts in EX mode */
 2030                 if (is_new) {
 2031                         CTR1(KTR_MLD, "%s: new join w/o source", __func__);
 2032                         im6f_init(imf, MCAST_UNDEFINED, MCAST_EXCLUDE);
 2033                 }
 2034         }
 2035 
 2036         /*
 2037          * Begin state merge transaction at MLD layer.
 2038          */
 2039         IN6_MULTI_LOCK();
 2040 
 2041         if (is_new) {
 2042                 error = in6_mc_join_locked(ifp, &gsa->sin6.sin6_addr, imf,
 2043                     &inm, 0);
 2044                 if (error)
 2045                         goto out_im6o_free;
 2046                 imo->im6o_membership[idx] = inm;
 2047         } else {
 2048                 CTR1(KTR_MLD, "%s: merge inm state", __func__);
 2049                 error = in6m_merge(inm, imf);
 2050                 if (error) {
 2051                         CTR1(KTR_MLD, "%s: failed to merge inm state",
 2052                             __func__);
 2053                         goto out_im6f_rollback;
 2054                 }
 2055                 CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
 2056                 error = mld_change_state(inm, 0);
 2057                 if (error) {
 2058                         CTR1(KTR_MLD, "%s: failed mld downcall",
 2059                             __func__);
 2060                         goto out_im6f_rollback;
 2061                 }
 2062         }
 2063 
 2064         IN6_MULTI_UNLOCK();
 2065 
 2066 out_im6f_rollback:
 2067         INP_WLOCK_ASSERT(inp);
 2068         if (error) {
 2069                 im6f_rollback(imf);
 2070                 if (is_new)
 2071                         im6f_purge(imf);
 2072                 else
 2073                         im6f_reap(imf);
 2074         } else {
 2075                 im6f_commit(imf);
 2076         }
 2077 
 2078 out_im6o_free:
 2079         if (error && is_new) {
 2080                 imo->im6o_membership[idx] = NULL;
 2081                 --imo->im6o_num_memberships;
 2082         }
 2083 
 2084 out_in6p_locked:
 2085         INP_WUNLOCK(inp);
 2086         return (error);
 2087 }
 2088 
 2089 /*
 2090  * Leave an IPv6 multicast group on an inpcb, possibly with a source.
 2091  */
 2092 static int
 2093 in6p_leave_group(struct inpcb *inp, struct sockopt *sopt)
 2094 {
 2095         struct ipv6_mreq                 mreq;
 2096         struct group_source_req          gsr;
 2097         sockunion_t                     *gsa, *ssa;
 2098         struct ifnet                    *ifp;
 2099         struct in6_mfilter              *imf;
 2100         struct ip6_moptions             *imo;
 2101         struct in6_msource              *ims;
 2102         struct in6_multi                *inm;
 2103         uint32_t                         ifindex;
 2104         size_t                           idx;
 2105         int                              error, is_final;
 2106 #ifdef KTR
 2107         char                             ip6tbuf[INET6_ADDRSTRLEN];
 2108 #endif
 2109 
 2110         ifp = NULL;
 2111         ifindex = 0;
 2112         error = 0;
 2113         is_final = 1;
 2114 
 2115         memset(&gsr, 0, sizeof(struct group_source_req));
 2116         gsa = (sockunion_t *)&gsr.gsr_group;
 2117         gsa->ss.ss_family = AF_UNSPEC;
 2118         ssa = (sockunion_t *)&gsr.gsr_source;
 2119         ssa->ss.ss_family = AF_UNSPEC;
 2120 
 2121         /*
 2122          * Chew everything passed in up into a struct group_source_req
 2123          * as that is easier to process.
 2124          * Note: Any embedded scope ID in the multicast group passed
 2125          * in by userland is ignored, the interface index is the recommended
 2126          * mechanism to specify an interface; see below.
 2127          */
 2128         switch (sopt->sopt_name) {
 2129         case IPV6_LEAVE_GROUP:
 2130                 error = sooptcopyin(sopt, &mreq, sizeof(struct ipv6_mreq),
 2131                     sizeof(struct ipv6_mreq));
 2132                 if (error)
 2133                         return (error);
 2134                 gsa->sin6.sin6_family = AF_INET6;
 2135                 gsa->sin6.sin6_len = sizeof(struct sockaddr_in6);
 2136                 gsa->sin6.sin6_addr = mreq.ipv6mr_multiaddr;
 2137                 gsa->sin6.sin6_port = 0;
 2138                 gsa->sin6.sin6_scope_id = 0;
 2139                 ifindex = mreq.ipv6mr_interface;
 2140                 break;
 2141 
 2142         case MCAST_LEAVE_GROUP:
 2143         case MCAST_LEAVE_SOURCE_GROUP:
 2144                 if (sopt->sopt_name == MCAST_LEAVE_GROUP) {
 2145                         error = sooptcopyin(sopt, &gsr,
 2146                             sizeof(struct group_req),
 2147                             sizeof(struct group_req));
 2148                 } else if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
 2149                         error = sooptcopyin(sopt, &gsr,
 2150                             sizeof(struct group_source_req),
 2151                             sizeof(struct group_source_req));
 2152                 }
 2153                 if (error)
 2154                         return (error);
 2155 
 2156                 if (gsa->sin6.sin6_family != AF_INET6 ||
 2157                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
 2158                         return (EINVAL);
 2159                 if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
 2160                         if (ssa->sin6.sin6_family != AF_INET6 ||
 2161                             ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
 2162                                 return (EINVAL);
 2163                         if (IN6_IS_ADDR_MULTICAST(&ssa->sin6.sin6_addr))
 2164                                 return (EINVAL);
 2165                         /*
 2166                          * TODO: Validate embedded scope ID in source
 2167                          * list entry against passed-in ifp, if and only
 2168                          * if source list filter entry is iface or node local.
 2169                          */
 2170                         in6_clearscope(&ssa->sin6.sin6_addr);
 2171                 }
 2172                 gsa->sin6.sin6_port = 0;
 2173                 gsa->sin6.sin6_scope_id = 0;
 2174                 ifindex = gsr.gsr_interface;
 2175                 break;
 2176 
 2177         default:
 2178                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
 2179                     __func__, sopt->sopt_name);
 2180                 return (EOPNOTSUPP);
 2181                 break;
 2182         }
 2183 
 2184         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
 2185                 return (EINVAL);
 2186 
 2187         /*
 2188          * Validate interface index if provided. If no interface index
 2189          * was provided separately, attempt to look the membership up
 2190          * from the default scope as a last resort to disambiguate
 2191          * the membership we are being asked to leave.
 2192          * XXX SCOPE6 lock potentially taken here.
 2193          */
 2194         if (ifindex != 0) {
 2195                 if (ifindex < 0 || V_if_index < ifindex)
 2196                         return (EADDRNOTAVAIL);
 2197                 ifp = ifnet_byindex(ifindex);
 2198                 if (ifp == NULL)
 2199                         return (EADDRNOTAVAIL);
 2200                 (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
 2201         } else {
 2202                 error = sa6_embedscope(&gsa->sin6, V_ip6_use_defzone);
 2203                 if (error)
 2204                         return (EADDRNOTAVAIL);
 2205                 /*
 2206                  * Some badly behaved applications don't pass an ifindex
 2207                  * or a scope ID, which is an API violation. In this case,
 2208                  * perform a lookup as per a v6 join.
 2209                  *
 2210                  * XXX For now, stomp on zone ID for the corner case.
 2211                  * This is not the 'KAME way', but we need to see the ifp
 2212                  * directly until such time as this implementation is
 2213                  * refactored, assuming the scope IDs are the way to go.
 2214                  */
 2215                 ifindex = ntohs(gsa->sin6.sin6_addr.s6_addr16[1]);
 2216                 if (ifindex == 0) {
 2217                         CTR2(KTR_MLD, "%s: warning: no ifindex, looking up "
 2218                             "ifp for group %s.", __func__,
 2219                             ip6_sprintf(ip6tbuf, &gsa->sin6.sin6_addr));
 2220                         ifp = in6p_lookup_mcast_ifp(inp, &gsa->sin6);
 2221                 } else {
 2222                         ifp = ifnet_byindex(ifindex);
 2223                 }
 2224                 if (ifp == NULL)
 2225                         return (EADDRNOTAVAIL);
 2226         }
 2227 
 2228         CTR2(KTR_MLD, "%s: ifp = %p", __func__, ifp);
 2229         KASSERT(ifp != NULL, ("%s: ifp did not resolve", __func__));
 2230 
 2231         /*
 2232          * Find the membership in the membership array.
 2233          */
 2234         imo = in6p_findmoptions(inp);
 2235         idx = im6o_match_group(imo, ifp, &gsa->sa);
 2236         if (idx == -1) {
 2237                 error = EADDRNOTAVAIL;
 2238                 goto out_in6p_locked;
 2239         }
 2240         inm = imo->im6o_membership[idx];
 2241         imf = &imo->im6o_mfilters[idx];
 2242 
 2243         if (ssa->ss.ss_family != AF_UNSPEC)
 2244                 is_final = 0;
 2245 
 2246         /*
 2247          * Begin state merge transaction at socket layer.
 2248          */
 2249         INP_WLOCK_ASSERT(inp);
 2250 
 2251         /*
 2252          * If we were instructed only to leave a given source, do so.
 2253          * MCAST_LEAVE_SOURCE_GROUP is only valid for inclusive memberships.
 2254          */
 2255         if (is_final) {
 2256                 im6f_leave(imf);
 2257         } else {
 2258                 if (imf->im6f_st[0] == MCAST_EXCLUDE) {
 2259                         error = EADDRNOTAVAIL;
 2260                         goto out_in6p_locked;
 2261                 }
 2262                 ims = im6o_match_source(imo, idx, &ssa->sa);
 2263                 if (ims == NULL) {
 2264                         CTR3(KTR_MLD, "%s: source %p %spresent", __func__,
 2265                             ip6_sprintf(ip6tbuf, &ssa->sin6.sin6_addr),
 2266                             "not ");
 2267                         error = EADDRNOTAVAIL;
 2268                         goto out_in6p_locked;
 2269                 }
 2270                 CTR2(KTR_MLD, "%s: %s source", __func__, "block");
 2271                 error = im6f_prune(imf, &ssa->sin6);
 2272                 if (error) {
 2273                         CTR1(KTR_MLD, "%s: merge imf state failed",
 2274                             __func__);
 2275                         goto out_in6p_locked;
 2276                 }
 2277         }
 2278 
 2279         /*
 2280          * Begin state merge transaction at MLD layer.
 2281          */
 2282         IN6_MULTI_LOCK();
 2283 
 2284         if (is_final) {
 2285                 /*
 2286                  * Give up the multicast address record to which
 2287                  * the membership points.
 2288                  */
 2289                 (void)in6_mc_leave_locked(inm, imf);
 2290         } else {
 2291                 CTR1(KTR_MLD, "%s: merge inm state", __func__);
 2292                 error = in6m_merge(inm, imf);
 2293                 if (error) {
 2294                         CTR1(KTR_MLD, "%s: failed to merge inm state",
 2295                             __func__);
 2296                         goto out_im6f_rollback;
 2297                 }
 2298 
 2299                 CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
 2300                 error = mld_change_state(inm, 0);
 2301                 if (error) {
 2302                         CTR1(KTR_MLD, "%s: failed mld downcall",
 2303                             __func__);
 2304                 }
 2305         }
 2306 
 2307         IN6_MULTI_UNLOCK();
 2308 
 2309 out_im6f_rollback:
 2310         if (error)
 2311                 im6f_rollback(imf);
 2312         else
 2313                 im6f_commit(imf);
 2314 
 2315         im6f_reap(imf);
 2316 
 2317         if (is_final) {
 2318                 /* Remove the gap in the membership array. */
 2319                 for (++idx; idx < imo->im6o_num_memberships; ++idx) {
 2320                         imo->im6o_membership[idx-1] = imo->im6o_membership[idx];
 2321                         imo->im6o_mfilters[idx-1] = imo->im6o_mfilters[idx];
 2322                 }
 2323                 imo->im6o_num_memberships--;
 2324         }
 2325 
 2326 out_in6p_locked:
 2327         INP_WUNLOCK(inp);
 2328         return (error);
 2329 }
 2330 
 2331 /*
 2332  * Select the interface for transmitting IPv6 multicast datagrams.
 2333  *
 2334  * Either an instance of struct in6_addr or an instance of struct ipv6_mreqn
 2335  * may be passed to this socket option. An address of in6addr_any or an
 2336  * interface index of 0 is used to remove a previous selection.
 2337  * When no interface is selected, one is chosen for every send.
 2338  */
 2339 static int
 2340 in6p_set_multicast_if(struct inpcb *inp, struct sockopt *sopt)
 2341 {
 2342         struct ifnet            *ifp;
 2343         struct ip6_moptions     *imo;
 2344         u_int                    ifindex;
 2345         int                      error;
 2346 
 2347         if (sopt->sopt_valsize != sizeof(u_int))
 2348                 return (EINVAL);
 2349 
 2350         error = sooptcopyin(sopt, &ifindex, sizeof(u_int), sizeof(u_int));
 2351         if (error)
 2352                 return (error);
 2353         if (ifindex < 0 || V_if_index < ifindex)
 2354                 return (EINVAL);
 2355 
 2356         ifp = ifnet_byindex(ifindex);
 2357         if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0)
 2358                 return (EADDRNOTAVAIL);
 2359 
 2360         imo = in6p_findmoptions(inp);
 2361         imo->im6o_multicast_ifp = ifp;
 2362         INP_WUNLOCK(inp);
 2363 
 2364         return (0);
 2365 }
 2366 
 2367 /*
 2368  * Atomically set source filters on a socket for an IPv6 multicast group.
 2369  *
 2370  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
 2371  */
 2372 static int
 2373 in6p_set_source_filters(struct inpcb *inp, struct sockopt *sopt)
 2374 {
 2375         struct __msfilterreq     msfr;
 2376         sockunion_t             *gsa;
 2377         struct ifnet            *ifp;
 2378         struct in6_mfilter      *imf;
 2379         struct ip6_moptions     *imo;
 2380         struct in6_multi                *inm;
 2381         size_t                   idx;
 2382         int                      error;
 2383 
 2384         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
 2385             sizeof(struct __msfilterreq));
 2386         if (error)
 2387                 return (error);
 2388 
 2389         if (msfr.msfr_nsrcs > in6_mcast_maxsocksrc)
 2390                 return (ENOBUFS);
 2391 
 2392         if (msfr.msfr_fmode != MCAST_EXCLUDE &&
 2393             msfr.msfr_fmode != MCAST_INCLUDE)
 2394                 return (EINVAL);
 2395 
 2396         if (msfr.msfr_group.ss_family != AF_INET6 ||
 2397             msfr.msfr_group.ss_len != sizeof(struct sockaddr_in6))
 2398                 return (EINVAL);
 2399 
 2400         gsa = (sockunion_t *)&msfr.msfr_group;
 2401         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
 2402                 return (EINVAL);
 2403 
 2404         gsa->sin6.sin6_port = 0;        /* ignore port */
 2405 
 2406         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
 2407                 return (EADDRNOTAVAIL);
 2408         ifp = ifnet_byindex(msfr.msfr_ifindex);
 2409         if (ifp == NULL)
 2410                 return (EADDRNOTAVAIL);
 2411         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
 2412 
 2413         /*
 2414          * Take the INP write lock.
 2415          * Check if this socket is a member of this group.
 2416          */
 2417         imo = in6p_findmoptions(inp);
 2418         idx = im6o_match_group(imo, ifp, &gsa->sa);
 2419         if (idx == -1 || imo->im6o_mfilters == NULL) {
 2420                 error = EADDRNOTAVAIL;
 2421                 goto out_in6p_locked;
 2422         }
 2423         inm = imo->im6o_membership[idx];
 2424         imf = &imo->im6o_mfilters[idx];
 2425 
 2426         /*
 2427          * Begin state merge transaction at socket layer.
 2428          */
 2429         INP_WLOCK_ASSERT(inp);
 2430 
 2431         imf->im6f_st[1] = msfr.msfr_fmode;
 2432 
 2433         /*
 2434          * Apply any new source filters, if present.
 2435          * Make a copy of the user-space source vector so
 2436          * that we may copy them with a single copyin. This
 2437          * allows us to deal with page faults up-front.
 2438          */
 2439         if (msfr.msfr_nsrcs > 0) {
 2440                 struct in6_msource      *lims;
 2441                 struct sockaddr_in6     *psin;
 2442                 struct sockaddr_storage *kss, *pkss;
 2443                 int                      i;
 2444 
 2445                 INP_WUNLOCK(inp);
 2446  
 2447                 CTR2(KTR_MLD, "%s: loading %lu source list entries",
 2448                     __func__, (unsigned long)msfr.msfr_nsrcs);
 2449                 kss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
 2450                     M_TEMP, M_WAITOK);
 2451                 error = copyin(msfr.msfr_srcs, kss,
 2452                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
 2453                 if (error) {
 2454                         free(kss, M_TEMP);
 2455                         return (error);
 2456                 }
 2457 
 2458                 INP_WLOCK(inp);
 2459 
 2460                 /*
 2461                  * Mark all source filters as UNDEFINED at t1.
 2462                  * Restore new group filter mode, as im6f_leave()
 2463                  * will set it to INCLUDE.
 2464                  */
 2465                 im6f_leave(imf);
 2466                 imf->im6f_st[1] = msfr.msfr_fmode;
 2467 
 2468                 /*
 2469                  * Update socket layer filters at t1, lazy-allocating
 2470                  * new entries. This saves a bunch of memory at the
 2471                  * cost of one RB_FIND() per source entry; duplicate
 2472                  * entries in the msfr_nsrcs vector are ignored.
 2473                  * If we encounter an error, rollback transaction.
 2474                  *
 2475                  * XXX This too could be replaced with a set-symmetric
 2476                  * difference like loop to avoid walking from root
 2477                  * every time, as the key space is common.
 2478                  */
 2479                 for (i = 0, pkss = kss; i < msfr.msfr_nsrcs; i++, pkss++) {
 2480                         psin = (struct sockaddr_in6 *)pkss;
 2481                         if (psin->sin6_family != AF_INET6) {
 2482                                 error = EAFNOSUPPORT;
 2483                                 break;
 2484                         }
 2485                         if (psin->sin6_len != sizeof(struct sockaddr_in6)) {
 2486                                 error = EINVAL;
 2487                                 break;
 2488                         }
 2489                         if (IN6_IS_ADDR_MULTICAST(&psin->sin6_addr)) {
 2490                                 error = EINVAL;
 2491                                 break;
 2492                         }
 2493                         /*
 2494                          * TODO: Validate embedded scope ID in source
 2495                          * list entry against passed-in ifp, if and only
 2496                          * if source list filter entry is iface or node local.
 2497                          */
 2498                         in6_clearscope(&psin->sin6_addr);
 2499                         error = im6f_get_source(imf, psin, &lims);
 2500                         if (error)
 2501                                 break;
 2502                         lims->im6sl_st[1] = imf->im6f_st[1];
 2503                 }
 2504                 free(kss, M_TEMP);
 2505         }
 2506 
 2507         if (error)
 2508                 goto out_im6f_rollback;
 2509 
 2510         INP_WLOCK_ASSERT(inp);
 2511         IN6_MULTI_LOCK();
 2512 
 2513         /*
 2514          * Begin state merge transaction at MLD layer.
 2515          */
 2516         CTR1(KTR_MLD, "%s: merge inm state", __func__);
 2517         error = in6m_merge(inm, imf);
 2518         if (error) {
 2519                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
 2520                 goto out_im6f_rollback;
 2521         }
 2522 
 2523         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
 2524         error = mld_change_state(inm, 0);
 2525         if (error)
 2526                 CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
 2527 
 2528         IN6_MULTI_UNLOCK();
 2529 
 2530 out_im6f_rollback:
 2531         if (error)
 2532                 im6f_rollback(imf);
 2533         else
 2534                 im6f_commit(imf);
 2535 
 2536         im6f_reap(imf);
 2537 
 2538 out_in6p_locked:
 2539         INP_WUNLOCK(inp);
 2540         return (error);
 2541 }
 2542 
 2543 /*
 2544  * Set the IP multicast options in response to user setsockopt().
 2545  *
 2546  * Many of the socket options handled in this function duplicate the
 2547  * functionality of socket options in the regular unicast API. However,
 2548  * it is not possible to merge the duplicate code, because the idempotence
 2549  * of the IPv6 multicast part of the BSD Sockets API must be preserved;
 2550  * the effects of these options must be treated as separate and distinct.
 2551  *
 2552  * SMPng: XXX: Unlocked read of inp_socket believed OK.
 2553  */
 2554 int
 2555 ip6_setmoptions(struct inpcb *inp, struct sockopt *sopt)
 2556 {
 2557         struct ip6_moptions     *im6o;
 2558         int                      error;
 2559 
 2560         error = 0;
 2561 
 2562         /*
 2563          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
 2564          * or is a divert socket, reject it.
 2565          */
 2566         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
 2567             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
 2568              inp->inp_socket->so_proto->pr_type != SOCK_DGRAM))
 2569                 return (EOPNOTSUPP);
 2570 
 2571         switch (sopt->sopt_name) {
 2572         case IPV6_MULTICAST_IF:
 2573                 error = in6p_set_multicast_if(inp, sopt);
 2574                 break;
 2575 
 2576         case IPV6_MULTICAST_HOPS: {
 2577                 int hlim;
 2578 
 2579                 if (sopt->sopt_valsize != sizeof(int)) {
 2580                         error = EINVAL;
 2581                         break;
 2582                 }
 2583                 error = sooptcopyin(sopt, &hlim, sizeof(hlim), sizeof(int));
 2584                 if (error)
 2585                         break;
 2586                 if (hlim < -1 || hlim > 255) {
 2587                         error = EINVAL;
 2588                         break;
 2589                 } else if (hlim == -1) {
 2590                         hlim = V_ip6_defmcasthlim;
 2591                 }
 2592                 im6o = in6p_findmoptions(inp);
 2593                 im6o->im6o_multicast_hlim = hlim;
 2594                 INP_WUNLOCK(inp);
 2595                 break;
 2596         }
 2597 
 2598         case IPV6_MULTICAST_LOOP: {
 2599                 u_int loop;
 2600 
 2601                 /*
 2602                  * Set the loopback flag for outgoing multicast packets.
 2603                  * Must be zero or one.
 2604                  */
 2605                 if (sopt->sopt_valsize != sizeof(u_int)) {
 2606                         error = EINVAL;
 2607                         break;
 2608                 }
 2609                 error = sooptcopyin(sopt, &loop, sizeof(u_int), sizeof(u_int));
 2610                 if (error)
 2611                         break;
 2612                 if (loop > 1) {
 2613                         error = EINVAL;
 2614                         break;
 2615                 }
 2616                 im6o = in6p_findmoptions(inp);
 2617                 im6o->im6o_multicast_loop = loop;
 2618                 INP_WUNLOCK(inp);
 2619                 break;
 2620         }
 2621 
 2622         case IPV6_JOIN_GROUP:
 2623         case MCAST_JOIN_GROUP:
 2624         case MCAST_JOIN_SOURCE_GROUP:
 2625                 error = in6p_join_group(inp, sopt);
 2626                 break;
 2627 
 2628         case IPV6_LEAVE_GROUP:
 2629         case MCAST_LEAVE_GROUP:
 2630         case MCAST_LEAVE_SOURCE_GROUP:
 2631                 error = in6p_leave_group(inp, sopt);
 2632                 break;
 2633 
 2634         case MCAST_BLOCK_SOURCE:
 2635         case MCAST_UNBLOCK_SOURCE:
 2636                 error = in6p_block_unblock_source(inp, sopt);
 2637                 break;
 2638 
 2639         case IPV6_MSFILTER:
 2640                 error = in6p_set_source_filters(inp, sopt);
 2641                 break;
 2642 
 2643         default:
 2644                 error = EOPNOTSUPP;
 2645                 break;
 2646         }
 2647 
 2648         INP_UNLOCK_ASSERT(inp);
 2649 
 2650         return (error);
 2651 }
 2652 
 2653 /*
 2654  * Expose MLD's multicast filter mode and source list(s) to userland,
 2655  * keyed by (ifindex, group).
 2656  * The filter mode is written out as a uint32_t, followed by
 2657  * 0..n of struct in6_addr.
 2658  * For use by ifmcstat(8).
 2659  * SMPng: NOTE: unlocked read of ifindex space.
 2660  */
 2661 static int
 2662 sysctl_ip6_mcast_filters(SYSCTL_HANDLER_ARGS)
 2663 {
 2664         struct in6_addr                  mcaddr;
 2665         struct in6_addr                  src;
 2666         struct ifnet                    *ifp;
 2667         struct ifmultiaddr              *ifma;
 2668         struct in6_multi                *inm;
 2669         struct ip6_msource              *ims;
 2670         int                             *name;
 2671         int                              retval;
 2672         u_int                            namelen;
 2673         uint32_t                         fmode, ifindex;
 2674 #ifdef KTR
 2675         char                             ip6tbuf[INET6_ADDRSTRLEN];
 2676 #endif
 2677 
 2678         name = (int *)arg1;
 2679         namelen = arg2;
 2680 
 2681         if (req->newptr != NULL)
 2682                 return (EPERM);
 2683 
 2684         /* int: ifindex + 4 * 32 bits of IPv6 address */
 2685         if (namelen != 5)
 2686                 return (EINVAL);
 2687 
 2688         ifindex = name[0];
 2689         if (ifindex <= 0 || ifindex > V_if_index) {
 2690                 CTR2(KTR_MLD, "%s: ifindex %u out of range",
 2691                     __func__, ifindex);
 2692                 return (ENOENT);
 2693         }
 2694 
 2695         memcpy(&mcaddr, &name[1], sizeof(struct in6_addr));
 2696         if (!IN6_IS_ADDR_MULTICAST(&mcaddr)) {
 2697                 CTR2(KTR_MLD, "%s: group %s is not multicast",
 2698                     __func__, ip6_sprintf(ip6tbuf, &mcaddr));
 2699                 return (EINVAL);
 2700         }
 2701 
 2702         ifp = ifnet_byindex(ifindex);
 2703         if (ifp == NULL) {
 2704                 CTR2(KTR_MLD, "%s: no ifp for ifindex %u",
 2705                     __func__, ifindex);
 2706                 return (ENOENT);
 2707         }
 2708         /*
 2709          * Internal MLD lookups require that scope/zone ID is set.
 2710          */
 2711         (void)in6_setscope(&mcaddr, ifp, NULL);
 2712 
 2713         retval = sysctl_wire_old_buffer(req,
 2714             sizeof(uint32_t) + (in6_mcast_maxgrpsrc * sizeof(struct in6_addr)));
 2715         if (retval)
 2716                 return (retval);
 2717 
 2718         IN6_MULTI_LOCK();
 2719 
 2720         IF_ADDR_RLOCK(ifp);
 2721         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
 2722                 if (ifma->ifma_addr->sa_family != AF_INET6 ||
 2723                     ifma->ifma_protospec == NULL)
 2724                         continue;
 2725                 inm = (struct in6_multi *)ifma->ifma_protospec;
 2726                 if (!IN6_ARE_ADDR_EQUAL(&inm->in6m_addr, &mcaddr))
 2727                         continue;
 2728                 fmode = inm->in6m_st[1].iss_fmode;
 2729                 retval = SYSCTL_OUT(req, &fmode, sizeof(uint32_t));
 2730                 if (retval != 0)
 2731                         break;
 2732                 RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
 2733                         CTR2(KTR_MLD, "%s: visit node %p", __func__, ims);
 2734                         /*
 2735                          * Only copy-out sources which are in-mode.
 2736                          */
 2737                         if (fmode != im6s_get_mode(inm, ims, 1)) {
 2738                                 CTR1(KTR_MLD, "%s: skip non-in-mode",
 2739                                     __func__);
 2740                                 continue;
 2741                         }
 2742                         src = ims->im6s_addr;
 2743                         retval = SYSCTL_OUT(req, &src,
 2744                             sizeof(struct in6_addr));
 2745                         if (retval != 0)
 2746                                 break;
 2747                 }
 2748         }
 2749         IF_ADDR_RUNLOCK(ifp);
 2750 
 2751         IN6_MULTI_UNLOCK();
 2752 
 2753         return (retval);
 2754 }
 2755 
 2756 #ifdef KTR
 2757 
 2758 static const char *in6m_modestrs[] = { "un", "in", "ex" };
 2759 
 2760 static const char *
 2761 in6m_mode_str(const int mode)
 2762 {
 2763 
 2764         if (mode >= MCAST_UNDEFINED && mode <= MCAST_EXCLUDE)
 2765                 return (in6m_modestrs[mode]);
 2766         return ("??");
 2767 }
 2768 
 2769 static const char *in6m_statestrs[] = {
 2770         "not-member",
 2771         "silent",
 2772         "idle",
 2773         "lazy",
 2774         "sleeping",
 2775         "awakening",
 2776         "query-pending",
 2777         "sg-query-pending",
 2778         "leaving"
 2779 };
 2780 
 2781 static const char *
 2782 in6m_state_str(const int state)
 2783 {
 2784 
 2785         if (state >= MLD_NOT_MEMBER && state <= MLD_LEAVING_MEMBER)
 2786                 return (in6m_statestrs[state]);
 2787         return ("??");
 2788 }
 2789 
 2790 /*
 2791  * Dump an in6_multi structure to the console.
 2792  */
 2793 void
 2794 in6m_print(const struct in6_multi *inm)
 2795 {
 2796         int t;
 2797         char ip6tbuf[INET6_ADDRSTRLEN];
 2798 
 2799         if ((ktr_mask & KTR_MLD) == 0)
 2800                 return;
 2801 
 2802         printf("%s: --- begin in6m %p ---\n", __func__, inm);
 2803         printf("addr %s ifp %p(%s) ifma %p\n",
 2804             ip6_sprintf(ip6tbuf, &inm->in6m_addr),
 2805             inm->in6m_ifp,
 2806             inm->in6m_ifp->if_xname,
 2807             inm->in6m_ifma);
 2808         printf("timer %u state %s refcount %u scq.len %u\n",
 2809             inm->in6m_timer,
 2810             in6m_state_str(inm->in6m_state),
 2811             inm->in6m_refcount,
 2812             inm->in6m_scq.ifq_len);
 2813         printf("mli %p nsrc %lu sctimer %u scrv %u\n",
 2814             inm->in6m_mli,
 2815             inm->in6m_nsrc,
 2816             inm->in6m_sctimer,
 2817             inm->in6m_scrv);
 2818         for (t = 0; t < 2; t++) {
 2819                 printf("t%d: fmode %s asm %u ex %u in %u rec %u\n", t,
 2820                     in6m_mode_str(inm->in6m_st[t].iss_fmode),
 2821                     inm->in6m_st[t].iss_asm,
 2822                     inm->in6m_st[t].iss_ex,
 2823                     inm->in6m_st[t].iss_in,
 2824                     inm->in6m_st[t].iss_rec);
 2825         }
 2826         printf("%s: --- end in6m %p ---\n", __func__, inm);
 2827 }
 2828 
 2829 #else /* !KTR */
 2830 
 2831 void
 2832 in6m_print(const struct in6_multi *inm)
 2833 {
 2834 
 2835 }
 2836 
 2837 #endif /* KTR */

Cache object: 02fc18f0b6ac03415a89e484abd724dd


[ 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.