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