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