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