]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/in6_mcast.c
in(6)_mcast: Expand out vnet set / restore macro so that they work in a conditional...
[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         struct vnet *saved_vnet;
528
529         CTR2(KTR_MLD, "%s: refcount is %d", __func__, inm->in6m_refcount);
530
531         MPASS(inm->in6m_refcount == 0);
532         CTR2(KTR_MLD, "%s: freeing inm %p", __func__, inm);
533
534         ifma = inm->in6m_ifma;
535         ifp = inm->in6m_ifp;
536         MPASS(ifma->ifma_llifma == NULL);
537
538         /* XXX this access is not covered by IF_ADDR_LOCK */
539         CTR2(KTR_MLD, "%s: purging ifma %p", __func__, ifma);
540         KASSERT(ifma->ifma_protospec == NULL,
541             ("%s: ifma_protospec != NULL", __func__));
542
543         if (ifp) {
544                 saved_vnet = curvnet;
545                 curvnet = ifp->if_vnet;
546         }
547         in6m_purge(inm);
548         free(inm, M_IP6MADDR);
549
550         if_delmulti_ifma_flags(ifma, 1);
551         if (ifp) {
552                 curvnet = saved_vnet;
553                 if_rele(ifp);
554         }
555 }
556
557 static struct grouptask free_gtask;
558 static struct in6_multi_head in6m_free_list;
559 static void in6m_release_task(void *arg __unused);
560 static void in6m_init(void)
561 {
562         SLIST_INIT(&in6m_free_list);
563         taskqgroup_config_gtask_init(NULL, &free_gtask, in6m_release_task, "in6m release task");
564 }
565
566 SYSINIT(in6m_init, SI_SUB_SMP + 1, SI_ORDER_FIRST,
567         in6m_init, NULL);
568
569
570 void
571 in6m_release_list_deferred(struct in6_multi_head *inmh)
572 {
573         if (SLIST_EMPTY(inmh))
574                 return;
575         mtx_lock(&in6_multi_free_mtx);
576         SLIST_CONCAT(&in6m_free_list, inmh, in6_multi, in6m_nrele);
577         mtx_unlock(&in6_multi_free_mtx);
578         GROUPTASK_ENQUEUE(&free_gtask);
579 }
580
581 void
582 in6m_disconnect(struct in6_multi *inm)
583 {
584         struct ifnet *ifp;
585         struct ifaddr *ifa;
586         struct in6_ifaddr *ifa6;
587         struct in6_multi_mship *imm, *imm_tmp;
588         struct ifmultiaddr *ifma, *ll_ifma;
589
590         ifp = inm->in6m_ifp;
591         IF_ADDR_WLOCK_ASSERT(ifp);
592         ifma = inm->in6m_ifma;
593
594         if_ref(ifp);
595         CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifmultiaddr, ifma_link);
596         MCDPRINTF("removed ifma: %p from %s\n", ifma, ifp->if_xname);
597         if ((ll_ifma = ifma->ifma_llifma) != NULL) {
598                 MPASS(ifma != ll_ifma);
599                 ifma->ifma_llifma = NULL;
600                 MPASS(ll_ifma->ifma_llifma == NULL);
601                 MPASS(ll_ifma->ifma_ifp == ifp);
602                 if (--ll_ifma->ifma_refcount == 0) {
603                         ifma6_restart = true;
604                         CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma, ifmultiaddr, ifma_link);
605                         MCDPRINTF("removed ll_ifma: %p from %s\n", ll_ifma, ifp->if_xname);
606                         if_freemulti(ll_ifma);
607                 }
608         }
609         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
610                 if (ifa->ifa_addr->sa_family != AF_INET6)
611                         continue;
612                 ifa6 = (void *)ifa;
613                 LIST_FOREACH_SAFE(imm, &ifa6->ia6_memberships,
614                     i6mm_chain, imm_tmp) {
615                         if (inm == imm->i6mm_maddr) {
616                                 LIST_REMOVE(imm, i6mm_chain);
617                                 free(imm, M_IP6MADDR);
618                         }
619                 }
620         }
621 }
622
623 void
624 in6m_release_deferred(struct in6_multi *inm)
625 {
626         struct in6_multi_head tmp;
627
628         IN6_MULTI_LIST_LOCK_ASSERT();
629         KASSERT(inm->in6m_refcount > 0, ("refcount == %d inm: %p", inm->in6m_refcount, inm));
630         if (--inm->in6m_refcount == 0) {
631                 in6m_disconnect(inm);
632                 SLIST_INIT(&tmp);
633                 inm->in6m_ifma->ifma_protospec = NULL;
634                 MPASS(inm->in6m_ifma->ifma_llifma == NULL);
635                 SLIST_INSERT_HEAD(&tmp, inm, in6m_nrele);
636                 in6m_release_list_deferred(&tmp);
637         }
638 }
639
640 static void
641 in6m_release_task(void *arg __unused)
642 {
643         struct in6_multi_head in6m_free_tmp;
644         struct in6_multi *inm, *tinm;
645
646         SLIST_INIT(&in6m_free_tmp);
647         mtx_lock(&in6_multi_free_mtx);
648         SLIST_CONCAT(&in6m_free_tmp, &in6m_free_list, in6_multi, in6m_nrele);
649         mtx_unlock(&in6_multi_free_mtx);
650         IN6_MULTI_LOCK();
651         SLIST_FOREACH_SAFE(inm, &in6m_free_tmp, in6m_nrele, tinm) {
652                 SLIST_REMOVE_HEAD(&in6m_free_tmp, in6m_nrele);
653                 in6m_release(inm);
654         }
655         IN6_MULTI_UNLOCK();
656 }
657
658 /*
659  * Clear recorded source entries for a group.
660  * Used by the MLD code. Caller must hold the IN6_MULTI lock.
661  * FIXME: Should reap.
662  */
663 void
664 in6m_clear_recorded(struct in6_multi *inm)
665 {
666         struct ip6_msource      *ims;
667
668         IN6_MULTI_LIST_LOCK_ASSERT();
669
670         RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
671                 if (ims->im6s_stp) {
672                         ims->im6s_stp = 0;
673                         --inm->in6m_st[1].iss_rec;
674                 }
675         }
676         KASSERT(inm->in6m_st[1].iss_rec == 0,
677             ("%s: iss_rec %d not 0", __func__, inm->in6m_st[1].iss_rec));
678 }
679
680 /*
681  * Record a source as pending for a Source-Group MLDv2 query.
682  * This lives here as it modifies the shared tree.
683  *
684  * inm is the group descriptor.
685  * naddr is the address of the source to record in network-byte order.
686  *
687  * If the net.inet6.mld.sgalloc sysctl is non-zero, we will
688  * lazy-allocate a source node in response to an SG query.
689  * Otherwise, no allocation is performed. This saves some memory
690  * with the trade-off that the source will not be reported to the
691  * router if joined in the window between the query response and
692  * the group actually being joined on the local host.
693  *
694  * VIMAGE: XXX: Currently the mld_sgalloc feature has been removed.
695  * This turns off the allocation of a recorded source entry if
696  * the group has not been joined.
697  *
698  * Return 0 if the source didn't exist or was already marked as recorded.
699  * Return 1 if the source was marked as recorded by this function.
700  * Return <0 if any error occurred (negated errno code).
701  */
702 int
703 in6m_record_source(struct in6_multi *inm, const struct in6_addr *addr)
704 {
705         struct ip6_msource       find;
706         struct ip6_msource      *ims, *nims;
707
708         IN6_MULTI_LIST_LOCK_ASSERT();
709
710         find.im6s_addr = *addr;
711         ims = RB_FIND(ip6_msource_tree, &inm->in6m_srcs, &find);
712         if (ims && ims->im6s_stp)
713                 return (0);
714         if (ims == NULL) {
715                 if (inm->in6m_nsrc == in6_mcast_maxgrpsrc)
716                         return (-ENOSPC);
717                 nims = malloc(sizeof(struct ip6_msource), M_IP6MSOURCE,
718                     M_NOWAIT | M_ZERO);
719                 if (nims == NULL)
720                         return (-ENOMEM);
721                 nims->im6s_addr = find.im6s_addr;
722                 RB_INSERT(ip6_msource_tree, &inm->in6m_srcs, nims);
723                 ++inm->in6m_nsrc;
724                 ims = nims;
725         }
726
727         /*
728          * Mark the source as recorded and update the recorded
729          * source count.
730          */
731         ++ims->im6s_stp;
732         ++inm->in6m_st[1].iss_rec;
733
734         return (1);
735 }
736
737 /*
738  * Return a pointer to an in6_msource owned by an in6_mfilter,
739  * given its source address.
740  * Lazy-allocate if needed. If this is a new entry its filter state is
741  * undefined at t0.
742  *
743  * imf is the filter set being modified.
744  * addr is the source address.
745  *
746  * SMPng: May be called with locks held; malloc must not block.
747  */
748 static int
749 im6f_get_source(struct in6_mfilter *imf, const struct sockaddr_in6 *psin,
750     struct in6_msource **plims)
751 {
752         struct ip6_msource       find;
753         struct ip6_msource      *ims, *nims;
754         struct in6_msource      *lims;
755         int                      error;
756
757         error = 0;
758         ims = NULL;
759         lims = NULL;
760
761         find.im6s_addr = psin->sin6_addr;
762         ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
763         lims = (struct in6_msource *)ims;
764         if (lims == NULL) {
765                 if (imf->im6f_nsrc == in6_mcast_maxsocksrc)
766                         return (ENOSPC);
767                 nims = malloc(sizeof(struct in6_msource), M_IN6MFILTER,
768                     M_NOWAIT | M_ZERO);
769                 if (nims == NULL)
770                         return (ENOMEM);
771                 lims = (struct in6_msource *)nims;
772                 lims->im6s_addr = find.im6s_addr;
773                 lims->im6sl_st[0] = MCAST_UNDEFINED;
774                 RB_INSERT(ip6_msource_tree, &imf->im6f_sources, nims);
775                 ++imf->im6f_nsrc;
776         }
777
778         *plims = lims;
779
780         return (error);
781 }
782
783 /*
784  * Graft a source entry into an existing socket-layer filter set,
785  * maintaining any required invariants and checking allocations.
786  *
787  * The source is marked as being in the new filter mode at t1.
788  *
789  * Return the pointer to the new node, otherwise return NULL.
790  */
791 static struct in6_msource *
792 im6f_graft(struct in6_mfilter *imf, const uint8_t st1,
793     const struct sockaddr_in6 *psin)
794 {
795         struct ip6_msource      *nims;
796         struct in6_msource      *lims;
797
798         nims = malloc(sizeof(struct in6_msource), M_IN6MFILTER,
799             M_NOWAIT | M_ZERO);
800         if (nims == NULL)
801                 return (NULL);
802         lims = (struct in6_msource *)nims;
803         lims->im6s_addr = psin->sin6_addr;
804         lims->im6sl_st[0] = MCAST_UNDEFINED;
805         lims->im6sl_st[1] = st1;
806         RB_INSERT(ip6_msource_tree, &imf->im6f_sources, nims);
807         ++imf->im6f_nsrc;
808
809         return (lims);
810 }
811
812 /*
813  * Prune a source entry from an existing socket-layer filter set,
814  * maintaining any required invariants and checking allocations.
815  *
816  * The source is marked as being left at t1, it is not freed.
817  *
818  * Return 0 if no error occurred, otherwise return an errno value.
819  */
820 static int
821 im6f_prune(struct in6_mfilter *imf, const struct sockaddr_in6 *psin)
822 {
823         struct ip6_msource       find;
824         struct ip6_msource      *ims;
825         struct in6_msource      *lims;
826
827         find.im6s_addr = psin->sin6_addr;
828         ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
829         if (ims == NULL)
830                 return (ENOENT);
831         lims = (struct in6_msource *)ims;
832         lims->im6sl_st[1] = MCAST_UNDEFINED;
833         return (0);
834 }
835
836 /*
837  * Revert socket-layer filter set deltas at t1 to t0 state.
838  */
839 static void
840 im6f_rollback(struct in6_mfilter *imf)
841 {
842         struct ip6_msource      *ims, *tims;
843         struct in6_msource      *lims;
844
845         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
846                 lims = (struct in6_msource *)ims;
847                 if (lims->im6sl_st[0] == lims->im6sl_st[1]) {
848                         /* no change at t1 */
849                         continue;
850                 } else if (lims->im6sl_st[0] != MCAST_UNDEFINED) {
851                         /* revert change to existing source at t1 */
852                         lims->im6sl_st[1] = lims->im6sl_st[0];
853                 } else {
854                         /* revert source added t1 */
855                         CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
856                         RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
857                         free(ims, M_IN6MFILTER);
858                         imf->im6f_nsrc--;
859                 }
860         }
861         imf->im6f_st[1] = imf->im6f_st[0];
862 }
863
864 /*
865  * Mark socket-layer filter set as INCLUDE {} at t1.
866  */
867 static void
868 im6f_leave(struct in6_mfilter *imf)
869 {
870         struct ip6_msource      *ims;
871         struct in6_msource      *lims;
872
873         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
874                 lims = (struct in6_msource *)ims;
875                 lims->im6sl_st[1] = MCAST_UNDEFINED;
876         }
877         imf->im6f_st[1] = MCAST_INCLUDE;
878 }
879
880 /*
881  * Mark socket-layer filter set deltas as committed.
882  */
883 static void
884 im6f_commit(struct in6_mfilter *imf)
885 {
886         struct ip6_msource      *ims;
887         struct in6_msource      *lims;
888
889         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
890                 lims = (struct in6_msource *)ims;
891                 lims->im6sl_st[0] = lims->im6sl_st[1];
892         }
893         imf->im6f_st[0] = imf->im6f_st[1];
894 }
895
896 /*
897  * Reap unreferenced sources from socket-layer filter set.
898  */
899 static void
900 im6f_reap(struct in6_mfilter *imf)
901 {
902         struct ip6_msource      *ims, *tims;
903         struct in6_msource      *lims;
904
905         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
906                 lims = (struct in6_msource *)ims;
907                 if ((lims->im6sl_st[0] == MCAST_UNDEFINED) &&
908                     (lims->im6sl_st[1] == MCAST_UNDEFINED)) {
909                         CTR2(KTR_MLD, "%s: free lims %p", __func__, ims);
910                         RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
911                         free(ims, M_IN6MFILTER);
912                         imf->im6f_nsrc--;
913                 }
914         }
915 }
916
917 /*
918  * Purge socket-layer filter set.
919  */
920 static void
921 im6f_purge(struct in6_mfilter *imf)
922 {
923         struct ip6_msource      *ims, *tims;
924
925         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
926                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
927                 RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
928                 free(ims, M_IN6MFILTER);
929                 imf->im6f_nsrc--;
930         }
931         imf->im6f_st[0] = imf->im6f_st[1] = MCAST_UNDEFINED;
932         KASSERT(RB_EMPTY(&imf->im6f_sources),
933             ("%s: im6f_sources not empty", __func__));
934 }
935
936 /*
937  * Look up a source filter entry for a multicast group.
938  *
939  * inm is the group descriptor to work with.
940  * addr is the IPv6 address to look up.
941  * noalloc may be non-zero to suppress allocation of sources.
942  * *pims will be set to the address of the retrieved or allocated source.
943  *
944  * SMPng: NOTE: may be called with locks held.
945  * Return 0 if successful, otherwise return a non-zero error code.
946  */
947 static int
948 in6m_get_source(struct in6_multi *inm, const struct in6_addr *addr,
949     const int noalloc, struct ip6_msource **pims)
950 {
951         struct ip6_msource       find;
952         struct ip6_msource      *ims, *nims;
953 #ifdef KTR
954         char                     ip6tbuf[INET6_ADDRSTRLEN];
955 #endif
956
957         find.im6s_addr = *addr;
958         ims = RB_FIND(ip6_msource_tree, &inm->in6m_srcs, &find);
959         if (ims == NULL && !noalloc) {
960                 if (inm->in6m_nsrc == in6_mcast_maxgrpsrc)
961                         return (ENOSPC);
962                 nims = malloc(sizeof(struct ip6_msource), M_IP6MSOURCE,
963                     M_NOWAIT | M_ZERO);
964                 if (nims == NULL)
965                         return (ENOMEM);
966                 nims->im6s_addr = *addr;
967                 RB_INSERT(ip6_msource_tree, &inm->in6m_srcs, nims);
968                 ++inm->in6m_nsrc;
969                 ims = nims;
970                 CTR3(KTR_MLD, "%s: allocated %s as %p", __func__,
971                     ip6_sprintf(ip6tbuf, addr), ims);
972         }
973
974         *pims = ims;
975         return (0);
976 }
977
978 /*
979  * Merge socket-layer source into MLD-layer source.
980  * If rollback is non-zero, perform the inverse of the merge.
981  */
982 static void
983 im6s_merge(struct ip6_msource *ims, const struct in6_msource *lims,
984     const int rollback)
985 {
986         int n = rollback ? -1 : 1;
987 #ifdef KTR
988         char ip6tbuf[INET6_ADDRSTRLEN];
989
990         ip6_sprintf(ip6tbuf, &lims->im6s_addr);
991 #endif
992
993         if (lims->im6sl_st[0] == MCAST_EXCLUDE) {
994                 CTR3(KTR_MLD, "%s: t1 ex -= %d on %s", __func__, n, ip6tbuf);
995                 ims->im6s_st[1].ex -= n;
996         } else if (lims->im6sl_st[0] == MCAST_INCLUDE) {
997                 CTR3(KTR_MLD, "%s: t1 in -= %d on %s", __func__, n, ip6tbuf);
998                 ims->im6s_st[1].in -= n;
999         }
1000
1001         if (lims->im6sl_st[1] == MCAST_EXCLUDE) {
1002                 CTR3(KTR_MLD, "%s: t1 ex += %d on %s", __func__, n, ip6tbuf);
1003                 ims->im6s_st[1].ex += n;
1004         } else if (lims->im6sl_st[1] == MCAST_INCLUDE) {
1005                 CTR3(KTR_MLD, "%s: t1 in += %d on %s", __func__, n, ip6tbuf);
1006                 ims->im6s_st[1].in += n;
1007         }
1008 }
1009
1010 /*
1011  * Atomically update the global in6_multi state, when a membership's
1012  * filter list is being updated in any way.
1013  *
1014  * imf is the per-inpcb-membership group filter pointer.
1015  * A fake imf may be passed for in-kernel consumers.
1016  *
1017  * XXX This is a candidate for a set-symmetric-difference style loop
1018  * which would eliminate the repeated lookup from root of ims nodes,
1019  * as they share the same key space.
1020  *
1021  * If any error occurred this function will back out of refcounts
1022  * and return a non-zero value.
1023  */
1024 static int
1025 in6m_merge(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
1026 {
1027         struct ip6_msource      *ims, *nims;
1028         struct in6_msource      *lims;
1029         int                      schanged, error;
1030         int                      nsrc0, nsrc1;
1031
1032         schanged = 0;
1033         error = 0;
1034         nsrc1 = nsrc0 = 0;
1035         IN6_MULTI_LIST_LOCK_ASSERT();
1036
1037         /*
1038          * Update the source filters first, as this may fail.
1039          * Maintain count of in-mode filters at t0, t1. These are
1040          * used to work out if we transition into ASM mode or not.
1041          * Maintain a count of source filters whose state was
1042          * actually modified by this operation.
1043          */
1044         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
1045                 lims = (struct in6_msource *)ims;
1046                 if (lims->im6sl_st[0] == imf->im6f_st[0]) nsrc0++;
1047                 if (lims->im6sl_st[1] == imf->im6f_st[1]) nsrc1++;
1048                 if (lims->im6sl_st[0] == lims->im6sl_st[1]) continue;
1049                 error = in6m_get_source(inm, &lims->im6s_addr, 0, &nims);
1050                 ++schanged;
1051                 if (error)
1052                         break;
1053                 im6s_merge(nims, lims, 0);
1054         }
1055         if (error) {
1056                 struct ip6_msource *bims;
1057
1058                 RB_FOREACH_REVERSE_FROM(ims, ip6_msource_tree, nims) {
1059                         lims = (struct in6_msource *)ims;
1060                         if (lims->im6sl_st[0] == lims->im6sl_st[1])
1061                                 continue;
1062                         (void)in6m_get_source(inm, &lims->im6s_addr, 1, &bims);
1063                         if (bims == NULL)
1064                                 continue;
1065                         im6s_merge(bims, lims, 1);
1066                 }
1067                 goto out_reap;
1068         }
1069
1070         CTR3(KTR_MLD, "%s: imf filters in-mode: %d at t0, %d at t1",
1071             __func__, nsrc0, nsrc1);
1072
1073         /* Handle transition between INCLUDE {n} and INCLUDE {} on socket. */
1074         if (imf->im6f_st[0] == imf->im6f_st[1] &&
1075             imf->im6f_st[1] == MCAST_INCLUDE) {
1076                 if (nsrc1 == 0) {
1077                         CTR1(KTR_MLD, "%s: --in on inm at t1", __func__);
1078                         --inm->in6m_st[1].iss_in;
1079                 }
1080         }
1081
1082         /* Handle filter mode transition on socket. */
1083         if (imf->im6f_st[0] != imf->im6f_st[1]) {
1084                 CTR3(KTR_MLD, "%s: imf transition %d to %d",
1085                     __func__, imf->im6f_st[0], imf->im6f_st[1]);
1086
1087                 if (imf->im6f_st[0] == MCAST_EXCLUDE) {
1088                         CTR1(KTR_MLD, "%s: --ex on inm at t1", __func__);
1089                         --inm->in6m_st[1].iss_ex;
1090                 } else if (imf->im6f_st[0] == MCAST_INCLUDE) {
1091                         CTR1(KTR_MLD, "%s: --in on inm at t1", __func__);
1092                         --inm->in6m_st[1].iss_in;
1093                 }
1094
1095                 if (imf->im6f_st[1] == MCAST_EXCLUDE) {
1096                         CTR1(KTR_MLD, "%s: ex++ on inm at t1", __func__);
1097                         inm->in6m_st[1].iss_ex++;
1098                 } else if (imf->im6f_st[1] == MCAST_INCLUDE && nsrc1 > 0) {
1099                         CTR1(KTR_MLD, "%s: in++ on inm at t1", __func__);
1100                         inm->in6m_st[1].iss_in++;
1101                 }
1102         }
1103
1104         /*
1105          * Track inm filter state in terms of listener counts.
1106          * If there are any exclusive listeners, stack-wide
1107          * membership is exclusive.
1108          * Otherwise, if only inclusive listeners, stack-wide is inclusive.
1109          * If no listeners remain, state is undefined at t1,
1110          * and the MLD lifecycle for this group should finish.
1111          */
1112         if (inm->in6m_st[1].iss_ex > 0) {
1113                 CTR1(KTR_MLD, "%s: transition to EX", __func__);
1114                 inm->in6m_st[1].iss_fmode = MCAST_EXCLUDE;
1115         } else if (inm->in6m_st[1].iss_in > 0) {
1116                 CTR1(KTR_MLD, "%s: transition to IN", __func__);
1117                 inm->in6m_st[1].iss_fmode = MCAST_INCLUDE;
1118         } else {
1119                 CTR1(KTR_MLD, "%s: transition to UNDEF", __func__);
1120                 inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
1121         }
1122
1123         /* Decrement ASM listener count on transition out of ASM mode. */
1124         if (imf->im6f_st[0] == MCAST_EXCLUDE && nsrc0 == 0) {
1125                 if ((imf->im6f_st[1] != MCAST_EXCLUDE) ||
1126                     (imf->im6f_st[1] == MCAST_EXCLUDE && nsrc1 > 0)) {
1127                         CTR1(KTR_MLD, "%s: --asm on inm at t1", __func__);
1128                         --inm->in6m_st[1].iss_asm;
1129                 }
1130         }
1131
1132         /* Increment ASM listener count on transition to ASM mode. */
1133         if (imf->im6f_st[1] == MCAST_EXCLUDE && nsrc1 == 0) {
1134                 CTR1(KTR_MLD, "%s: asm++ on inm at t1", __func__);
1135                 inm->in6m_st[1].iss_asm++;
1136         }
1137
1138         CTR3(KTR_MLD, "%s: merged imf %p to inm %p", __func__, imf, inm);
1139         in6m_print(inm);
1140
1141 out_reap:
1142         if (schanged > 0) {
1143                 CTR1(KTR_MLD, "%s: sources changed; reaping", __func__);
1144                 in6m_reap(inm);
1145         }
1146         return (error);
1147 }
1148
1149 /*
1150  * Mark an in6_multi's filter set deltas as committed.
1151  * Called by MLD after a state change has been enqueued.
1152  */
1153 void
1154 in6m_commit(struct in6_multi *inm)
1155 {
1156         struct ip6_msource      *ims;
1157
1158         CTR2(KTR_MLD, "%s: commit inm %p", __func__, inm);
1159         CTR1(KTR_MLD, "%s: pre commit:", __func__);
1160         in6m_print(inm);
1161
1162         RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
1163                 ims->im6s_st[0] = ims->im6s_st[1];
1164         }
1165         inm->in6m_st[0] = inm->in6m_st[1];
1166 }
1167
1168 /*
1169  * Reap unreferenced nodes from an in6_multi's filter set.
1170  */
1171 static void
1172 in6m_reap(struct in6_multi *inm)
1173 {
1174         struct ip6_msource      *ims, *tims;
1175
1176         RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs, tims) {
1177                 if (ims->im6s_st[0].ex > 0 || ims->im6s_st[0].in > 0 ||
1178                     ims->im6s_st[1].ex > 0 || ims->im6s_st[1].in > 0 ||
1179                     ims->im6s_stp != 0)
1180                         continue;
1181                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
1182                 RB_REMOVE(ip6_msource_tree, &inm->in6m_srcs, ims);
1183                 free(ims, M_IP6MSOURCE);
1184                 inm->in6m_nsrc--;
1185         }
1186 }
1187
1188 /*
1189  * Purge all source nodes from an in6_multi's filter set.
1190  */
1191 static void
1192 in6m_purge(struct in6_multi *inm)
1193 {
1194         struct ip6_msource      *ims, *tims;
1195
1196         RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs, tims) {
1197                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
1198                 RB_REMOVE(ip6_msource_tree, &inm->in6m_srcs, ims);
1199                 free(ims, M_IP6MSOURCE);
1200                 inm->in6m_nsrc--;
1201         }
1202         /* Free state-change requests that might be queued. */
1203         mbufq_drain(&inm->in6m_scq);
1204 }
1205
1206 /*
1207  * Join a multicast address w/o sources.
1208  * KAME compatibility entry point.
1209  *
1210  * SMPng: Assume no mc locks held by caller.
1211  */
1212 int
1213 in6_joingroup(struct ifnet *ifp, const struct in6_addr *mcaddr,
1214     /*const*/ struct in6_mfilter *imf, struct in6_multi **pinm,
1215     const int delay)
1216 {
1217         int error;
1218
1219         IN6_MULTI_LOCK();
1220         error = in6_joingroup_locked(ifp, mcaddr, NULL, pinm, delay);
1221         IN6_MULTI_UNLOCK();
1222         return (error);
1223 }
1224
1225 /*
1226  * Join a multicast group; real entry point.
1227  *
1228  * Only preserves atomicity at inm level.
1229  * NOTE: imf argument cannot be const due to sys/tree.h limitations.
1230  *
1231  * If the MLD downcall fails, the group is not joined, and an error
1232  * code is returned.
1233  */
1234 int
1235 in6_joingroup_locked(struct ifnet *ifp, const struct in6_addr *mcaddr,
1236     /*const*/ struct in6_mfilter *imf, struct in6_multi **pinm,
1237     const int delay)
1238 {
1239         struct in6_mfilter       timf;
1240         struct in6_multi        *inm;
1241         struct ifmultiaddr *ifma;
1242         int                      error;
1243 #ifdef KTR
1244         char                     ip6tbuf[INET6_ADDRSTRLEN];
1245 #endif
1246
1247 #ifdef INVARIANTS
1248         /*
1249          * Sanity: Check scope zone ID was set for ifp, if and
1250          * only if group is scoped to an interface.
1251          */
1252         KASSERT(IN6_IS_ADDR_MULTICAST(mcaddr),
1253             ("%s: not a multicast address", __func__));
1254         if (IN6_IS_ADDR_MC_LINKLOCAL(mcaddr) ||
1255             IN6_IS_ADDR_MC_INTFACELOCAL(mcaddr)) {
1256                 KASSERT(mcaddr->s6_addr16[1] != 0,
1257                     ("%s: scope zone ID not set", __func__));
1258         }
1259 #endif
1260
1261         IN6_MULTI_LOCK_ASSERT();
1262         IN6_MULTI_LIST_UNLOCK_ASSERT();
1263
1264         CTR4(KTR_MLD, "%s: join %s on %p(%s))", __func__,
1265             ip6_sprintf(ip6tbuf, mcaddr), ifp, if_name(ifp));
1266
1267         error = 0;
1268         inm = NULL;
1269
1270         /*
1271          * If no imf was specified (i.e. kernel consumer),
1272          * fake one up and assume it is an ASM join.
1273          */
1274         if (imf == NULL) {
1275                 im6f_init(&timf, MCAST_UNDEFINED, MCAST_EXCLUDE);
1276                 imf = &timf;
1277         }
1278         error = in6_getmulti(ifp, mcaddr, &inm);
1279         if (error) {
1280                 CTR1(KTR_MLD, "%s: in6_getmulti() failure", __func__);
1281                 return (error);
1282         }
1283
1284         IN6_MULTI_LIST_LOCK();
1285         CTR1(KTR_MLD, "%s: merge inm state", __func__);
1286         error = in6m_merge(inm, imf);
1287         if (error) {
1288                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
1289                 goto out_in6m_release;
1290         }
1291
1292         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
1293         error = mld_change_state(inm, delay);
1294         if (error) {
1295                 CTR1(KTR_MLD, "%s: failed to update source", __func__);
1296                 goto out_in6m_release;
1297         }
1298
1299 out_in6m_release:
1300         if (error) {
1301                 CTR2(KTR_MLD, "%s: dropping ref on %p", __func__, inm);
1302                 IF_ADDR_RLOCK(ifp);
1303                 CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1304                         if (ifma->ifma_protospec == inm) {
1305                                 ifma->ifma_protospec = NULL;
1306                                 break;
1307                         }
1308                 }
1309                 in6m_release_deferred(inm);
1310                 IF_ADDR_RUNLOCK(ifp);
1311         } else {
1312                 *pinm = inm;
1313         }
1314         IN6_MULTI_LIST_UNLOCK();
1315         return (error);
1316 }
1317
1318 /*
1319  * Leave a multicast group; unlocked entry point.
1320  */
1321 int
1322 in6_leavegroup(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
1323 {
1324         int error;
1325
1326         IN6_MULTI_LOCK();
1327         error = in6_leavegroup_locked(inm, imf);
1328         IN6_MULTI_UNLOCK();
1329         return (error);
1330 }
1331
1332 /*
1333  * Leave a multicast group; real entry point.
1334  * All source filters will be expunged.
1335  *
1336  * Only preserves atomicity at inm level.
1337  *
1338  * Holding the write lock for the INP which contains imf
1339  * is highly advisable. We can't assert for it as imf does not
1340  * contain a back-pointer to the owning inp.
1341  *
1342  * Note: This is not the same as in6m_release(*) as this function also
1343  * makes a state change downcall into MLD.
1344  */
1345 int
1346 in6_leavegroup_locked(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
1347 {
1348         struct in6_mfilter       timf;
1349         struct ifnet *ifp;
1350         int                      error;
1351 #ifdef KTR
1352         char                     ip6tbuf[INET6_ADDRSTRLEN];
1353 #endif
1354
1355         error = 0;
1356
1357         IN6_MULTI_LOCK_ASSERT();
1358
1359         CTR5(KTR_MLD, "%s: leave inm %p, %s/%s, imf %p", __func__,
1360             inm, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
1361             (in6m_is_ifp_detached(inm) ? "null" : if_name(inm->in6m_ifp)),
1362             imf);
1363
1364         /*
1365          * If no imf was specified (i.e. kernel consumer),
1366          * fake one up and assume it is an ASM join.
1367          */
1368         if (imf == NULL) {
1369                 im6f_init(&timf, MCAST_EXCLUDE, MCAST_UNDEFINED);
1370                 imf = &timf;
1371         }
1372
1373         /*
1374          * Begin state merge transaction at MLD layer.
1375          *
1376          * As this particular invocation should not cause any memory
1377          * to be allocated, and there is no opportunity to roll back
1378          * the transaction, it MUST NOT fail.
1379          */
1380
1381         ifp = inm->in6m_ifp;
1382         IN6_MULTI_LIST_LOCK();
1383         CTR1(KTR_MLD, "%s: merge inm state", __func__);
1384         error = in6m_merge(inm, imf);
1385         KASSERT(error == 0, ("%s: failed to merge inm state", __func__));
1386
1387         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
1388         error = mld_change_state(inm, 0);
1389         if (error)
1390                 CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
1391
1392         CTR2(KTR_MLD, "%s: dropping ref on %p", __func__, inm);
1393         if (ifp)
1394                 IF_ADDR_WLOCK(ifp);
1395         in6m_release_deferred(inm);
1396         if (ifp)
1397                 IF_ADDR_WUNLOCK(ifp);
1398         IN6_MULTI_LIST_UNLOCK();
1399
1400         return (error);
1401 }
1402
1403
1404 /*
1405  * Block or unblock an ASM multicast source on an inpcb.
1406  * This implements the delta-based API described in RFC 3678.
1407  *
1408  * The delta-based API applies only to exclusive-mode memberships.
1409  * An MLD downcall will be performed.
1410  *
1411  * SMPng: NOTE: Must take Giant as a join may create a new ifma.
1412  *
1413  * Return 0 if successful, otherwise return an appropriate error code.
1414  */
1415 static int
1416 in6p_block_unblock_source(struct inpcb *inp, struct sockopt *sopt)
1417 {
1418         struct group_source_req          gsr;
1419         sockunion_t                     *gsa, *ssa;
1420         struct ifnet                    *ifp;
1421         struct in6_mfilter              *imf;
1422         struct ip6_moptions             *imo;
1423         struct in6_msource              *ims;
1424         struct in6_multi                        *inm;
1425         size_t                           idx;
1426         uint16_t                         fmode;
1427         int                              error, doblock;
1428 #ifdef KTR
1429         char                             ip6tbuf[INET6_ADDRSTRLEN];
1430 #endif
1431
1432         ifp = NULL;
1433         error = 0;
1434         doblock = 0;
1435
1436         memset(&gsr, 0, sizeof(struct group_source_req));
1437         gsa = (sockunion_t *)&gsr.gsr_group;
1438         ssa = (sockunion_t *)&gsr.gsr_source;
1439
1440         switch (sopt->sopt_name) {
1441         case MCAST_BLOCK_SOURCE:
1442         case MCAST_UNBLOCK_SOURCE:
1443                 error = sooptcopyin(sopt, &gsr,
1444                     sizeof(struct group_source_req),
1445                     sizeof(struct group_source_req));
1446                 if (error)
1447                         return (error);
1448
1449                 if (gsa->sin6.sin6_family != AF_INET6 ||
1450                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
1451                         return (EINVAL);
1452
1453                 if (ssa->sin6.sin6_family != AF_INET6 ||
1454                     ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
1455                         return (EINVAL);
1456
1457                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
1458                         return (EADDRNOTAVAIL);
1459
1460                 ifp = ifnet_byindex(gsr.gsr_interface);
1461
1462                 if (sopt->sopt_name == MCAST_BLOCK_SOURCE)
1463                         doblock = 1;
1464                 break;
1465
1466         default:
1467                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
1468                     __func__, sopt->sopt_name);
1469                 return (EOPNOTSUPP);
1470                 break;
1471         }
1472
1473         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
1474                 return (EINVAL);
1475
1476         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
1477
1478         /*
1479          * Check if we are actually a member of this group.
1480          */
1481         imo = in6p_findmoptions(inp);
1482         idx = im6o_match_group(imo, ifp, &gsa->sa);
1483         if (idx == -1 || imo->im6o_mfilters == NULL) {
1484                 error = EADDRNOTAVAIL;
1485                 goto out_in6p_locked;
1486         }
1487
1488         KASSERT(imo->im6o_mfilters != NULL,
1489             ("%s: im6o_mfilters not allocated", __func__));
1490         imf = &imo->im6o_mfilters[idx];
1491         inm = imo->im6o_membership[idx];
1492
1493         /*
1494          * Attempting to use the delta-based API on an
1495          * non exclusive-mode membership is an error.
1496          */
1497         fmode = imf->im6f_st[0];
1498         if (fmode != MCAST_EXCLUDE) {
1499                 error = EINVAL;
1500                 goto out_in6p_locked;
1501         }
1502
1503         /*
1504          * Deal with error cases up-front:
1505          *  Asked to block, but already blocked; or
1506          *  Asked to unblock, but nothing to unblock.
1507          * If adding a new block entry, allocate it.
1508          */
1509         ims = im6o_match_source(imo, idx, &ssa->sa);
1510         if ((ims != NULL && doblock) || (ims == NULL && !doblock)) {
1511                 CTR3(KTR_MLD, "%s: source %s %spresent", __func__,
1512                     ip6_sprintf(ip6tbuf, &ssa->sin6.sin6_addr),
1513                     doblock ? "" : "not ");
1514                 error = EADDRNOTAVAIL;
1515                 goto out_in6p_locked;
1516         }
1517
1518         INP_WLOCK_ASSERT(inp);
1519
1520         /*
1521          * Begin state merge transaction at socket layer.
1522          */
1523         if (doblock) {
1524                 CTR2(KTR_MLD, "%s: %s source", __func__, "block");
1525                 ims = im6f_graft(imf, fmode, &ssa->sin6);
1526                 if (ims == NULL)
1527                         error = ENOMEM;
1528         } else {
1529                 CTR2(KTR_MLD, "%s: %s source", __func__, "allow");
1530                 error = im6f_prune(imf, &ssa->sin6);
1531         }
1532
1533         if (error) {
1534                 CTR1(KTR_MLD, "%s: merge imf state failed", __func__);
1535                 goto out_im6f_rollback;
1536         }
1537
1538         /*
1539          * Begin state merge transaction at MLD layer.
1540          */
1541         IN6_MULTI_LIST_LOCK();
1542         CTR1(KTR_MLD, "%s: merge inm state", __func__);
1543         error = in6m_merge(inm, imf);
1544         if (error)
1545                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
1546         else {
1547                 CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
1548                 error = mld_change_state(inm, 0);
1549                 if (error)
1550                         CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
1551         }
1552
1553         IN6_MULTI_LIST_UNLOCK();
1554
1555 out_im6f_rollback:
1556         if (error)
1557                 im6f_rollback(imf);
1558         else
1559                 im6f_commit(imf);
1560
1561         im6f_reap(imf);
1562
1563 out_in6p_locked:
1564         INP_WUNLOCK(inp);
1565         return (error);
1566 }
1567
1568 /*
1569  * Given an inpcb, return its multicast options structure pointer.  Accepts
1570  * an unlocked inpcb pointer, but will return it locked.  May sleep.
1571  *
1572  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
1573  * SMPng: NOTE: Returns with the INP write lock held.
1574  */
1575 static struct ip6_moptions *
1576 in6p_findmoptions(struct inpcb *inp)
1577 {
1578         struct ip6_moptions      *imo;
1579         struct in6_multi                **immp;
1580         struct in6_mfilter       *imfp;
1581         size_t                    idx;
1582
1583         INP_WLOCK(inp);
1584         if (inp->in6p_moptions != NULL)
1585                 return (inp->in6p_moptions);
1586
1587         INP_WUNLOCK(inp);
1588
1589         imo = malloc(sizeof(*imo), M_IP6MOPTS, M_WAITOK);
1590         immp = malloc(sizeof(*immp) * IPV6_MIN_MEMBERSHIPS, M_IP6MOPTS,
1591             M_WAITOK | M_ZERO);
1592         imfp = malloc(sizeof(struct in6_mfilter) * IPV6_MIN_MEMBERSHIPS,
1593             M_IN6MFILTER, M_WAITOK);
1594
1595         imo->im6o_multicast_ifp = NULL;
1596         imo->im6o_multicast_hlim = V_ip6_defmcasthlim;
1597         imo->im6o_multicast_loop = in6_mcast_loop;
1598         imo->im6o_num_memberships = 0;
1599         imo->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
1600         imo->im6o_membership = immp;
1601
1602         /* Initialize per-group source filters. */
1603         for (idx = 0; idx < IPV6_MIN_MEMBERSHIPS; idx++)
1604                 im6f_init(&imfp[idx], MCAST_UNDEFINED, MCAST_EXCLUDE);
1605         imo->im6o_mfilters = imfp;
1606
1607         INP_WLOCK(inp);
1608         if (inp->in6p_moptions != NULL) {
1609                 free(imfp, M_IN6MFILTER);
1610                 free(immp, M_IP6MOPTS);
1611                 free(imo, M_IP6MOPTS);
1612                 return (inp->in6p_moptions);
1613         }
1614         inp->in6p_moptions = imo;
1615         return (imo);
1616 }
1617
1618 /*
1619  * Discard the IPv6 multicast options (and source filters).
1620  *
1621  * SMPng: NOTE: assumes INP write lock is held.
1622  *
1623  * XXX can all be safely deferred to epoch_call
1624  *
1625  */
1626
1627 static void
1628 inp_gcmoptions(epoch_context_t ctx)
1629 {
1630         struct ip6_moptions *imo;
1631         struct in6_mfilter      *imf;
1632         struct in6_multi *inm;
1633         struct ifnet *ifp;
1634         struct vnet *saved_vnet;
1635         size_t                   idx, nmships;
1636
1637         imo =  __containerof(ctx, struct ip6_moptions, imo6_epoch_ctx);
1638
1639         nmships = imo->im6o_num_memberships;
1640         for (idx = 0; idx < nmships; ++idx) {
1641                 imf = imo->im6o_mfilters ? &imo->im6o_mfilters[idx] : NULL;
1642                 if (imf)
1643                         im6f_leave(imf);
1644                 inm = imo->im6o_membership[idx];
1645                 ifp = inm->in6m_ifp;
1646                 if (ifp) {
1647                         saved_vnet = curvnet;
1648                         curvnet = ifp->if_vnet;
1649                 }                       
1650                 (void)in6_leavegroup(inm, imf);
1651                 if (ifp)
1652                         curvnet = saved_vnet;
1653                 if (imf)
1654                         im6f_purge(imf);
1655         }
1656
1657         if (imo->im6o_mfilters)
1658                 free(imo->im6o_mfilters, M_IN6MFILTER);
1659         free(imo->im6o_membership, M_IP6MOPTS);
1660         free(imo, M_IP6MOPTS);
1661 }
1662
1663 void
1664 ip6_freemoptions(struct ip6_moptions *imo)
1665 {
1666         if (imo == NULL)
1667                 return;
1668         epoch_call(net_epoch_preempt, &imo->imo6_epoch_ctx, inp_gcmoptions);
1669 }
1670
1671 /*
1672  * Atomically get source filters on a socket for an IPv6 multicast group.
1673  * Called with INP lock held; returns with lock released.
1674  */
1675 static int
1676 in6p_get_source_filters(struct inpcb *inp, struct sockopt *sopt)
1677 {
1678         struct __msfilterreq     msfr;
1679         sockunion_t             *gsa;
1680         struct ifnet            *ifp;
1681         struct ip6_moptions     *imo;
1682         struct in6_mfilter      *imf;
1683         struct ip6_msource      *ims;
1684         struct in6_msource      *lims;
1685         struct sockaddr_in6     *psin;
1686         struct sockaddr_storage *ptss;
1687         struct sockaddr_storage *tss;
1688         int                      error;
1689         size_t                   idx, nsrcs, ncsrcs;
1690
1691         INP_WLOCK_ASSERT(inp);
1692
1693         imo = inp->in6p_moptions;
1694         KASSERT(imo != NULL, ("%s: null ip6_moptions", __func__));
1695
1696         INP_WUNLOCK(inp);
1697
1698         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
1699             sizeof(struct __msfilterreq));
1700         if (error)
1701                 return (error);
1702
1703         if (msfr.msfr_group.ss_family != AF_INET6 ||
1704             msfr.msfr_group.ss_len != sizeof(struct sockaddr_in6))
1705                 return (EINVAL);
1706
1707         gsa = (sockunion_t *)&msfr.msfr_group;
1708         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
1709                 return (EINVAL);
1710
1711         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
1712                 return (EADDRNOTAVAIL);
1713         ifp = ifnet_byindex(msfr.msfr_ifindex);
1714         if (ifp == NULL)
1715                 return (EADDRNOTAVAIL);
1716         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
1717
1718         INP_WLOCK(inp);
1719
1720         /*
1721          * Lookup group on the socket.
1722          */
1723         idx = im6o_match_group(imo, ifp, &gsa->sa);
1724         if (idx == -1 || imo->im6o_mfilters == NULL) {
1725                 INP_WUNLOCK(inp);
1726                 return (EADDRNOTAVAIL);
1727         }
1728         imf = &imo->im6o_mfilters[idx];
1729
1730         /*
1731          * Ignore memberships which are in limbo.
1732          */
1733         if (imf->im6f_st[1] == MCAST_UNDEFINED) {
1734                 INP_WUNLOCK(inp);
1735                 return (EAGAIN);
1736         }
1737         msfr.msfr_fmode = imf->im6f_st[1];
1738
1739         /*
1740          * If the user specified a buffer, copy out the source filter
1741          * entries to userland gracefully.
1742          * We only copy out the number of entries which userland
1743          * has asked for, but we always tell userland how big the
1744          * buffer really needs to be.
1745          */
1746         if (msfr.msfr_nsrcs > in6_mcast_maxsocksrc)
1747                 msfr.msfr_nsrcs = in6_mcast_maxsocksrc;
1748         tss = NULL;
1749         if (msfr.msfr_srcs != NULL && msfr.msfr_nsrcs > 0) {
1750                 tss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
1751                     M_TEMP, M_NOWAIT | M_ZERO);
1752                 if (tss == NULL) {
1753                         INP_WUNLOCK(inp);
1754                         return (ENOBUFS);
1755                 }
1756         }
1757
1758         /*
1759          * Count number of sources in-mode at t0.
1760          * If buffer space exists and remains, copy out source entries.
1761          */
1762         nsrcs = msfr.msfr_nsrcs;
1763         ncsrcs = 0;
1764         ptss = tss;
1765         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
1766                 lims = (struct in6_msource *)ims;
1767                 if (lims->im6sl_st[0] == MCAST_UNDEFINED ||
1768                     lims->im6sl_st[0] != imf->im6f_st[0])
1769                         continue;
1770                 ++ncsrcs;
1771                 if (tss != NULL && nsrcs > 0) {
1772                         psin = (struct sockaddr_in6 *)ptss;
1773                         psin->sin6_family = AF_INET6;
1774                         psin->sin6_len = sizeof(struct sockaddr_in6);
1775                         psin->sin6_addr = lims->im6s_addr;
1776                         psin->sin6_port = 0;
1777                         --nsrcs;
1778                         ++ptss;
1779                 }
1780         }
1781
1782         INP_WUNLOCK(inp);
1783
1784         if (tss != NULL) {
1785                 error = copyout(tss, msfr.msfr_srcs,
1786                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
1787                 free(tss, M_TEMP);
1788                 if (error)
1789                         return (error);
1790         }
1791
1792         msfr.msfr_nsrcs = ncsrcs;
1793         error = sooptcopyout(sopt, &msfr, sizeof(struct __msfilterreq));
1794
1795         return (error);
1796 }
1797
1798 /*
1799  * Return the IP multicast options in response to user getsockopt().
1800  */
1801 int
1802 ip6_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1803 {
1804         struct ip6_moptions     *im6o;
1805         int                      error;
1806         u_int                    optval;
1807
1808         INP_WLOCK(inp);
1809         im6o = inp->in6p_moptions;
1810         /*
1811          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
1812          * or is a divert socket, reject it.
1813          */
1814         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
1815             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
1816             inp->inp_socket->so_proto->pr_type != SOCK_DGRAM)) {
1817                 INP_WUNLOCK(inp);
1818                 return (EOPNOTSUPP);
1819         }
1820
1821         error = 0;
1822         switch (sopt->sopt_name) {
1823         case IPV6_MULTICAST_IF:
1824                 if (im6o == NULL || im6o->im6o_multicast_ifp == NULL) {
1825                         optval = 0;
1826                 } else {
1827                         optval = im6o->im6o_multicast_ifp->if_index;
1828                 }
1829                 INP_WUNLOCK(inp);
1830                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
1831                 break;
1832
1833         case IPV6_MULTICAST_HOPS:
1834                 if (im6o == NULL)
1835                         optval = V_ip6_defmcasthlim;
1836                 else
1837                         optval = im6o->im6o_multicast_hlim;
1838                 INP_WUNLOCK(inp);
1839                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
1840                 break;
1841
1842         case IPV6_MULTICAST_LOOP:
1843                 if (im6o == NULL)
1844                         optval = in6_mcast_loop; /* XXX VIMAGE */
1845                 else
1846                         optval = im6o->im6o_multicast_loop;
1847                 INP_WUNLOCK(inp);
1848                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
1849                 break;
1850
1851         case IPV6_MSFILTER:
1852                 if (im6o == NULL) {
1853                         error = EADDRNOTAVAIL;
1854                         INP_WUNLOCK(inp);
1855                 } else {
1856                         error = in6p_get_source_filters(inp, sopt);
1857                 }
1858                 break;
1859
1860         default:
1861                 INP_WUNLOCK(inp);
1862                 error = ENOPROTOOPT;
1863                 break;
1864         }
1865
1866         INP_UNLOCK_ASSERT(inp);
1867
1868         return (error);
1869 }
1870
1871 /*
1872  * Look up the ifnet to use for a multicast group membership,
1873  * given the address of an IPv6 group.
1874  *
1875  * This routine exists to support legacy IPv6 multicast applications.
1876  *
1877  * If inp is non-NULL, use this socket's current FIB number for any
1878  * required FIB lookup. Look up the group address in the unicast FIB,
1879  * and use its ifp; usually, this points to the default next-hop.
1880  * If the FIB lookup fails, return NULL.
1881  *
1882  * FUTURE: Support multiple forwarding tables for IPv6.
1883  *
1884  * Returns NULL if no ifp could be found.
1885  */
1886 static struct ifnet *
1887 in6p_lookup_mcast_ifp(const struct inpcb *in6p,
1888     const struct sockaddr_in6 *gsin6)
1889 {
1890         struct nhop6_basic      nh6;
1891         struct in6_addr         dst;
1892         uint32_t                scopeid;
1893         uint32_t                fibnum;
1894
1895         KASSERT(in6p->inp_vflag & INP_IPV6,
1896             ("%s: not INP_IPV6 inpcb", __func__));
1897         KASSERT(gsin6->sin6_family == AF_INET6,
1898             ("%s: not AF_INET6 group", __func__));
1899
1900         in6_splitscope(&gsin6->sin6_addr, &dst, &scopeid);
1901         fibnum = in6p ? in6p->inp_inc.inc_fibnum : RT_DEFAULT_FIB;
1902         if (fib6_lookup_nh_basic(fibnum, &dst, scopeid, 0, 0, &nh6) != 0)
1903                 return (NULL);
1904
1905         return (nh6.nh_ifp);
1906 }
1907
1908 /*
1909  * Join an IPv6 multicast group, possibly with a source.
1910  *
1911  * FIXME: The KAME use of the unspecified address (::)
1912  * to join *all* multicast groups is currently unsupported.
1913  */
1914 static int
1915 in6p_join_group(struct inpcb *inp, struct sockopt *sopt)
1916 {
1917         struct group_source_req          gsr;
1918         sockunion_t                     *gsa, *ssa;
1919         struct ifnet                    *ifp;
1920         struct in6_mfilter              *imf;
1921         struct ip6_moptions             *imo;
1922         struct in6_multi                *inm;
1923         struct in6_msource              *lims;
1924         size_t                           idx;
1925         int                              error, is_new;
1926
1927         ifp = NULL;
1928         imf = NULL;
1929         lims = NULL;
1930         error = 0;
1931         is_new = 0;
1932
1933         memset(&gsr, 0, sizeof(struct group_source_req));
1934         gsa = (sockunion_t *)&gsr.gsr_group;
1935         gsa->ss.ss_family = AF_UNSPEC;
1936         ssa = (sockunion_t *)&gsr.gsr_source;
1937         ssa->ss.ss_family = AF_UNSPEC;
1938
1939         /*
1940          * Chew everything into struct group_source_req.
1941          * Overwrite the port field if present, as the sockaddr
1942          * being copied in may be matched with a binary comparison.
1943          * Ignore passed-in scope ID.
1944          */
1945         switch (sopt->sopt_name) {
1946         case IPV6_JOIN_GROUP: {
1947                 struct ipv6_mreq mreq;
1948
1949                 error = sooptcopyin(sopt, &mreq, sizeof(struct ipv6_mreq),
1950                     sizeof(struct ipv6_mreq));
1951                 if (error)
1952                         return (error);
1953
1954                 gsa->sin6.sin6_family = AF_INET6;
1955                 gsa->sin6.sin6_len = sizeof(struct sockaddr_in6);
1956                 gsa->sin6.sin6_addr = mreq.ipv6mr_multiaddr;
1957
1958                 if (mreq.ipv6mr_interface == 0) {
1959                         ifp = in6p_lookup_mcast_ifp(inp, &gsa->sin6);
1960                 } else {
1961                         if (V_if_index < mreq.ipv6mr_interface)
1962                                 return (EADDRNOTAVAIL);
1963                         ifp = ifnet_byindex(mreq.ipv6mr_interface);
1964                 }
1965                 CTR3(KTR_MLD, "%s: ipv6mr_interface = %d, ifp = %p",
1966                     __func__, mreq.ipv6mr_interface, ifp);
1967         } break;
1968
1969         case MCAST_JOIN_GROUP:
1970         case MCAST_JOIN_SOURCE_GROUP:
1971                 if (sopt->sopt_name == MCAST_JOIN_GROUP) {
1972                         error = sooptcopyin(sopt, &gsr,
1973                             sizeof(struct group_req),
1974                             sizeof(struct group_req));
1975                 } else if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
1976                         error = sooptcopyin(sopt, &gsr,
1977                             sizeof(struct group_source_req),
1978                             sizeof(struct group_source_req));
1979                 }
1980                 if (error)
1981                         return (error);
1982
1983                 if (gsa->sin6.sin6_family != AF_INET6 ||
1984                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
1985                         return (EINVAL);
1986
1987                 if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
1988                         if (ssa->sin6.sin6_family != AF_INET6 ||
1989                             ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
1990                                 return (EINVAL);
1991                         if (IN6_IS_ADDR_MULTICAST(&ssa->sin6.sin6_addr))
1992                                 return (EINVAL);
1993                         /*
1994                          * TODO: Validate embedded scope ID in source
1995                          * list entry against passed-in ifp, if and only
1996                          * if source list filter entry is iface or node local.
1997                          */
1998                         in6_clearscope(&ssa->sin6.sin6_addr);
1999                         ssa->sin6.sin6_port = 0;
2000                         ssa->sin6.sin6_scope_id = 0;
2001                 }
2002
2003                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
2004                         return (EADDRNOTAVAIL);
2005                 ifp = ifnet_byindex(gsr.gsr_interface);
2006                 break;
2007
2008         default:
2009                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
2010                     __func__, sopt->sopt_name);
2011                 return (EOPNOTSUPP);
2012                 break;
2013         }
2014
2015         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
2016                 return (EINVAL);
2017
2018         if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0)
2019                 return (EADDRNOTAVAIL);
2020
2021         gsa->sin6.sin6_port = 0;
2022         gsa->sin6.sin6_scope_id = 0;
2023
2024         /*
2025          * Always set the scope zone ID on memberships created from userland.
2026          * Use the passed-in ifp to do this.
2027          * XXX The in6_setscope() return value is meaningless.
2028          * XXX SCOPE6_LOCK() is taken by in6_setscope().
2029          */
2030         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
2031
2032         imo = in6p_findmoptions(inp);
2033         idx = im6o_match_group(imo, ifp, &gsa->sa);
2034         if (idx == -1) {
2035                 is_new = 1;
2036         } else {
2037                 inm = imo->im6o_membership[idx];
2038                 imf = &imo->im6o_mfilters[idx];
2039                 if (ssa->ss.ss_family != AF_UNSPEC) {
2040                         /*
2041                          * MCAST_JOIN_SOURCE_GROUP on an exclusive membership
2042                          * is an error. On an existing inclusive membership,
2043                          * it just adds the source to the filter list.
2044                          */
2045                         if (imf->im6f_st[1] != MCAST_INCLUDE) {
2046                                 error = EINVAL;
2047                                 goto out_in6p_locked;
2048                         }
2049                         /*
2050                          * Throw out duplicates.
2051                          *
2052                          * XXX FIXME: This makes a naive assumption that
2053                          * even if entries exist for *ssa in this imf,
2054                          * they will be rejected as dupes, even if they
2055                          * are not valid in the current mode (in-mode).
2056                          *
2057                          * in6_msource is transactioned just as for anything
2058                          * else in SSM -- but note naive use of in6m_graft()
2059                          * below for allocating new filter entries.
2060                          *
2061                          * This is only an issue if someone mixes the
2062                          * full-state SSM API with the delta-based API,
2063                          * which is discouraged in the relevant RFCs.
2064                          */
2065                         lims = im6o_match_source(imo, idx, &ssa->sa);
2066                         if (lims != NULL /*&&
2067                             lims->im6sl_st[1] == MCAST_INCLUDE*/) {
2068                                 error = EADDRNOTAVAIL;
2069                                 goto out_in6p_locked;
2070                         }
2071                 } else {
2072                         /*
2073                          * MCAST_JOIN_GROUP alone, on any existing membership,
2074                          * is rejected, to stop the same inpcb tying up
2075                          * multiple refs to the in_multi.
2076                          * On an existing inclusive membership, this is also
2077                          * an error; if you want to change filter mode,
2078                          * you must use the userland API setsourcefilter().
2079                          * XXX We don't reject this for imf in UNDEFINED
2080                          * state at t1, because allocation of a filter
2081                          * is atomic with allocation of a membership.
2082                          */
2083                         error = EINVAL;
2084                         goto out_in6p_locked;
2085                 }
2086         }
2087
2088         /*
2089          * Begin state merge transaction at socket layer.
2090          */
2091         INP_WLOCK_ASSERT(inp);
2092
2093         if (is_new) {
2094                 if (imo->im6o_num_memberships == imo->im6o_max_memberships) {
2095                         error = im6o_grow(imo);
2096                         if (error)
2097                                 goto out_in6p_locked;
2098                 }
2099                 /*
2100                  * Allocate the new slot upfront so we can deal with
2101                  * grafting the new source filter in same code path
2102                  * as for join-source on existing membership.
2103                  */
2104                 idx = imo->im6o_num_memberships;
2105                 imo->im6o_membership[idx] = NULL;
2106                 imo->im6o_num_memberships++;
2107                 KASSERT(imo->im6o_mfilters != NULL,
2108                     ("%s: im6f_mfilters vector was not allocated", __func__));
2109                 imf = &imo->im6o_mfilters[idx];
2110                 KASSERT(RB_EMPTY(&imf->im6f_sources),
2111                     ("%s: im6f_sources not empty", __func__));
2112         }
2113
2114         /*
2115          * Graft new source into filter list for this inpcb's
2116          * membership of the group. The in6_multi may not have
2117          * been allocated yet if this is a new membership, however,
2118          * the in_mfilter slot will be allocated and must be initialized.
2119          *
2120          * Note: Grafting of exclusive mode filters doesn't happen
2121          * in this path.
2122          * XXX: Should check for non-NULL lims (node exists but may
2123          * not be in-mode) for interop with full-state API.
2124          */
2125         if (ssa->ss.ss_family != AF_UNSPEC) {
2126                 /* Membership starts in IN mode */
2127                 if (is_new) {
2128                         CTR1(KTR_MLD, "%s: new join w/source", __func__);
2129                         im6f_init(imf, MCAST_UNDEFINED, MCAST_INCLUDE);
2130                 } else {
2131                         CTR2(KTR_MLD, "%s: %s source", __func__, "allow");
2132                 }
2133                 lims = im6f_graft(imf, MCAST_INCLUDE, &ssa->sin6);
2134                 if (lims == NULL) {
2135                         CTR1(KTR_MLD, "%s: merge imf state failed",
2136                             __func__);
2137                         error = ENOMEM;
2138                         goto out_im6o_free;
2139                 }
2140         } else {
2141                 /* No address specified; Membership starts in EX mode */
2142                 if (is_new) {
2143                         CTR1(KTR_MLD, "%s: new join w/o source", __func__);
2144                         im6f_init(imf, MCAST_UNDEFINED, MCAST_EXCLUDE);
2145                 }
2146         }
2147
2148         /*
2149          * Begin state merge transaction at MLD layer.
2150          */
2151         in_pcbref(inp);
2152         INP_WUNLOCK(inp);
2153         IN6_MULTI_LOCK();
2154
2155         if (is_new) {
2156                 error = in6_joingroup_locked(ifp, &gsa->sin6.sin6_addr, imf,
2157                     &inm, 0);
2158                 if (error) {
2159                         IN6_MULTI_UNLOCK();
2160                         goto out_im6o_free;
2161                 }
2162                 imo->im6o_membership[idx] = inm;
2163         } else {
2164                 CTR1(KTR_MLD, "%s: merge inm state", __func__);
2165                 IN6_MULTI_LIST_LOCK();
2166                 error = in6m_merge(inm, imf);
2167                 if (error)
2168                         CTR1(KTR_MLD, "%s: failed to merge inm state",
2169                             __func__);
2170                 else {
2171                         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
2172                         error = mld_change_state(inm, 0);
2173                         if (error)
2174                                 CTR1(KTR_MLD, "%s: failed mld downcall",
2175                                     __func__);
2176                 }
2177                 IN6_MULTI_LIST_UNLOCK();
2178         }
2179
2180         IN6_MULTI_UNLOCK();
2181         INP_WLOCK(inp);
2182         if (in_pcbrele_wlocked(inp))
2183                 return (ENXIO);
2184         if (error) {
2185                 im6f_rollback(imf);
2186                 if (is_new)
2187                         im6f_purge(imf);
2188                 else
2189                         im6f_reap(imf);
2190         } else {
2191                 im6f_commit(imf);
2192         }
2193
2194 out_im6o_free:
2195         if (error && is_new) {
2196                 imo->im6o_membership[idx] = NULL;
2197                 --imo->im6o_num_memberships;
2198         }
2199
2200 out_in6p_locked:
2201         INP_WUNLOCK(inp);
2202         return (error);
2203 }
2204
2205 /*
2206  * Leave an IPv6 multicast group on an inpcb, possibly with a source.
2207  */
2208 static int
2209 in6p_leave_group(struct inpcb *inp, struct sockopt *sopt)
2210 {
2211         struct ipv6_mreq                 mreq;
2212         struct group_source_req          gsr;
2213         sockunion_t                     *gsa, *ssa;
2214         struct ifnet                    *ifp;
2215         struct in6_mfilter              *imf;
2216         struct ip6_moptions             *imo;
2217         struct in6_msource              *ims;
2218         struct in6_multi                *inm;
2219         uint32_t                         ifindex;
2220         size_t                           idx;
2221         int                              error, is_final;
2222 #ifdef KTR
2223         char                             ip6tbuf[INET6_ADDRSTRLEN];
2224 #endif
2225
2226         ifp = NULL;
2227         ifindex = 0;
2228         error = 0;
2229         is_final = 1;
2230
2231         memset(&gsr, 0, sizeof(struct group_source_req));
2232         gsa = (sockunion_t *)&gsr.gsr_group;
2233         gsa->ss.ss_family = AF_UNSPEC;
2234         ssa = (sockunion_t *)&gsr.gsr_source;
2235         ssa->ss.ss_family = AF_UNSPEC;
2236
2237         /*
2238          * Chew everything passed in up into a struct group_source_req
2239          * as that is easier to process.
2240          * Note: Any embedded scope ID in the multicast group passed
2241          * in by userland is ignored, the interface index is the recommended
2242          * mechanism to specify an interface; see below.
2243          */
2244         switch (sopt->sopt_name) {
2245         case IPV6_LEAVE_GROUP:
2246                 error = sooptcopyin(sopt, &mreq, sizeof(struct ipv6_mreq),
2247                     sizeof(struct ipv6_mreq));
2248                 if (error)
2249                         return (error);
2250                 gsa->sin6.sin6_family = AF_INET6;
2251                 gsa->sin6.sin6_len = sizeof(struct sockaddr_in6);
2252                 gsa->sin6.sin6_addr = mreq.ipv6mr_multiaddr;
2253                 gsa->sin6.sin6_port = 0;
2254                 gsa->sin6.sin6_scope_id = 0;
2255                 ifindex = mreq.ipv6mr_interface;
2256                 break;
2257
2258         case MCAST_LEAVE_GROUP:
2259         case MCAST_LEAVE_SOURCE_GROUP:
2260                 if (sopt->sopt_name == MCAST_LEAVE_GROUP) {
2261                         error = sooptcopyin(sopt, &gsr,
2262                             sizeof(struct group_req),
2263                             sizeof(struct group_req));
2264                 } else if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2265                         error = sooptcopyin(sopt, &gsr,
2266                             sizeof(struct group_source_req),
2267                             sizeof(struct group_source_req));
2268                 }
2269                 if (error)
2270                         return (error);
2271
2272                 if (gsa->sin6.sin6_family != AF_INET6 ||
2273                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
2274                         return (EINVAL);
2275                 if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2276                         if (ssa->sin6.sin6_family != AF_INET6 ||
2277                             ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
2278                                 return (EINVAL);
2279                         if (IN6_IS_ADDR_MULTICAST(&ssa->sin6.sin6_addr))
2280                                 return (EINVAL);
2281                         /*
2282                          * TODO: Validate embedded scope ID in source
2283                          * list entry against passed-in ifp, if and only
2284                          * if source list filter entry is iface or node local.
2285                          */
2286                         in6_clearscope(&ssa->sin6.sin6_addr);
2287                 }
2288                 gsa->sin6.sin6_port = 0;
2289                 gsa->sin6.sin6_scope_id = 0;
2290                 ifindex = gsr.gsr_interface;
2291                 break;
2292
2293         default:
2294                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
2295                     __func__, sopt->sopt_name);
2296                 return (EOPNOTSUPP);
2297                 break;
2298         }
2299
2300         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
2301                 return (EINVAL);
2302
2303         /*
2304          * Validate interface index if provided. If no interface index
2305          * was provided separately, attempt to look the membership up
2306          * from the default scope as a last resort to disambiguate
2307          * the membership we are being asked to leave.
2308          * XXX SCOPE6 lock potentially taken here.
2309          */
2310         if (ifindex != 0) {
2311                 if (V_if_index < ifindex)
2312                         return (EADDRNOTAVAIL);
2313                 ifp = ifnet_byindex(ifindex);
2314                 if (ifp == NULL)
2315                         return (EADDRNOTAVAIL);
2316                 (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
2317         } else {
2318                 error = sa6_embedscope(&gsa->sin6, V_ip6_use_defzone);
2319                 if (error)
2320                         return (EADDRNOTAVAIL);
2321                 /*
2322                  * Some badly behaved applications don't pass an ifindex
2323                  * or a scope ID, which is an API violation. In this case,
2324                  * perform a lookup as per a v6 join.
2325                  *
2326                  * XXX For now, stomp on zone ID for the corner case.
2327                  * This is not the 'KAME way', but we need to see the ifp
2328                  * directly until such time as this implementation is
2329                  * refactored, assuming the scope IDs are the way to go.
2330                  */
2331                 ifindex = ntohs(gsa->sin6.sin6_addr.s6_addr16[1]);
2332                 if (ifindex == 0) {
2333                         CTR2(KTR_MLD, "%s: warning: no ifindex, looking up "
2334                             "ifp for group %s.", __func__,
2335                             ip6_sprintf(ip6tbuf, &gsa->sin6.sin6_addr));
2336                         ifp = in6p_lookup_mcast_ifp(inp, &gsa->sin6);
2337                 } else {
2338                         ifp = ifnet_byindex(ifindex);
2339                 }
2340                 if (ifp == NULL)
2341                         return (EADDRNOTAVAIL);
2342         }
2343
2344         CTR2(KTR_MLD, "%s: ifp = %p", __func__, ifp);
2345         KASSERT(ifp != NULL, ("%s: ifp did not resolve", __func__));
2346
2347         /*
2348          * Find the membership in the membership array.
2349          */
2350         imo = in6p_findmoptions(inp);
2351         idx = im6o_match_group(imo, ifp, &gsa->sa);
2352         if (idx == -1) {
2353                 error = EADDRNOTAVAIL;
2354                 goto out_in6p_locked;
2355         }
2356         inm = imo->im6o_membership[idx];
2357         imf = &imo->im6o_mfilters[idx];
2358
2359         if (ssa->ss.ss_family != AF_UNSPEC)
2360                 is_final = 0;
2361
2362         /*
2363          * Begin state merge transaction at socket layer.
2364          */
2365         INP_WLOCK_ASSERT(inp);
2366
2367         /*
2368          * If we were instructed only to leave a given source, do so.
2369          * MCAST_LEAVE_SOURCE_GROUP is only valid for inclusive memberships.
2370          */
2371         if (is_final) {
2372                 im6f_leave(imf);
2373         } else {
2374                 if (imf->im6f_st[0] == MCAST_EXCLUDE) {
2375                         error = EADDRNOTAVAIL;
2376                         goto out_in6p_locked;
2377                 }
2378                 ims = im6o_match_source(imo, idx, &ssa->sa);
2379                 if (ims == NULL) {
2380                         CTR3(KTR_MLD, "%s: source %p %spresent", __func__,
2381                             ip6_sprintf(ip6tbuf, &ssa->sin6.sin6_addr),
2382                             "not ");
2383                         error = EADDRNOTAVAIL;
2384                         goto out_in6p_locked;
2385                 }
2386                 CTR2(KTR_MLD, "%s: %s source", __func__, "block");
2387                 error = im6f_prune(imf, &ssa->sin6);
2388                 if (error) {
2389                         CTR1(KTR_MLD, "%s: merge imf state failed",
2390                             __func__);
2391                         goto out_in6p_locked;
2392                 }
2393         }
2394
2395         /*
2396          * Begin state merge transaction at MLD layer.
2397          */
2398         in_pcbref(inp);
2399         INP_WUNLOCK(inp);
2400         IN6_MULTI_LOCK();
2401
2402         if (is_final) {
2403                 /*
2404                  * Give up the multicast address record to which
2405                  * the membership points.
2406                  */
2407                 (void)in6_leavegroup_locked(inm, imf);
2408         } else {
2409                 CTR1(KTR_MLD, "%s: merge inm state", __func__);
2410                 IN6_MULTI_LIST_LOCK();
2411                 error = in6m_merge(inm, imf);
2412                 if (error)
2413                         CTR1(KTR_MLD, "%s: failed to merge inm state",
2414                             __func__);
2415                 else {
2416                         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
2417                         error = mld_change_state(inm, 0);
2418                         if (error)
2419                                 CTR1(KTR_MLD, "%s: failed mld downcall",
2420                                     __func__);
2421                 }
2422                 IN6_MULTI_LIST_UNLOCK();
2423         }
2424
2425         IN6_MULTI_UNLOCK();
2426         INP_WLOCK(inp);
2427         if (in_pcbrele_wlocked(inp))
2428                 return (ENXIO);
2429
2430         if (error)
2431                 im6f_rollback(imf);
2432         else
2433                 im6f_commit(imf);
2434
2435         im6f_reap(imf);
2436
2437         if (is_final) {
2438                 /* Remove the gap in the membership array. */
2439                 for (++idx; idx < imo->im6o_num_memberships; ++idx) {
2440                         imo->im6o_membership[idx-1] = imo->im6o_membership[idx];
2441                         imo->im6o_mfilters[idx-1] = imo->im6o_mfilters[idx];
2442                 }
2443                 imo->im6o_num_memberships--;
2444         }
2445
2446 out_in6p_locked:
2447         INP_WUNLOCK(inp);
2448         return (error);
2449 }
2450
2451 /*
2452  * Select the interface for transmitting IPv6 multicast datagrams.
2453  *
2454  * Either an instance of struct in6_addr or an instance of struct ipv6_mreqn
2455  * may be passed to this socket option. An address of in6addr_any or an
2456  * interface index of 0 is used to remove a previous selection.
2457  * When no interface is selected, one is chosen for every send.
2458  */
2459 static int
2460 in6p_set_multicast_if(struct inpcb *inp, struct sockopt *sopt)
2461 {
2462         struct ifnet            *ifp;
2463         struct ip6_moptions     *imo;
2464         u_int                    ifindex;
2465         int                      error;
2466
2467         if (sopt->sopt_valsize != sizeof(u_int))
2468                 return (EINVAL);
2469
2470         error = sooptcopyin(sopt, &ifindex, sizeof(u_int), sizeof(u_int));
2471         if (error)
2472                 return (error);
2473         if (V_if_index < ifindex)
2474                 return (EINVAL);
2475         if (ifindex == 0)
2476                 ifp = NULL;
2477         else {
2478                 ifp = ifnet_byindex(ifindex);
2479                 if (ifp == NULL)
2480                         return (EINVAL);
2481                 if ((ifp->if_flags & IFF_MULTICAST) == 0)
2482                         return (EADDRNOTAVAIL);
2483         }
2484         imo = in6p_findmoptions(inp);
2485         imo->im6o_multicast_ifp = ifp;
2486         INP_WUNLOCK(inp);
2487
2488         return (0);
2489 }
2490
2491 /*
2492  * Atomically set source filters on a socket for an IPv6 multicast group.
2493  *
2494  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
2495  */
2496 static int
2497 in6p_set_source_filters(struct inpcb *inp, struct sockopt *sopt)
2498 {
2499         struct __msfilterreq     msfr;
2500         sockunion_t             *gsa;
2501         struct ifnet            *ifp;
2502         struct in6_mfilter      *imf;
2503         struct ip6_moptions     *imo;
2504         struct in6_multi                *inm;
2505         size_t                   idx;
2506         int                      error;
2507
2508         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
2509             sizeof(struct __msfilterreq));
2510         if (error)
2511                 return (error);
2512
2513         if (msfr.msfr_nsrcs > in6_mcast_maxsocksrc)
2514                 return (ENOBUFS);
2515
2516         if (msfr.msfr_fmode != MCAST_EXCLUDE &&
2517             msfr.msfr_fmode != MCAST_INCLUDE)
2518                 return (EINVAL);
2519
2520         if (msfr.msfr_group.ss_family != AF_INET6 ||
2521             msfr.msfr_group.ss_len != sizeof(struct sockaddr_in6))
2522                 return (EINVAL);
2523
2524         gsa = (sockunion_t *)&msfr.msfr_group;
2525         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
2526                 return (EINVAL);
2527
2528         gsa->sin6.sin6_port = 0;        /* ignore port */
2529
2530         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
2531                 return (EADDRNOTAVAIL);
2532         ifp = ifnet_byindex(msfr.msfr_ifindex);
2533         if (ifp == NULL)
2534                 return (EADDRNOTAVAIL);
2535         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
2536
2537         /*
2538          * Take the INP write lock.
2539          * Check if this socket is a member of this group.
2540          */
2541         imo = in6p_findmoptions(inp);
2542         idx = im6o_match_group(imo, ifp, &gsa->sa);
2543         if (idx == -1 || imo->im6o_mfilters == NULL) {
2544                 error = EADDRNOTAVAIL;
2545                 goto out_in6p_locked;
2546         }
2547         inm = imo->im6o_membership[idx];
2548         imf = &imo->im6o_mfilters[idx];
2549
2550         /*
2551          * Begin state merge transaction at socket layer.
2552          */
2553         INP_WLOCK_ASSERT(inp);
2554
2555         imf->im6f_st[1] = msfr.msfr_fmode;
2556
2557         /*
2558          * Apply any new source filters, if present.
2559          * Make a copy of the user-space source vector so
2560          * that we may copy them with a single copyin. This
2561          * allows us to deal with page faults up-front.
2562          */
2563         if (msfr.msfr_nsrcs > 0) {
2564                 struct in6_msource      *lims;
2565                 struct sockaddr_in6     *psin;
2566                 struct sockaddr_storage *kss, *pkss;
2567                 int                      i;
2568
2569                 INP_WUNLOCK(inp);
2570  
2571                 CTR2(KTR_MLD, "%s: loading %lu source list entries",
2572                     __func__, (unsigned long)msfr.msfr_nsrcs);
2573                 kss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
2574                     M_TEMP, M_WAITOK);
2575                 error = copyin(msfr.msfr_srcs, kss,
2576                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
2577                 if (error) {
2578                         free(kss, M_TEMP);
2579                         return (error);
2580                 }
2581
2582                 INP_WLOCK(inp);
2583
2584                 /*
2585                  * Mark all source filters as UNDEFINED at t1.
2586                  * Restore new group filter mode, as im6f_leave()
2587                  * will set it to INCLUDE.
2588                  */
2589                 im6f_leave(imf);
2590                 imf->im6f_st[1] = msfr.msfr_fmode;
2591
2592                 /*
2593                  * Update socket layer filters at t1, lazy-allocating
2594                  * new entries. This saves a bunch of memory at the
2595                  * cost of one RB_FIND() per source entry; duplicate
2596                  * entries in the msfr_nsrcs vector are ignored.
2597                  * If we encounter an error, rollback transaction.
2598                  *
2599                  * XXX This too could be replaced with a set-symmetric
2600                  * difference like loop to avoid walking from root
2601                  * every time, as the key space is common.
2602                  */
2603                 for (i = 0, pkss = kss; i < msfr.msfr_nsrcs; i++, pkss++) {
2604                         psin = (struct sockaddr_in6 *)pkss;
2605                         if (psin->sin6_family != AF_INET6) {
2606                                 error = EAFNOSUPPORT;
2607                                 break;
2608                         }
2609                         if (psin->sin6_len != sizeof(struct sockaddr_in6)) {
2610                                 error = EINVAL;
2611                                 break;
2612                         }
2613                         if (IN6_IS_ADDR_MULTICAST(&psin->sin6_addr)) {
2614                                 error = EINVAL;
2615                                 break;
2616                         }
2617                         /*
2618                          * TODO: Validate embedded scope ID in source
2619                          * list entry against passed-in ifp, if and only
2620                          * if source list filter entry is iface or node local.
2621                          */
2622                         in6_clearscope(&psin->sin6_addr);
2623                         error = im6f_get_source(imf, psin, &lims);
2624                         if (error)
2625                                 break;
2626                         lims->im6sl_st[1] = imf->im6f_st[1];
2627                 }
2628                 free(kss, M_TEMP);
2629         }
2630
2631         if (error)
2632                 goto out_im6f_rollback;
2633
2634         INP_WLOCK_ASSERT(inp);
2635         IN6_MULTI_LIST_LOCK();
2636
2637         /*
2638          * Begin state merge transaction at MLD layer.
2639          */
2640         CTR1(KTR_MLD, "%s: merge inm state", __func__);
2641         error = in6m_merge(inm, imf);
2642         if (error)
2643                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
2644         else {
2645                 CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
2646                 error = mld_change_state(inm, 0);
2647                 if (error)
2648                         CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
2649         }
2650
2651         IN6_MULTI_LIST_UNLOCK();
2652
2653 out_im6f_rollback:
2654         if (error)
2655                 im6f_rollback(imf);
2656         else
2657                 im6f_commit(imf);
2658
2659         im6f_reap(imf);
2660
2661 out_in6p_locked:
2662         INP_WUNLOCK(inp);
2663         return (error);
2664 }
2665
2666 /*
2667  * Set the IP multicast options in response to user setsockopt().
2668  *
2669  * Many of the socket options handled in this function duplicate the
2670  * functionality of socket options in the regular unicast API. However,
2671  * it is not possible to merge the duplicate code, because the idempotence
2672  * of the IPv6 multicast part of the BSD Sockets API must be preserved;
2673  * the effects of these options must be treated as separate and distinct.
2674  *
2675  * SMPng: XXX: Unlocked read of inp_socket believed OK.
2676  */
2677 int
2678 ip6_setmoptions(struct inpcb *inp, struct sockopt *sopt)
2679 {
2680         struct ip6_moptions     *im6o;
2681         int                      error;
2682
2683         error = 0;
2684
2685         /*
2686          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
2687          * or is a divert socket, reject it.
2688          */
2689         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
2690             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
2691              inp->inp_socket->so_proto->pr_type != SOCK_DGRAM))
2692                 return (EOPNOTSUPP);
2693
2694         switch (sopt->sopt_name) {
2695         case IPV6_MULTICAST_IF:
2696                 error = in6p_set_multicast_if(inp, sopt);
2697                 break;
2698
2699         case IPV6_MULTICAST_HOPS: {
2700                 int hlim;
2701
2702                 if (sopt->sopt_valsize != sizeof(int)) {
2703                         error = EINVAL;
2704                         break;
2705                 }
2706                 error = sooptcopyin(sopt, &hlim, sizeof(hlim), sizeof(int));
2707                 if (error)
2708                         break;
2709                 if (hlim < -1 || hlim > 255) {
2710                         error = EINVAL;
2711                         break;
2712                 } else if (hlim == -1) {
2713                         hlim = V_ip6_defmcasthlim;
2714                 }
2715                 im6o = in6p_findmoptions(inp);
2716                 im6o->im6o_multicast_hlim = hlim;
2717                 INP_WUNLOCK(inp);
2718                 break;
2719         }
2720
2721         case IPV6_MULTICAST_LOOP: {
2722                 u_int loop;
2723
2724                 /*
2725                  * Set the loopback flag for outgoing multicast packets.
2726                  * Must be zero or one.
2727                  */
2728                 if (sopt->sopt_valsize != sizeof(u_int)) {
2729                         error = EINVAL;
2730                         break;
2731                 }
2732                 error = sooptcopyin(sopt, &loop, sizeof(u_int), sizeof(u_int));
2733                 if (error)
2734                         break;
2735                 if (loop > 1) {
2736                         error = EINVAL;
2737                         break;
2738                 }
2739                 im6o = in6p_findmoptions(inp);
2740                 im6o->im6o_multicast_loop = loop;
2741                 INP_WUNLOCK(inp);
2742                 break;
2743         }
2744
2745         case IPV6_JOIN_GROUP:
2746         case MCAST_JOIN_GROUP:
2747         case MCAST_JOIN_SOURCE_GROUP:
2748                 error = in6p_join_group(inp, sopt);
2749                 break;
2750
2751         case IPV6_LEAVE_GROUP:
2752         case MCAST_LEAVE_GROUP:
2753         case MCAST_LEAVE_SOURCE_GROUP:
2754                 error = in6p_leave_group(inp, sopt);
2755                 break;
2756
2757         case MCAST_BLOCK_SOURCE:
2758         case MCAST_UNBLOCK_SOURCE:
2759                 error = in6p_block_unblock_source(inp, sopt);
2760                 break;
2761
2762         case IPV6_MSFILTER:
2763                 error = in6p_set_source_filters(inp, sopt);
2764                 break;
2765
2766         default:
2767                 error = EOPNOTSUPP;
2768                 break;
2769         }
2770
2771         INP_UNLOCK_ASSERT(inp);
2772
2773         return (error);
2774 }
2775
2776 /*
2777  * Expose MLD's multicast filter mode and source list(s) to userland,
2778  * keyed by (ifindex, group).
2779  * The filter mode is written out as a uint32_t, followed by
2780  * 0..n of struct in6_addr.
2781  * For use by ifmcstat(8).
2782  * SMPng: NOTE: unlocked read of ifindex space.
2783  */
2784 static int
2785 sysctl_ip6_mcast_filters(SYSCTL_HANDLER_ARGS)
2786 {
2787         struct in6_addr                  mcaddr;
2788         struct in6_addr                  src;
2789         struct ifnet                    *ifp;
2790         struct ifmultiaddr              *ifma;
2791         struct in6_multi                *inm;
2792         struct ip6_msource              *ims;
2793         int                             *name;
2794         int                              retval;
2795         u_int                            namelen;
2796         uint32_t                         fmode, ifindex;
2797 #ifdef KTR
2798         char                             ip6tbuf[INET6_ADDRSTRLEN];
2799 #endif
2800
2801         name = (int *)arg1;
2802         namelen = arg2;
2803
2804         if (req->newptr != NULL)
2805                 return (EPERM);
2806
2807         /* int: ifindex + 4 * 32 bits of IPv6 address */
2808         if (namelen != 5)
2809                 return (EINVAL);
2810
2811         ifindex = name[0];
2812         if (ifindex <= 0 || ifindex > V_if_index) {
2813                 CTR2(KTR_MLD, "%s: ifindex %u out of range",
2814                     __func__, ifindex);
2815                 return (ENOENT);
2816         }
2817
2818         memcpy(&mcaddr, &name[1], sizeof(struct in6_addr));
2819         if (!IN6_IS_ADDR_MULTICAST(&mcaddr)) {
2820                 CTR2(KTR_MLD, "%s: group %s is not multicast",
2821                     __func__, ip6_sprintf(ip6tbuf, &mcaddr));
2822                 return (EINVAL);
2823         }
2824
2825         ifp = ifnet_byindex(ifindex);
2826         if (ifp == NULL) {
2827                 CTR2(KTR_MLD, "%s: no ifp for ifindex %u",
2828                     __func__, ifindex);
2829                 return (ENOENT);
2830         }
2831         /*
2832          * Internal MLD lookups require that scope/zone ID is set.
2833          */
2834         (void)in6_setscope(&mcaddr, ifp, NULL);
2835
2836         retval = sysctl_wire_old_buffer(req,
2837             sizeof(uint32_t) + (in6_mcast_maxgrpsrc * sizeof(struct in6_addr)));
2838         if (retval)
2839                 return (retval);
2840
2841         IN6_MULTI_LOCK();
2842         IN6_MULTI_LIST_LOCK();
2843         IF_ADDR_RLOCK(ifp);
2844         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2845                 if (ifma->ifma_addr->sa_family != AF_INET6 ||
2846                     ifma->ifma_protospec == NULL)
2847                         continue;
2848                 inm = (struct in6_multi *)ifma->ifma_protospec;
2849                 if (!IN6_ARE_ADDR_EQUAL(&inm->in6m_addr, &mcaddr))
2850                         continue;
2851                 fmode = inm->in6m_st[1].iss_fmode;
2852                 retval = SYSCTL_OUT(req, &fmode, sizeof(uint32_t));
2853                 if (retval != 0)
2854                         break;
2855                 RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
2856                         CTR2(KTR_MLD, "%s: visit node %p", __func__, ims);
2857                         /*
2858                          * Only copy-out sources which are in-mode.
2859                          */
2860                         if (fmode != im6s_get_mode(inm, ims, 1)) {
2861                                 CTR1(KTR_MLD, "%s: skip non-in-mode",
2862                                     __func__);
2863                                 continue;
2864                         }
2865                         src = ims->im6s_addr;
2866                         retval = SYSCTL_OUT(req, &src,
2867                             sizeof(struct in6_addr));
2868                         if (retval != 0)
2869                                 break;
2870                 }
2871         }
2872         IF_ADDR_RUNLOCK(ifp);
2873
2874         IN6_MULTI_LIST_UNLOCK();
2875         IN6_MULTI_UNLOCK();
2876
2877         return (retval);
2878 }
2879
2880 #ifdef KTR
2881
2882 static const char *in6m_modestrs[] = { "un", "in", "ex" };
2883
2884 static const char *
2885 in6m_mode_str(const int mode)
2886 {
2887
2888         if (mode >= MCAST_UNDEFINED && mode <= MCAST_EXCLUDE)
2889                 return (in6m_modestrs[mode]);
2890         return ("??");
2891 }
2892
2893 static const char *in6m_statestrs[] = {
2894         "not-member",
2895         "silent",
2896         "idle",
2897         "lazy",
2898         "sleeping",
2899         "awakening",
2900         "query-pending",
2901         "sg-query-pending",
2902         "leaving"
2903 };
2904
2905 static const char *
2906 in6m_state_str(const int state)
2907 {
2908
2909         if (state >= MLD_NOT_MEMBER && state <= MLD_LEAVING_MEMBER)
2910                 return (in6m_statestrs[state]);
2911         return ("??");
2912 }
2913
2914 /*
2915  * Dump an in6_multi structure to the console.
2916  */
2917 void
2918 in6m_print(const struct in6_multi *inm)
2919 {
2920         int t;
2921         char ip6tbuf[INET6_ADDRSTRLEN];
2922
2923         if ((ktr_mask & KTR_MLD) == 0)
2924                 return;
2925
2926         printf("%s: --- begin in6m %p ---\n", __func__, inm);
2927         printf("addr %s ifp %p(%s) ifma %p\n",
2928             ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2929             inm->in6m_ifp,
2930             if_name(inm->in6m_ifp),
2931             inm->in6m_ifma);
2932         printf("timer %u state %s refcount %u scq.len %u\n",
2933             inm->in6m_timer,
2934             in6m_state_str(inm->in6m_state),
2935             inm->in6m_refcount,
2936             mbufq_len(&inm->in6m_scq));
2937         printf("mli %p nsrc %lu sctimer %u scrv %u\n",
2938             inm->in6m_mli,
2939             inm->in6m_nsrc,
2940             inm->in6m_sctimer,
2941             inm->in6m_scrv);
2942         for (t = 0; t < 2; t++) {
2943                 printf("t%d: fmode %s asm %u ex %u in %u rec %u\n", t,
2944                     in6m_mode_str(inm->in6m_st[t].iss_fmode),
2945                     inm->in6m_st[t].iss_asm,
2946                     inm->in6m_st[t].iss_ex,
2947                     inm->in6m_st[t].iss_in,
2948                     inm->in6m_st[t].iss_rec);
2949         }
2950         printf("%s: --- end in6m %p ---\n", __func__, inm);
2951 }
2952
2953 #else /* !KTR */
2954
2955 void
2956 in6m_print(const struct in6_multi *inm)
2957 {
2958
2959 }
2960
2961 #endif /* KTR */