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