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