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