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