xref: /xnu-11417.140.69/bsd/netinet6/in6_mcast.c (revision 43a90889846e00bfb5cf1d255cdc0a701a1e05a4)
1 /*
2  * Copyright (c) 2010-2022 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (c) 2009 Bruce Simpson.
30  * All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. The name of the author may not be used to endorse or promote
41  *    products derived from this software without specific prior written
42  *    permission.
43  *
44  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
45  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
47  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
48  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
49  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
50  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
52  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
53  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54  * SUCH DAMAGE.
55  */
56 
57 /*
58  * IPv6 multicast socket, group, and socket option processing module.
59  * Normative references: RFC 2292, RFC 3492, RFC 3542, RFC 3678, RFC 3810.
60  */
61 
62 #include <sys/cdefs.h>
63 
64 #include <sys/param.h>
65 #include <sys/systm.h>
66 #include <sys/kernel.h>
67 #include <sys/malloc.h>
68 #include <sys/mbuf.h>
69 #include <sys/protosw.h>
70 #include <sys/socket.h>
71 #include <sys/socketvar.h>
72 #include <sys/protosw.h>
73 #include <sys/tree.h>
74 #include <sys/mcache.h>
75 
76 #include <kern/zalloc.h>
77 
78 #include <pexpert/pexpert.h>
79 
80 #include <net/if.h>
81 #include <net/if_dl.h>
82 #include <net/net_api_stats.h>
83 #include <net/route.h>
84 #include <net/sockaddr_utils.h>
85 #include <net/net_sysctl.h>
86 
87 #include <netinet/in.h>
88 #include <netinet/in_var.h>
89 #include <netinet6/in6_var.h>
90 #include <netinet/ip6.h>
91 #include <netinet/icmp6.h>
92 #include <netinet6/ip6_var.h>
93 #include <netinet/in_pcb.h>
94 #include <netinet/tcp.h>
95 #include <netinet/tcp_seq.h>
96 #include <netinet/tcp_var.h>
97 #include <netinet6/nd6.h>
98 #include <netinet6/mld6_var.h>
99 #include <netinet6/scope6_var.h>
100 
101 #include <net/sockaddr_utils.h>
102 
103 static void     im6f_commit(struct in6_mfilter *);
104 static int      im6f_get_source(struct in6_mfilter *imf,
105     const struct sockaddr_in6 *psin,
106     struct in6_msource **);
107 static struct in6_msource *
108 im6f_graft(struct in6_mfilter *, const uint8_t,
109     const struct sockaddr_in6 *);
110 static int      im6f_prune(struct in6_mfilter *, const struct sockaddr_in6 *);
111 static void     im6f_rollback(struct in6_mfilter *);
112 static void     im6f_reap(struct in6_mfilter *);
113 static int      im6o_grow(struct ip6_moptions *);
114 static size_t   im6o_match_group(const struct ip6_moptions *,
115     const struct ifnet *, const struct sockaddr_in6 *);
116 static struct in6_msource *
117 im6o_match_source(const struct ip6_moptions *,
118     const size_t, const struct sockaddr_in6 *);
119 static void     im6s_merge(struct ip6_msource *ims,
120     const struct in6_msource *lims, const int rollback);
121 static int      in6_mc_get(struct ifnet *, const struct in6_addr *,
122     struct in6_multi **);
123 static int      in6m_get_source(struct in6_multi *inm,
124     const struct in6_addr *addr, const int noalloc,
125     struct ip6_msource **pims);
126 static int      in6m_is_ifp_detached(const struct in6_multi *);
127 static int      in6m_merge(struct in6_multi *, /*const*/ struct in6_mfilter *);
128 static void     in6m_reap(struct in6_multi *);
129 static struct ip6_moptions *
130 in6p_findmoptions(struct inpcb *);
131 static int      in6p_get_source_filters(struct inpcb *, struct sockopt *);
132 static int      in6p_lookup_v4addr(struct ipv6_mreq *, struct ip_mreq *);
133 static int      in6p_join_group(struct inpcb *, struct sockopt *);
134 static int      in6p_leave_group(struct inpcb *, struct sockopt *);
135 static struct ifnet *
136 in6p_lookup_mcast_ifp(const struct inpcb *,
137     const struct sockaddr_in6 *);
138 static int      in6p_block_unblock_source(struct inpcb *, struct sockopt *);
139 static int      in6p_set_multicast_if(struct inpcb *, struct sockopt *);
140 static int      in6p_set_source_filters(struct inpcb *, struct sockopt *);
141 static int      sysctl_ip6_mcast_filters SYSCTL_HANDLER_ARGS;
142 static __inline__ int ip6_msource_cmp(const struct ip6_msource *,
143     const struct ip6_msource *);
144 
145 SYSCTL_DECL(_net_inet6_ip6);    /* XXX Not in any common header. */
146 
147 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, mcast, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "IPv6 multicast");
148 
149 static unsigned long in6_mcast_maxgrpsrc = IPV6_MAX_GROUP_SRC_FILTER;
150 SYSCTL_LONG(_net_inet6_ip6_mcast, OID_AUTO, maxgrpsrc,
151     CTLFLAG_RW | CTLFLAG_LOCKED, &in6_mcast_maxgrpsrc,
152     "Max source filters per group");
153 
154 static unsigned long in6_mcast_maxsocksrc = IPV6_MAX_SOCK_SRC_FILTER;
155 SYSCTL_LONG(_net_inet6_ip6_mcast, OID_AUTO, maxsocksrc,
156     CTLFLAG_RW | CTLFLAG_LOCKED, &in6_mcast_maxsocksrc,
157     "Max source filters per socket");
158 
159 int in6_mcast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
160 SYSCTL_INT(_net_inet6_ip6_mcast, OID_AUTO, loop, CTLFLAG_RW | CTLFLAG_LOCKED,
161     &in6_mcast_loop, 0, "Loopback multicast datagrams by default");
162 
163 SYSCTL_NODE(_net_inet6_ip6_mcast, OID_AUTO, filters,
164     CTLFLAG_RD | CTLFLAG_LOCKED, sysctl_ip6_mcast_filters,
165     "Per-interface stack-wide source filters");
166 
167 RB_GENERATE_PREV(ip6_msource_tree, ip6_msource, im6s_link, ip6_msource_cmp);
168 
169 #define IN6M_TRACE_HIST_SIZE    32      /* size of trace history */
170 
171 /* For gdb */
172 __private_extern__ unsigned int in6m_trace_hist_size = IN6M_TRACE_HIST_SIZE;
173 
174 struct in6_multi_dbg {
175 	struct in6_multi        in6m;                   /* in6_multi */
176 	u_int16_t               in6m_refhold_cnt;       /* # of ref */
177 	u_int16_t               in6m_refrele_cnt;       /* # of rele */
178 	/*
179 	 * Circular lists of in6m_addref and in6m_remref callers.
180 	 */
181 	ctrace_t                in6m_refhold[IN6M_TRACE_HIST_SIZE];
182 	ctrace_t                in6m_refrele[IN6M_TRACE_HIST_SIZE];
183 	/*
184 	 * Trash list linkage
185 	 */
186 	TAILQ_ENTRY(in6_multi_dbg) in6m_trash_link;
187 };
188 
189 /* Lock group and attribute for in6_multihead_lock lock */
190 static LCK_ATTR_DECLARE(in6_multihead_lock_attr, 0, 0);
191 static LCK_GRP_DECLARE(in6_multihead_lock_grp, "in6_multihead");
192 
193 /* List of trash in6_multi entries protected by in6m_trash_lock */
194 static TAILQ_HEAD(, in6_multi_dbg) in6m_trash_head = TAILQ_HEAD_INITIALIZER(in6m_trash_head);
195 static LCK_MTX_DECLARE_ATTR(in6m_trash_lock, &in6_multihead_lock_grp,
196     &in6_multihead_lock_attr);
197 
198 #if DEBUG
199 static TUNABLE(bool, in6m_debug, "ifa_debug", true); /* debugging (enabled) */
200 #else
201 static TUNABLE(bool, in6m_debug, "ifa_debug", false); /* debugging (disabled) */
202 #endif /* !DEBUG */
203 
204 static KALLOC_TYPE_DEFINE(imm_zone, struct in6_multi_mship, NET_KT_DEFAULT);
205 static KALLOC_TYPE_DEFINE(ip6ms_zone, struct ip6_msource, NET_KT_DEFAULT);
206 static KALLOC_TYPE_DEFINE(in6ms_zone, struct in6_msource, NET_KT_DEFAULT);
207 
208 static LCK_RW_DECLARE_ATTR(in6_multihead_lock, &in6_multihead_lock_grp,
209     &in6_multihead_lock_attr);
210 struct in6_multihead in6_multihead;
211 
212 static struct in6_multi *in6_multi_alloc(zalloc_flags_t);
213 static void in6_multi_free(struct in6_multi *);
214 static void in6_multi_attach(struct in6_multi *);
215 static struct in6_multi_mship *in6_multi_mship_alloc(zalloc_flags_t);
216 static void in6_multi_mship_free(struct in6_multi_mship *);
217 static void in6m_trace(struct in6_multi *, int);
218 
219 static struct ip6_msource *ip6ms_alloc(zalloc_flags_t);
220 static void ip6ms_free(struct ip6_msource *);
221 static struct in6_msource *in6ms_alloc(zalloc_flags_t);
222 static void in6ms_free(struct in6_msource *);
223 
224 /*
225  * IPv6 source tree comparison function.
226  *
227  * An ordered predicate is necessary; bcmp() is not documented to return
228  * an indication of order, memcmp() is, and is an ISO C99 requirement.
229  */
230 static __inline int
ip6_msource_cmp(const struct ip6_msource * a,const struct ip6_msource * b)231 ip6_msource_cmp(const struct ip6_msource *a, const struct ip6_msource *b)
232 {
233 	return memcmp(&a->im6s_addr, &b->im6s_addr, sizeof(struct in6_addr));
234 }
235 
236 /*
237  * Inline function which wraps assertions for a valid ifp.
238  */
239 static __inline__ int
in6m_is_ifp_detached(const struct in6_multi * inm)240 in6m_is_ifp_detached(const struct in6_multi *inm)
241 {
242 	VERIFY(inm->in6m_ifma != NULL);
243 	VERIFY(inm->in6m_ifp == inm->in6m_ifma->ifma_ifp);
244 
245 	return !ifnet_is_attached(inm->in6m_ifp, 0);
246 }
247 
248 /*
249  * Initialize an in6_mfilter structure to a known state at t0, t1
250  * with an empty source filter list.
251  */
252 static __inline__ void
im6f_init(struct in6_mfilter * imf,const uint8_t st0,const uint8_t st1)253 im6f_init(struct in6_mfilter *imf, const uint8_t st0, const  uint8_t st1)
254 {
255 	memset(imf, 0, sizeof(struct in6_mfilter));
256 	RB_INIT(&imf->im6f_sources);
257 	imf->im6f_st[0] = st0;
258 	imf->im6f_st[1] = st1;
259 }
260 
261 /*
262  * Resize the ip6_moptions vector to the next power-of-two minus 1.
263  */
264 static int
im6o_grow(struct ip6_moptions * imo)265 im6o_grow(struct ip6_moptions *imo)
266 {
267 	struct in6_multi        **nmships;
268 	struct in6_multi        **omships;
269 	struct in6_mfilter       *nmfilters;
270 	struct in6_mfilter       *omfilters;
271 	int                       err;
272 	size_t                    idx;
273 	uint16_t                  oldmax;
274 	uint16_t                  newmax;
275 
276 	IM6O_LOCK_ASSERT_HELD(imo);
277 
278 	nmships = NULL;
279 	nmfilters = NULL;
280 	err = 0;
281 	omships = imo->im6o_membership;
282 	omfilters = imo->im6o_mfilters;
283 	oldmax = imo->im6o_max_memberships;
284 	newmax = ((oldmax + 1) * 2) - 1;
285 
286 	if (newmax > IPV6_MAX_MEMBERSHIPS) {
287 		return ETOOMANYREFS;
288 	}
289 
290 	if ((nmships = kalloc_type(struct in6_multi *, newmax,
291 	    Z_WAITOK | Z_ZERO)) == NULL) {
292 		err = ENOMEM;
293 		goto cleanup;
294 	}
295 
296 	if ((nmfilters = kalloc_type(struct in6_mfilter, newmax,
297 	    Z_WAITOK | Z_ZERO)) == NULL) {
298 		err = ENOMEM;
299 		goto cleanup;
300 	}
301 
302 	/* Copy the existing memberships and release the memory. */
303 	if (omships != NULL) {
304 		VERIFY(oldmax <= newmax);
305 		memcpy(nmships, omships, oldmax * sizeof(struct in6_multi *));
306 		kfree_type(struct in6_multi *, oldmax, omships);
307 	}
308 
309 	/* Copy the existing filters and release the memory. */
310 	if (omfilters != NULL) {
311 		VERIFY(oldmax <= newmax);
312 		memcpy(nmfilters, omfilters, oldmax * sizeof(struct in6_mfilter));
313 		kfree_type(struct in6_mfilter, oldmax, omfilters);
314 	}
315 
316 	/* Initialize newly allocated source filter heads. */
317 	for (idx = oldmax; idx < newmax; idx++) {
318 		im6f_init(&nmfilters[idx], MCAST_UNDEFINED, MCAST_EXCLUDE);
319 	}
320 
321 	imo->im6o_membership = nmships;
322 	imo->im6o_max_memberships = newmax;
323 	nmships = NULL;
324 
325 	imo->im6o_mfilters = nmfilters;
326 	imo->im6o_max_filters = newmax;
327 	nmfilters = NULL;
328 
329 	return 0;
330 cleanup:
331 	if (nmfilters != NULL) {
332 		kfree_type(struct in6_mfilter, newmax, nmfilters);
333 	}
334 
335 	if (nmships != NULL) {
336 		kfree_type(struct in6_multi *, newmax, nmships);
337 	}
338 
339 	return err;
340 }
341 
342 /*
343  * Find an IPv6 multicast group entry for this ip6_moptions instance
344  * which matches the specified group, and optionally an interface.
345  * Return its index into the array, or -1 if not found.
346  */
347 static size_t
im6o_match_group(const struct ip6_moptions * imo,const struct ifnet * ifp,const struct sockaddr_in6 * group)348 im6o_match_group(const struct ip6_moptions *imo, const struct ifnet *ifp,
349     const struct sockaddr_in6 *group)
350 {
351 	const struct sockaddr_in6 *gsin6;
352 	struct in6_multi *pinm;
353 	int               idx;
354 	int               nmships;
355 
356 	IM6O_LOCK_ASSERT_HELD(__DECONST(struct ip6_moptions *, imo));
357 
358 	gsin6 = group;
359 
360 	/* The im6o_membership array may be lazy allocated. */
361 	if (imo->im6o_membership == NULL || imo->im6o_num_memberships == 0) {
362 		return -1;
363 	}
364 
365 	nmships = imo->im6o_num_memberships;
366 	for (idx = 0; idx < nmships; idx++) {
367 		pinm = imo->im6o_membership[idx];
368 		if (pinm == NULL) {
369 			continue;
370 		}
371 		IN6M_LOCK(pinm);
372 		if ((ifp == NULL || (pinm->in6m_ifp == ifp)) &&
373 		    in6_are_addr_equal_scoped(&pinm->in6m_addr,
374 		    &gsin6->sin6_addr, pinm->ifscope, gsin6->sin6_scope_id)) {
375 			IN6M_UNLOCK(pinm);
376 			break;
377 		}
378 		IN6M_UNLOCK(pinm);
379 	}
380 	if (idx >= nmships) {
381 		idx = -1;
382 	}
383 
384 	return idx;
385 }
386 
387 /*
388  * Find an IPv6 multicast source entry for this imo which matches
389  * the given group index for this socket, and source address.
390  *
391  * XXX TODO: The scope ID, if present in src, is stripped before
392  * any comparison. We SHOULD enforce scope/zone checks where the source
393  * filter entry has a link scope.
394  *
395  * NOTE: This does not check if the entry is in-mode, merely if
396  * it exists, which may not be the desired behaviour.
397  */
398 static struct in6_msource *
im6o_match_source(const struct ip6_moptions * imo,const size_t gidx,const struct sockaddr_in6 * src)399 im6o_match_source(const struct ip6_moptions *imo, const size_t gidx,
400     const struct sockaddr_in6 *src)
401 {
402 	struct ip6_msource       find;
403 	struct in6_mfilter      *imf;
404 	struct ip6_msource      *ims;
405 	const struct sockaddr_in6 *psa;
406 
407 	IM6O_LOCK_ASSERT_HELD(__DECONST(struct ip6_moptions *, imo));
408 
409 	VERIFY(src->sin6_family == AF_INET6);
410 	VERIFY(gidx != (size_t)-1 && gidx < imo->im6o_num_memberships);
411 
412 	/* The im6o_mfilters array may be lazy allocated. */
413 	if (imo->im6o_mfilters == NULL) {
414 		return NULL;
415 	}
416 	imf = &imo->im6o_mfilters[gidx];
417 
418 	psa = src;
419 	find.im6s_addr = psa->sin6_addr;
420 	in6_clearscope(&find.im6s_addr);                /* XXX */
421 	ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
422 
423 	return (struct in6_msource *)ims;
424 }
425 
426 /*
427  * Perform filtering for multicast datagrams on a socket by group and source.
428  *
429  * Returns 0 if a datagram should be allowed through, or various error codes
430  * if the socket was not a member of the group, or the source was muted, etc.
431  */
432 int
im6o_mc_filter(const struct ip6_moptions * imo,struct ifnet * ifp,const struct sockaddr_in6 * group,const struct sockaddr_in6 * src)433 im6o_mc_filter(const struct ip6_moptions *imo, struct ifnet *ifp,
434     const struct sockaddr_in6 *group, const struct sockaddr_in6 *src)
435 {
436 	size_t gidx;
437 	struct in6_msource *ims;
438 	int mode;
439 
440 	IM6O_LOCK_ASSERT_HELD(__DECONST(struct ip6_moptions *, imo));
441 	VERIFY(ifp != NULL);
442 
443 	struct sockaddr_in6 group_tmp = *group;
444 	if (!in6_embedded_scope) {
445 		group_tmp.sin6_scope_id = in6_addr2scopeid(ifp, &group_tmp.sin6_addr);
446 	}
447 	gidx = im6o_match_group(imo, ifp, &group_tmp);
448 	if (gidx == (size_t)-1) {
449 		return MCAST_NOTGMEMBER;
450 	}
451 
452 	/*
453 	 * Check if the source was included in an (S,G) join.
454 	 * Allow reception on exclusive memberships by default,
455 	 * reject reception on inclusive memberships by default.
456 	 * Exclude source only if an in-mode exclude filter exists.
457 	 * Include source only if an in-mode include filter exists.
458 	 * NOTE: We are comparing group state here at MLD t1 (now)
459 	 * with socket-layer t0 (since last downcall).
460 	 */
461 	mode = imo->im6o_mfilters[gidx].im6f_st[1];
462 	ims = im6o_match_source(imo, gidx, src);
463 
464 	if ((ims == NULL && mode == MCAST_INCLUDE) ||
465 	    (ims != NULL && ims->im6sl_st[0] != mode)) {
466 		return MCAST_NOTSMEMBER;
467 	}
468 
469 	return MCAST_PASS;
470 }
471 
472 /*
473  * Find and return a reference to an in6_multi record for (ifp, group),
474  * and bump its reference count.
475  * If one does not exist, try to allocate it, and update link-layer multicast
476  * filters on ifp to listen for group.
477  * Assumes the IN6_MULTI lock is held across the call.
478  * Return 0 if successful, otherwise return an appropriate error code.
479  */
480 static int
in6_mc_get(struct ifnet * ifp,const struct in6_addr * group,struct in6_multi ** pinm)481 in6_mc_get(struct ifnet *ifp, const struct in6_addr *group,
482     struct in6_multi **pinm)
483 {
484 	struct sockaddr_in6      gsin6;
485 	struct ifmultiaddr      *__single ifma;
486 	struct in6_multi        *__single inm;
487 	int                      error;
488 
489 	*pinm = NULL;
490 
491 	in6_multihead_lock_shared();
492 	IN6_LOOKUP_MULTI(group, ifp, inm);
493 	if (inm != NULL) {
494 		IN6M_LOCK(inm);
495 		VERIFY(inm->in6m_reqcnt >= 1);
496 		inm->in6m_reqcnt++;
497 		VERIFY(inm->in6m_reqcnt != 0);
498 		*pinm = inm;
499 		IN6M_UNLOCK(inm);
500 		in6_multihead_lock_done();
501 		/*
502 		 * We already joined this group; return the in6m
503 		 * with a refcount held (via lookup) for caller.
504 		 */
505 		return 0;
506 	}
507 	in6_multihead_lock_done();
508 
509 	memset(&gsin6, 0, sizeof(gsin6));
510 	gsin6.sin6_family = AF_INET6;
511 	gsin6.sin6_len = sizeof(struct sockaddr_in6);
512 	gsin6.sin6_addr = *group;
513 
514 	/*
515 	 * Check if a link-layer group is already associated
516 	 * with this network-layer group on the given ifnet.
517 	 */
518 	error = if_addmulti(ifp, SA(&gsin6), &ifma);
519 	if (error != 0) {
520 		return error;
521 	}
522 
523 	/*
524 	 * See comments in in6m_remref() for access to ifma_protospec.
525 	 */
526 	in6_multihead_lock_exclusive();
527 	IFMA_LOCK(ifma);
528 	if ((inm = ifma->ifma_protospec) != NULL) {
529 		VERIFY(ifma->ifma_addr != NULL);
530 		VERIFY(ifma->ifma_addr->sa_family == AF_INET6);
531 		IN6M_ADDREF(inm);       /* for caller */
532 		IFMA_UNLOCK(ifma);
533 		IN6M_LOCK(inm);
534 		VERIFY(inm->in6m_ifma == ifma);
535 		VERIFY(inm->in6m_ifp == ifp);
536 		VERIFY(in6_are_addr_equal_scoped(&inm->in6m_addr, group, inm->ifscope, ifp->if_index));
537 		if (inm->in6m_debug & IFD_ATTACHED) {
538 			VERIFY(inm->in6m_reqcnt >= 1);
539 			inm->in6m_reqcnt++;
540 			VERIFY(inm->in6m_reqcnt != 0);
541 			*pinm = inm;
542 			IN6M_UNLOCK(inm);
543 			in6_multihead_lock_done();
544 			IFMA_REMREF(ifma);
545 			/*
546 			 * We lost the race with another thread doing
547 			 * in6_mc_get(); since this group has already
548 			 * been joined; return the inm with a refcount
549 			 * held for caller.
550 			 */
551 			return 0;
552 		}
553 		/*
554 		 * We lost the race with another thread doing in6_delmulti();
555 		 * the inm referring to the ifma has been detached, thus we
556 		 * reattach it back to the in6_multihead list, and return the
557 		 * inm with a refcount held for the caller.
558 		 */
559 		in6_multi_attach(inm);
560 		VERIFY((inm->in6m_debug &
561 		    (IFD_ATTACHED | IFD_TRASHED)) == IFD_ATTACHED);
562 		*pinm = inm;
563 		IN6M_UNLOCK(inm);
564 		in6_multihead_lock_done();
565 		IFMA_REMREF(ifma);
566 		return 0;
567 	}
568 	IFMA_UNLOCK(ifma);
569 
570 	/*
571 	 * A new in6_multi record is needed; allocate and initialize it.
572 	 * We DO NOT perform an MLD join as the in6_ layer may need to
573 	 * push an initial source list down to MLD to support SSM.
574 	 *
575 	 * The initial source filter state is INCLUDE, {} as per the RFC.
576 	 * Pending state-changes per group are subject to a bounds check.
577 	 */
578 	inm = in6_multi_alloc(Z_WAITOK);
579 
580 	IN6M_LOCK(inm);
581 	inm->in6m_addr = *group;
582 	inm->ifscope = in6_addr2scopeid(ifp, &inm->in6m_addr);
583 	inm->in6m_ifp = ifp;
584 	inm->in6m_mli = MLD_IFINFO(ifp);
585 	VERIFY(inm->in6m_mli != NULL);
586 	MLI_ADDREF(inm->in6m_mli);
587 	inm->in6m_ifma = ifma;          /* keep refcount from if_addmulti() */
588 	inm->in6m_state = MLD_NOT_MEMBER;
589 	/*
590 	 * Pending state-changes per group are subject to a bounds check.
591 	 */
592 	inm->in6m_scq.ifq_maxlen = MLD_MAX_STATE_CHANGES;
593 	inm->in6m_st[0].iss_fmode = MCAST_UNDEFINED;
594 	inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
595 	RB_INIT(&inm->in6m_srcs);
596 	*pinm = inm;
597 	in6_multi_attach(inm);
598 	VERIFY((inm->in6m_debug &
599 	    (IFD_ATTACHED | IFD_TRASHED)) == IFD_ATTACHED);
600 	IN6M_ADDREF_LOCKED(inm);        /* for caller */
601 	IN6M_UNLOCK(inm);
602 
603 	IFMA_LOCK(ifma);
604 	VERIFY(ifma->ifma_protospec == NULL);
605 	ifma->ifma_protospec = inm;
606 	IFMA_UNLOCK(ifma);
607 	in6_multihead_lock_done();
608 
609 	return 0;
610 }
611 
612 /*
613  * Clear recorded source entries for a group.
614  * Used by the MLD code. Caller must hold the IN6_MULTI lock.
615  * FIXME: Should reap.
616  */
617 void
in6m_clear_recorded(struct in6_multi * inm)618 in6m_clear_recorded(struct in6_multi *inm)
619 {
620 	struct ip6_msource      *ims;
621 
622 	IN6M_LOCK_ASSERT_HELD(inm);
623 
624 	RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
625 		if (ims->im6s_stp) {
626 			ims->im6s_stp = 0;
627 			--inm->in6m_st[1].iss_rec;
628 		}
629 	}
630 	VERIFY(inm->in6m_st[1].iss_rec == 0);
631 }
632 
633 /*
634  * Record a source as pending for a Source-Group MLDv2 query.
635  * This lives here as it modifies the shared tree.
636  *
637  * inm is the group descriptor.
638  * naddr is the address of the source to record in network-byte order.
639  *
640  * If the net.inet6.mld.sgalloc sysctl is non-zero, we will
641  * lazy-allocate a source node in response to an SG query.
642  * Otherwise, no allocation is performed. This saves some memory
643  * with the trade-off that the source will not be reported to the
644  * router if joined in the window between the query response and
645  * the group actually being joined on the local host.
646  *
647  * VIMAGE: XXX: Currently the mld_sgalloc feature has been removed.
648  * This turns off the allocation of a recorded source entry if
649  * the group has not been joined.
650  *
651  * Return 0 if the source didn't exist or was already marked as recorded.
652  * Return 1 if the source was marked as recorded by this function.
653  * Return <0 if any error occured (negated errno code).
654  */
655 int
in6m_record_source(struct in6_multi * inm,const struct in6_addr * addr)656 in6m_record_source(struct in6_multi *inm, const struct in6_addr *addr)
657 {
658 	struct ip6_msource       find;
659 	struct ip6_msource      *ims, *nims;
660 
661 	IN6M_LOCK_ASSERT_HELD(inm);
662 
663 	find.im6s_addr = *addr;
664 	ims = RB_FIND(ip6_msource_tree, &inm->in6m_srcs, &find);
665 	if (ims && ims->im6s_stp) {
666 		return 0;
667 	}
668 	if (ims == NULL) {
669 		if (inm->in6m_nsrc == in6_mcast_maxgrpsrc) {
670 			return -ENOSPC;
671 		}
672 		nims = ip6ms_alloc(Z_WAITOK);
673 		nims->im6s_addr = find.im6s_addr;
674 		RB_INSERT(ip6_msource_tree, &inm->in6m_srcs, nims);
675 		++inm->in6m_nsrc;
676 		ims = nims;
677 	}
678 
679 	/*
680 	 * Mark the source as recorded and update the recorded
681 	 * source count.
682 	 */
683 	++ims->im6s_stp;
684 	++inm->in6m_st[1].iss_rec;
685 
686 	return 1;
687 }
688 
689 /*
690  * Return a pointer to an in6_msource owned by an in6_mfilter,
691  * given its source address.
692  * Lazy-allocate if needed. If this is a new entry its filter state is
693  * undefined at t0.
694  *
695  * imf is the filter set being modified.
696  * addr is the source address.
697  *
698  * Caller is expected to be holding im6o_lock.
699  */
700 static int
im6f_get_source(struct in6_mfilter * imf,const struct sockaddr_in6 * psin,struct in6_msource ** plims)701 im6f_get_source(struct in6_mfilter *imf, const struct sockaddr_in6 *psin,
702     struct in6_msource **plims)
703 {
704 	struct ip6_msource       find;
705 	struct ip6_msource      *ims;
706 	struct in6_msource      *lims;
707 	int                      error;
708 
709 	error = 0;
710 	ims = NULL;
711 	lims = NULL;
712 
713 	find.im6s_addr = psin->sin6_addr;
714 	ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
715 	lims = (struct in6_msource *)ims;
716 	if (lims == NULL) {
717 		if (imf->im6f_nsrc == in6_mcast_maxsocksrc) {
718 			return ENOSPC;
719 		}
720 		lims = in6ms_alloc(Z_WAITOK);
721 		lims->im6s_addr = find.im6s_addr;
722 		lims->im6sl_st[0] = MCAST_UNDEFINED;
723 		RB_INSERT(ip6_msource_tree, &imf->im6f_sources,
724 		    (struct ip6_msource *)lims);
725 		++imf->im6f_nsrc;
726 	}
727 
728 	*plims = lims;
729 
730 	return error;
731 }
732 
733 /*
734  * Graft a source entry into an existing socket-layer filter set,
735  * maintaining any required invariants and checking allocations.
736  *
737  * The source is marked as being in the new filter mode at t1.
738  *
739  * Return the pointer to the new node, otherwise return NULL.
740  *
741  * Caller is expected to be holding im6o_lock.
742  */
743 static struct in6_msource *
im6f_graft(struct in6_mfilter * imf,const uint8_t st1,const struct sockaddr_in6 * psin)744 im6f_graft(struct in6_mfilter *imf, const uint8_t st1,
745     const struct sockaddr_in6 *psin)
746 {
747 	struct in6_msource      *lims;
748 	struct ip6_msource      *__single lims_forged;
749 
750 	lims = in6ms_alloc(Z_WAITOK);
751 	lims->im6s_addr = psin->sin6_addr;
752 	lims->im6sl_st[0] = MCAST_UNDEFINED;
753 	lims->im6sl_st[1] = st1;
754 
755 	/* Removal of __unsafe_forge_single tracked by rdar://121702748 */
756 	lims_forged = __unsafe_forge_single(struct ip6_msource *, lims);
757 	RB_INSERT(ip6_msource_tree, &imf->im6f_sources,
758 	    lims_forged);
759 	++imf->im6f_nsrc;
760 
761 	return lims;
762 }
763 
764 /*
765  * Prune a source entry from an existing socket-layer filter set,
766  * maintaining any required invariants and checking allocations.
767  *
768  * The source is marked as being left at t1, it is not freed.
769  *
770  * Return 0 if no error occurred, otherwise return an errno value.
771  *
772  * Caller is expected to be holding im6o_lock.
773  */
774 static int
im6f_prune(struct in6_mfilter * imf,const struct sockaddr_in6 * psin)775 im6f_prune(struct in6_mfilter *imf, const struct sockaddr_in6 *psin)
776 {
777 	struct ip6_msource       find;
778 	struct ip6_msource      *ims;
779 	struct in6_msource      *lims;
780 
781 	find.im6s_addr = psin->sin6_addr;
782 	ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
783 	if (ims == NULL) {
784 		return ENOENT;
785 	}
786 	lims = (struct in6_msource *)ims;
787 	lims->im6sl_st[1] = MCAST_UNDEFINED;
788 	return 0;
789 }
790 
791 /*
792  * Revert socket-layer filter set deltas at t1 to t0 state.
793  *
794  * Caller is expected to be holding im6o_lock.
795  */
796 static void
im6f_rollback(struct in6_mfilter * imf)797 im6f_rollback(struct in6_mfilter *imf)
798 {
799 	struct ip6_msource      *ims, *tims;
800 	struct in6_msource      *lims;
801 
802 	RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
803 		lims = (struct in6_msource *)ims;
804 		if (lims->im6sl_st[0] == lims->im6sl_st[1]) {
805 			/* no change at t1 */
806 			continue;
807 		} else if (lims->im6sl_st[0] != MCAST_UNDEFINED) {
808 			/* revert change to existing source at t1 */
809 			lims->im6sl_st[1] = lims->im6sl_st[0];
810 		} else {
811 			/* revert source added t1 */
812 			MLD_PRINTF(("%s: free in6ms 0x%llx\n", __func__,
813 			    (uint64_t)VM_KERNEL_ADDRPERM(lims)));
814 			RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
815 			in6ms_free(lims);
816 			imf->im6f_nsrc--;
817 		}
818 	}
819 	imf->im6f_st[1] = imf->im6f_st[0];
820 }
821 
822 /*
823  * Mark socket-layer filter set as INCLUDE {} at t1.
824  *
825  * Caller is expected to be holding im6o_lock.
826  */
827 void
im6f_leave(struct in6_mfilter * imf)828 im6f_leave(struct in6_mfilter *imf)
829 {
830 	struct ip6_msource      *ims;
831 	struct in6_msource      *lims;
832 
833 	RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
834 		lims = (struct in6_msource *)ims;
835 		lims->im6sl_st[1] = MCAST_UNDEFINED;
836 	}
837 	imf->im6f_st[1] = MCAST_INCLUDE;
838 }
839 
840 /*
841  * Mark socket-layer filter set deltas as committed.
842  *
843  * Caller is expected to be holding im6o_lock.
844  */
845 static void
im6f_commit(struct in6_mfilter * imf)846 im6f_commit(struct in6_mfilter *imf)
847 {
848 	struct ip6_msource      *ims;
849 	struct in6_msource      *lims;
850 
851 	RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
852 		lims = (struct in6_msource *)ims;
853 		lims->im6sl_st[0] = lims->im6sl_st[1];
854 	}
855 	imf->im6f_st[0] = imf->im6f_st[1];
856 }
857 
858 /*
859  * Reap unreferenced sources from socket-layer filter set.
860  *
861  * Caller is expected to be holding im6o_lock.
862  */
863 static void
im6f_reap(struct in6_mfilter * imf)864 im6f_reap(struct in6_mfilter *imf)
865 {
866 	struct ip6_msource      *ims, *tims;
867 	struct in6_msource      *lims;
868 
869 	RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
870 		lims = (struct in6_msource *)ims;
871 		if ((lims->im6sl_st[0] == MCAST_UNDEFINED) &&
872 		    (lims->im6sl_st[1] == MCAST_UNDEFINED)) {
873 			MLD_PRINTF(("%s: free in6ms 0x%llx\n", __func__,
874 			    (uint64_t)VM_KERNEL_ADDRPERM(lims)));
875 			RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
876 			in6ms_free(lims);
877 			imf->im6f_nsrc--;
878 		}
879 	}
880 }
881 
882 /*
883  * Purge socket-layer filter set.
884  *
885  * Caller is expected to be holding im6o_lock.
886  */
887 void
im6f_purge(struct in6_mfilter * imf)888 im6f_purge(struct in6_mfilter *imf)
889 {
890 	struct ip6_msource      *ims, *tims;
891 	struct in6_msource      *lims;
892 
893 	RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
894 		lims = (struct in6_msource *)ims;
895 		MLD_PRINTF(("%s: free in6ms 0x%llx\n", __func__,
896 		    (uint64_t)VM_KERNEL_ADDRPERM(lims)));
897 		RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
898 		in6ms_free(lims);
899 		imf->im6f_nsrc--;
900 	}
901 	imf->im6f_st[0] = imf->im6f_st[1] = MCAST_UNDEFINED;
902 	VERIFY(RB_EMPTY(&imf->im6f_sources));
903 }
904 
905 /*
906  * Look up a source filter entry for a multicast group.
907  *
908  * inm is the group descriptor to work with.
909  * addr is the IPv6 address to look up.
910  * noalloc may be non-zero to suppress allocation of sources.
911  * *pims will be set to the address of the retrieved or allocated source.
912  *
913  * Return 0 if successful, otherwise return a non-zero error code.
914  */
915 static int
in6m_get_source(struct in6_multi * inm,const struct in6_addr * addr,const int noalloc,struct ip6_msource ** pims)916 in6m_get_source(struct in6_multi *inm, const struct in6_addr *addr,
917     const int noalloc, struct ip6_msource **pims)
918 {
919 	struct ip6_msource       find;
920 	struct ip6_msource      *ims, *nims;
921 
922 	IN6M_LOCK_ASSERT_HELD(inm);
923 
924 	find.im6s_addr = *addr;
925 	ims = RB_FIND(ip6_msource_tree, &inm->in6m_srcs, &find);
926 	if (ims == NULL && !noalloc) {
927 		if (inm->in6m_nsrc == in6_mcast_maxgrpsrc) {
928 			return ENOSPC;
929 		}
930 		nims = ip6ms_alloc(Z_WAITOK);
931 		nims->im6s_addr = *addr;
932 		RB_INSERT(ip6_msource_tree, &inm->in6m_srcs, nims);
933 		++inm->in6m_nsrc;
934 		ims = nims;
935 		MLD_PRINTF(("%s: allocated %s as 0x%llx\n", __func__,
936 		    ip6_sprintf(addr), (uint64_t)VM_KERNEL_ADDRPERM(ims)));
937 	}
938 
939 	*pims = ims;
940 	return 0;
941 }
942 
943 /*
944  * Helper function to derive the filter mode on a source entry
945  * from its internal counters. Predicates are:
946  *  A source is only excluded if all listeners exclude it.
947  *  A source is only included if no listeners exclude it,
948  *  and at least one listener includes it.
949  * May be used by ifmcstat(8).
950  */
951 uint8_t
im6s_get_mode(const struct in6_multi * inm,const struct ip6_msource * ims,uint8_t t)952 im6s_get_mode(const struct in6_multi *inm, const struct ip6_msource *ims,
953     uint8_t t)
954 {
955 	IN6M_LOCK_ASSERT_HELD(__DECONST(struct in6_multi *, inm));
956 
957 	t = !!t;
958 	if (inm->in6m_st[t].iss_ex > 0 &&
959 	    inm->in6m_st[t].iss_ex == ims->im6s_st[t].ex) {
960 		return MCAST_EXCLUDE;
961 	} else if (ims->im6s_st[t].in > 0 && ims->im6s_st[t].ex == 0) {
962 		return MCAST_INCLUDE;
963 	}
964 	return MCAST_UNDEFINED;
965 }
966 
967 /*
968  * Merge socket-layer source into MLD-layer source.
969  * If rollback is non-zero, perform the inverse of the merge.
970  */
971 static void
im6s_merge(struct ip6_msource * ims,const struct in6_msource * lims,const int rollback)972 im6s_merge(struct ip6_msource *ims, const struct in6_msource *lims,
973     const int rollback)
974 {
975 	int n = rollback ? -1 : 1;
976 
977 	if (lims->im6sl_st[0] == MCAST_EXCLUDE) {
978 		MLD_PRINTF(("%s: t1 ex -= %d on %s\n", __func__, n,
979 		    ip6_sprintf(&lims->im6s_addr)));
980 		ims->im6s_st[1].ex -= n;
981 	} else if (lims->im6sl_st[0] == MCAST_INCLUDE) {
982 		MLD_PRINTF(("%s: t1 in -= %d on %s\n", __func__, n,
983 		    ip6_sprintf(&lims->im6s_addr)));
984 		ims->im6s_st[1].in -= n;
985 	}
986 
987 	if (lims->im6sl_st[1] == MCAST_EXCLUDE) {
988 		MLD_PRINTF(("%s: t1 ex += %d on %s\n", __func__, n,
989 		    ip6_sprintf(&lims->im6s_addr)));
990 		ims->im6s_st[1].ex += n;
991 	} else if (lims->im6sl_st[1] == MCAST_INCLUDE) {
992 		MLD_PRINTF(("%s: t1 in += %d on %s\n", __func__, n,
993 		    ip6_sprintf(&lims->im6s_addr)));
994 		ims->im6s_st[1].in += n;
995 	}
996 }
997 
998 /*
999  * Atomically update the global in6_multi state, when a membership's
1000  * filter list is being updated in any way.
1001  *
1002  * imf is the per-inpcb-membership group filter pointer.
1003  * A fake imf may be passed for in-kernel consumers.
1004  *
1005  * XXX This is a candidate for a set-symmetric-difference style loop
1006  * which would eliminate the repeated lookup from root of ims nodes,
1007  * as they share the same key space.
1008  *
1009  * If any error occurred this function will back out of refcounts
1010  * and return a non-zero value.
1011  */
1012 static int
in6m_merge(struct in6_multi * inm,struct in6_mfilter * imf)1013 in6m_merge(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
1014 {
1015 	struct ip6_msource      *ims, *__single nims = NULL;
1016 	struct in6_msource      *lims;
1017 	int                      schanged, error;
1018 	int                      nsrc0, nsrc1;
1019 
1020 	IN6M_LOCK_ASSERT_HELD(inm);
1021 
1022 	schanged = 0;
1023 	error = 0;
1024 	nsrc1 = nsrc0 = 0;
1025 
1026 	/*
1027 	 * Update the source filters first, as this may fail.
1028 	 * Maintain count of in-mode filters at t0, t1. These are
1029 	 * used to work out if we transition into ASM mode or not.
1030 	 * Maintain a count of source filters whose state was
1031 	 * actually modified by this operation.
1032 	 */
1033 	RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
1034 		lims = (struct in6_msource *)ims;
1035 		if (lims->im6sl_st[0] == imf->im6f_st[0]) {
1036 			nsrc0++;
1037 		}
1038 		if (lims->im6sl_st[1] == imf->im6f_st[1]) {
1039 			nsrc1++;
1040 		}
1041 		if (lims->im6sl_st[0] == lims->im6sl_st[1]) {
1042 			continue;
1043 		}
1044 		error = in6m_get_source(inm, &lims->im6s_addr, 0, &nims);
1045 		++schanged;
1046 		if (error) {
1047 			break;
1048 		}
1049 		im6s_merge(nims, lims, 0);
1050 	}
1051 	if (error) {
1052 		struct ip6_msource *__single bims;
1053 
1054 		RB_FOREACH_REVERSE_FROM(ims, ip6_msource_tree, nims) {
1055 			lims = (struct in6_msource *)ims;
1056 			if (lims->im6sl_st[0] == lims->im6sl_st[1]) {
1057 				continue;
1058 			}
1059 			(void) in6m_get_source(inm, &lims->im6s_addr, 1, &bims);
1060 			if (bims == NULL) {
1061 				continue;
1062 			}
1063 			im6s_merge(bims, lims, 1);
1064 		}
1065 		goto out_reap;
1066 	}
1067 
1068 	MLD_PRINTF(("%s: imf filters in-mode: %d at t0, %d at t1\n",
1069 	    __func__, nsrc0, nsrc1));
1070 
1071 	/* Handle transition between INCLUDE {n} and INCLUDE {} on socket. */
1072 	if (imf->im6f_st[0] == imf->im6f_st[1] &&
1073 	    imf->im6f_st[1] == MCAST_INCLUDE) {
1074 		if (nsrc1 == 0) {
1075 			MLD_PRINTF(("%s: --in on inm at t1\n", __func__));
1076 			--inm->in6m_st[1].iss_in;
1077 		}
1078 	}
1079 
1080 	/* Handle filter mode transition on socket. */
1081 	if (imf->im6f_st[0] != imf->im6f_st[1]) {
1082 		MLD_PRINTF(("%s: imf transition %d to %d\n",
1083 		    __func__, imf->im6f_st[0], imf->im6f_st[1]));
1084 
1085 		if (imf->im6f_st[0] == MCAST_EXCLUDE) {
1086 			MLD_PRINTF(("%s: --ex on inm at t1\n", __func__));
1087 			--inm->in6m_st[1].iss_ex;
1088 		} else if (imf->im6f_st[0] == MCAST_INCLUDE) {
1089 			MLD_PRINTF(("%s: --in on inm at t1\n", __func__));
1090 			--inm->in6m_st[1].iss_in;
1091 		}
1092 
1093 		if (imf->im6f_st[1] == MCAST_EXCLUDE) {
1094 			MLD_PRINTF(("%s: ex++ on inm at t1\n", __func__));
1095 			inm->in6m_st[1].iss_ex++;
1096 		} else if (imf->im6f_st[1] == MCAST_INCLUDE && nsrc1 > 0) {
1097 			MLD_PRINTF(("%s: in++ on inm at t1\n", __func__));
1098 			inm->in6m_st[1].iss_in++;
1099 		}
1100 	}
1101 
1102 	/*
1103 	 * Track inm filter state in terms of listener counts.
1104 	 * If there are any exclusive listeners, stack-wide
1105 	 * membership is exclusive.
1106 	 * Otherwise, if only inclusive listeners, stack-wide is inclusive.
1107 	 * If no listeners remain, state is undefined at t1,
1108 	 * and the MLD lifecycle for this group should finish.
1109 	 */
1110 	if (inm->in6m_st[1].iss_ex > 0) {
1111 		MLD_PRINTF(("%s: transition to EX\n", __func__));
1112 		inm->in6m_st[1].iss_fmode = MCAST_EXCLUDE;
1113 	} else if (inm->in6m_st[1].iss_in > 0) {
1114 		MLD_PRINTF(("%s: transition to IN\n", __func__));
1115 		inm->in6m_st[1].iss_fmode = MCAST_INCLUDE;
1116 	} else {
1117 		MLD_PRINTF(("%s: transition to UNDEF\n", __func__));
1118 		inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
1119 	}
1120 
1121 	/* Decrement ASM listener count on transition out of ASM mode. */
1122 	if (imf->im6f_st[0] == MCAST_EXCLUDE && nsrc0 == 0) {
1123 		if ((imf->im6f_st[1] != MCAST_EXCLUDE) ||
1124 		    (imf->im6f_st[1] == MCAST_EXCLUDE && nsrc1 > 0)) {
1125 			MLD_PRINTF(("%s: --asm on inm at t1\n", __func__));
1126 			--inm->in6m_st[1].iss_asm;
1127 		}
1128 	}
1129 
1130 	/* Increment ASM listener count on transition to ASM mode. */
1131 	if (imf->im6f_st[1] == MCAST_EXCLUDE && nsrc1 == 0) {
1132 		MLD_PRINTF(("%s: asm++ on inm at t1\n", __func__));
1133 		inm->in6m_st[1].iss_asm++;
1134 	}
1135 
1136 	MLD_PRINTF(("%s: merged imf 0x%llx to inm 0x%llx\n", __func__,
1137 	    (uint64_t)VM_KERNEL_ADDRPERM(imf),
1138 	    (uint64_t)VM_KERNEL_ADDRPERM(inm)));
1139 	in6m_print(inm);
1140 
1141 out_reap:
1142 	if (schanged > 0) {
1143 		MLD_PRINTF(("%s: sources changed; reaping\n", __func__));
1144 		in6m_reap(inm);
1145 	}
1146 	return error;
1147 }
1148 
1149 /*
1150  * Mark an in6_multi's filter set deltas as committed.
1151  * Called by MLD after a state change has been enqueued.
1152  */
1153 void
in6m_commit(struct in6_multi * inm)1154 in6m_commit(struct in6_multi *inm)
1155 {
1156 	struct ip6_msource      *ims;
1157 
1158 	IN6M_LOCK_ASSERT_HELD(inm);
1159 
1160 	MLD_PRINTF(("%s: commit inm 0x%llx\n", __func__,
1161 	    (uint64_t)VM_KERNEL_ADDRPERM(inm)));
1162 	MLD_PRINTF(("%s: pre commit:\n", __func__));
1163 	in6m_print(inm);
1164 
1165 	RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
1166 		ims->im6s_st[0] = ims->im6s_st[1];
1167 	}
1168 	inm->in6m_st[0] = inm->in6m_st[1];
1169 }
1170 
1171 /*
1172  * Reap unreferenced nodes from an in6_multi's filter set.
1173  */
1174 static void
in6m_reap(struct in6_multi * inm)1175 in6m_reap(struct in6_multi *inm)
1176 {
1177 	struct ip6_msource      *ims, *tims;
1178 
1179 	IN6M_LOCK_ASSERT_HELD(inm);
1180 
1181 	RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs, tims) {
1182 		if (ims->im6s_st[0].ex > 0 || ims->im6s_st[0].in > 0 ||
1183 		    ims->im6s_st[1].ex > 0 || ims->im6s_st[1].in > 0 ||
1184 		    ims->im6s_stp != 0) {
1185 			continue;
1186 		}
1187 		MLD_PRINTF(("%s: free ims 0x%llx\n", __func__,
1188 		    (uint64_t)VM_KERNEL_ADDRPERM(ims)));
1189 		RB_REMOVE(ip6_msource_tree, &inm->in6m_srcs, ims);
1190 		ip6ms_free(ims);
1191 		inm->in6m_nsrc--;
1192 	}
1193 }
1194 
1195 /*
1196  * Purge all source nodes from an in6_multi's filter set.
1197  */
1198 void
in6m_purge(struct in6_multi * inm)1199 in6m_purge(struct in6_multi *inm)
1200 {
1201 	struct ip6_msource      *ims, *tims;
1202 
1203 	IN6M_LOCK_ASSERT_HELD(inm);
1204 
1205 	RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs, tims) {
1206 		MLD_PRINTF(("%s: free ims 0x%llx\n", __func__,
1207 		    (uint64_t)VM_KERNEL_ADDRPERM(ims)));
1208 		RB_REMOVE(ip6_msource_tree, &inm->in6m_srcs, ims);
1209 		ip6ms_free(ims);
1210 		inm->in6m_nsrc--;
1211 	}
1212 }
1213 
1214 /*
1215  * Join a multicast address w/o sources.
1216  * KAME compatibility entry point.
1217  *
1218  */
1219 struct in6_multi_mship *
in6_joingroup(struct ifnet * ifp,struct in6_addr * mcaddr,int * errorp,int delay)1220 in6_joingroup(struct ifnet *ifp, struct in6_addr *mcaddr,
1221     int *errorp, int delay)
1222 {
1223 	struct in6_multi_mship *imm;
1224 	int error;
1225 
1226 	*errorp = 0;
1227 
1228 	imm = in6_multi_mship_alloc(Z_WAITOK);
1229 
1230 	error = in6_mc_join(ifp, mcaddr, NULL, &imm->i6mm_maddr, delay);
1231 	if (error) {
1232 		*errorp = error;
1233 		in6_multi_mship_free(imm);
1234 		return NULL;
1235 	}
1236 
1237 	return imm;
1238 }
1239 
1240 /*
1241  * Leave a multicast address w/o sources.
1242  * KAME compatibility entry point.
1243  */
1244 int
in6_leavegroup(struct in6_multi_mship * imm)1245 in6_leavegroup(struct in6_multi_mship *imm)
1246 {
1247 	if (imm->i6mm_maddr != NULL) {
1248 		in6_mc_leave(imm->i6mm_maddr, NULL);
1249 		IN6M_REMREF(imm->i6mm_maddr);
1250 		imm->i6mm_maddr = NULL;
1251 	}
1252 	in6_multi_mship_free(imm);
1253 	return 0;
1254 }
1255 
1256 /*
1257  * Join a multicast group; real entry point.
1258  *
1259  * Only preserves atomicity at inm level.
1260  * NOTE: imf argument cannot be const due to sys/tree.h limitations.
1261  *
1262  * If the MLD downcall fails, the group is not joined, and an error
1263  * code is returned.
1264  */
1265 int
in6_mc_join(struct ifnet * ifp,const struct in6_addr * mcaddr,struct in6_mfilter * imf,struct in6_multi ** pinm,const int delay)1266 in6_mc_join(struct ifnet *ifp, const struct in6_addr *mcaddr,
1267     /*const*/ struct in6_mfilter *imf, struct in6_multi **pinm,
1268     const int delay)
1269 {
1270 	struct in6_mfilter       timf;
1271 	struct in6_multi        *__single inm = NULL;
1272 	int                      error = 0;
1273 	struct mld_tparams       mtp;
1274 
1275 	/*
1276 	 * Sanity: Check scope zone ID was set for ifp, if and
1277 	 * only if group is scoped to an interface.
1278 	 */
1279 	VERIFY(IN6_IS_ADDR_MULTICAST(mcaddr));
1280 	if (in6_embedded_scope && (IN6_IS_ADDR_MC_LINKLOCAL(mcaddr) ||
1281 	    IN6_IS_ADDR_MC_INTFACELOCAL(mcaddr))) {
1282 		VERIFY(mcaddr->s6_addr16[1] != 0);
1283 	}
1284 
1285 	MLD_PRINTF(("%s: join %s on 0x%llx(%s))\n", __func__,
1286 	    ip6_sprintf(mcaddr), (uint64_t)VM_KERNEL_ADDRPERM(ifp),
1287 	    if_name(ifp)));
1288 
1289 	bzero(&mtp, sizeof(mtp));
1290 	*pinm = NULL;
1291 
1292 	/*
1293 	 * If no imf was specified (i.e. kernel consumer),
1294 	 * fake one up and assume it is an ASM join.
1295 	 */
1296 	if (imf == NULL) {
1297 		im6f_init(&timf, MCAST_UNDEFINED, MCAST_EXCLUDE);
1298 		imf = &timf;
1299 	}
1300 
1301 	error = in6_mc_get(ifp, mcaddr, &inm);
1302 	if (error) {
1303 		MLD_PRINTF(("%s: in6_mc_get() failure\n", __func__));
1304 		return error;
1305 	}
1306 
1307 	MLD_PRINTF(("%s: merge inm state\n", __func__));
1308 
1309 	IN6M_LOCK(inm);
1310 	error = in6m_merge(inm, imf);
1311 	if (error) {
1312 		MLD_PRINTF(("%s: failed to merge inm state\n", __func__));
1313 		goto out_in6m_release;
1314 	}
1315 
1316 	MLD_PRINTF(("%s: doing mld downcall\n", __func__));
1317 	error = mld_change_state(inm, &mtp, delay);
1318 	if (error) {
1319 		MLD_PRINTF(("%s: failed to update source\n", __func__));
1320 		im6f_rollback(imf);
1321 		goto out_in6m_release;
1322 	}
1323 
1324 out_in6m_release:
1325 	if (error) {
1326 		MLD_PRINTF(("%s: dropping ref on 0x%llx\n", __func__,
1327 		    (uint64_t)VM_KERNEL_ADDRPERM(inm)));
1328 		IN6M_UNLOCK(inm);
1329 		IN6M_REMREF(inm);
1330 	} else {
1331 		IN6M_UNLOCK(inm);
1332 		*pinm = inm;    /* keep refcount from in6_mc_get() */
1333 	}
1334 
1335 	/* schedule timer now that we've dropped the lock(s) */
1336 	mld_set_fast_timeout(&mtp);
1337 
1338 	return error;
1339 }
1340 
1341 /*
1342  * Leave a multicast group; real entry point.
1343  * All source filters will be expunged.
1344  *
1345  * Only preserves atomicity at inm level.
1346  *
1347  * Holding the write lock for the INP which contains imf
1348  * is highly advisable. We can't assert for it as imf does not
1349  * contain a back-pointer to the owning inp.
1350  *
1351  * Note: This is not the same as in6m_release(*) as this function also
1352  * makes a state change downcall into MLD.
1353  */
1354 int
in6_mc_leave(struct in6_multi * inm,struct in6_mfilter * imf)1355 in6_mc_leave(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
1356 {
1357 	struct in6_mfilter       timf;
1358 	int                      error, lastref;
1359 	struct mld_tparams       mtp;
1360 
1361 	bzero(&mtp, sizeof(mtp));
1362 	error = 0;
1363 
1364 	IN6M_LOCK_ASSERT_NOTHELD(inm);
1365 
1366 	in6_multihead_lock_exclusive();
1367 	IN6M_LOCK(inm);
1368 
1369 	MLD_PRINTF(("%s: leave inm 0x%llx, %s/%s%d, imf 0x%llx\n", __func__,
1370 	    (uint64_t)VM_KERNEL_ADDRPERM(inm), ip6_sprintf(&inm->in6m_addr),
1371 	    (in6m_is_ifp_detached(inm) ? "null" : inm->in6m_ifp->if_name),
1372 	    inm->in6m_ifp->if_unit, (uint64_t)VM_KERNEL_ADDRPERM(imf)));
1373 
1374 	/*
1375 	 * If no imf was specified (i.e. kernel consumer),
1376 	 * fake one up and assume it is an ASM join.
1377 	 */
1378 	if (imf == NULL) {
1379 		im6f_init(&timf, MCAST_EXCLUDE, MCAST_UNDEFINED);
1380 		imf = &timf;
1381 	}
1382 
1383 	/*
1384 	 * Begin state merge transaction at MLD layer.
1385 	 *
1386 	 * As this particular invocation should not cause any memory
1387 	 * to be allocated, and there is no opportunity to roll back
1388 	 * the transaction, it MUST NOT fail.
1389 	 */
1390 	MLD_PRINTF(("%s: merge inm state\n", __func__));
1391 
1392 	error = in6m_merge(inm, imf);
1393 	KASSERT(error == 0, ("%s: failed to merge inm state\n", __func__));
1394 
1395 	MLD_PRINTF(("%s: doing mld downcall\n", __func__));
1396 	error = mld_change_state(inm, &mtp, 0);
1397 #if MLD_DEBUG
1398 	if (error) {
1399 		MLD_PRINTF(("%s: failed mld downcall\n", __func__));
1400 	}
1401 #endif
1402 	lastref = in6_multi_detach(inm);
1403 	VERIFY(!lastref || (!(inm->in6m_debug & IFD_ATTACHED) &&
1404 	    inm->in6m_reqcnt == 0));
1405 	IN6M_UNLOCK(inm);
1406 	in6_multihead_lock_done();
1407 
1408 	if (lastref) {
1409 		IN6M_REMREF(inm);       /* for in6_multihead list */
1410 	}
1411 	/* schedule timer now that we've dropped the lock(s) */
1412 	mld_set_fast_timeout(&mtp);
1413 
1414 	return error;
1415 }
1416 
1417 /*
1418  * Block or unblock an ASM multicast source on an inpcb.
1419  * This implements the delta-based API described in RFC 3678.
1420  *
1421  * The delta-based API applies only to exclusive-mode memberships.
1422  * An MLD downcall will be performed.
1423  *
1424  * Return 0 if successful, otherwise return an appropriate error code.
1425  */
1426 static int
in6p_block_unblock_source(struct inpcb * inp,struct sockopt * sopt)1427 in6p_block_unblock_source(struct inpcb *inp, struct sockopt *sopt)
1428 {
1429 	struct group_source_req          gsr;
1430 	struct sockaddr_in6             *gsa, *ssa;
1431 	struct ifnet                    *ifp;
1432 	struct in6_mfilter              *imf;
1433 	struct ip6_moptions             *imo;
1434 	struct in6_msource              *ims;
1435 	struct in6_multi                *inm;
1436 	size_t                           idx;
1437 	uint8_t                         fmode;
1438 	int                              error, doblock;
1439 	struct mld_tparams               mtp;
1440 
1441 	bzero(&mtp, sizeof(mtp));
1442 	ifp = NULL;
1443 	error = 0;
1444 	doblock = 0;
1445 
1446 	memset(&gsr, 0, sizeof(struct group_source_req));
1447 	gsa = SIN6(&gsr.gsr_group);
1448 	ssa = SIN6(&gsr.gsr_source);
1449 
1450 	switch (sopt->sopt_name) {
1451 	case MCAST_BLOCK_SOURCE:
1452 	case MCAST_UNBLOCK_SOURCE:
1453 		error = sooptcopyin(sopt, &gsr,
1454 		    sizeof(struct group_source_req),
1455 		    sizeof(struct group_source_req));
1456 		if (error) {
1457 			return error;
1458 		}
1459 
1460 		if (gsa->sin6_family != AF_INET6 ||
1461 		    gsa->sin6_len != sizeof(struct sockaddr_in6)) {
1462 			return EINVAL;
1463 		}
1464 
1465 		if (ssa->sin6_family != AF_INET6 ||
1466 		    ssa->sin6_len != sizeof(struct sockaddr_in6)) {
1467 			return EINVAL;
1468 		}
1469 
1470 		ifnet_head_lock_shared();
1471 		if (gsr.gsr_interface == 0 || !IF_INDEX_IN_RANGE(gsr.gsr_interface)) {
1472 			ifnet_head_done();
1473 			return EADDRNOTAVAIL;
1474 		}
1475 
1476 		ifp = ifindex2ifnet[gsr.gsr_interface];
1477 		ifnet_head_done();
1478 
1479 		if (ifp == NULL) {
1480 			return EADDRNOTAVAIL;
1481 		}
1482 
1483 		if (sopt->sopt_name == MCAST_BLOCK_SOURCE) {
1484 			doblock = 1;
1485 		}
1486 		break;
1487 
1488 	default:
1489 		MLD_PRINTF(("%s: unknown sopt_name %d\n",
1490 		    __func__, sopt->sopt_name));
1491 		return EOPNOTSUPP;
1492 	}
1493 
1494 	if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6_addr)) {
1495 		return EINVAL;
1496 	}
1497 
1498 	(void) in6_setscope(&gsa->sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&gsa->sin6_scope_id));
1499 
1500 	/*
1501 	 * Check if we are actually a member of this group.
1502 	 */
1503 	imo = in6p_findmoptions(inp);
1504 	if (imo == NULL) {
1505 		return ENOMEM;
1506 	}
1507 
1508 	IM6O_LOCK(imo);
1509 	idx = im6o_match_group(imo, ifp, gsa);
1510 	if (idx == (size_t)-1 || imo->im6o_mfilters == NULL) {
1511 		error = EADDRNOTAVAIL;
1512 		goto out_imo_locked;
1513 	}
1514 
1515 	VERIFY(imo->im6o_mfilters != NULL);
1516 	imf = &imo->im6o_mfilters[idx];
1517 	inm = imo->im6o_membership[idx];
1518 
1519 	/*
1520 	 * Attempting to use the delta-based API on an
1521 	 * non exclusive-mode membership is an error.
1522 	 */
1523 	fmode = imf->im6f_st[0];
1524 	if (fmode != MCAST_EXCLUDE) {
1525 		error = EINVAL;
1526 		goto out_imo_locked;
1527 	}
1528 
1529 	/*
1530 	 * Deal with error cases up-front:
1531 	 *  Asked to block, but already blocked; or
1532 	 *  Asked to unblock, but nothing to unblock.
1533 	 * If adding a new block entry, allocate it.
1534 	 */
1535 	ims = im6o_match_source(imo, idx, ssa);
1536 	if ((ims != NULL && doblock) || (ims == NULL && !doblock)) {
1537 		MLD_PRINTF(("%s: source %s %spresent\n", __func__,
1538 		    ip6_sprintf(&ssa->sin6_addr),
1539 		    doblock ? "" : "not "));
1540 		error = EADDRNOTAVAIL;
1541 		goto out_imo_locked;
1542 	}
1543 
1544 	/*
1545 	 * Begin state merge transaction at socket layer.
1546 	 */
1547 	if (doblock) {
1548 		MLD_PRINTF(("%s: %s source\n", __func__, "block"));
1549 		ims = im6f_graft(imf, fmode, ssa);
1550 		if (ims == NULL) {
1551 			error = ENOMEM;
1552 		}
1553 	} else {
1554 		MLD_PRINTF(("%s: %s source\n", __func__, "allow"));
1555 		error = im6f_prune(imf, ssa);
1556 	}
1557 
1558 	if (error) {
1559 		MLD_PRINTF(("%s: merge imf state failed\n", __func__));
1560 		goto out_im6f_rollback;
1561 	}
1562 
1563 	/*
1564 	 * Begin state merge transaction at MLD layer.
1565 	 */
1566 	IN6M_LOCK(inm);
1567 	MLD_PRINTF(("%s: merge inm state\n", __func__));
1568 	error = in6m_merge(inm, imf);
1569 	if (error) {
1570 		MLD_PRINTF(("%s: failed to merge inm state\n", __func__));
1571 		IN6M_UNLOCK(inm);
1572 		goto out_im6f_rollback;
1573 	}
1574 
1575 	MLD_PRINTF(("%s: doing mld downcall\n", __func__));
1576 	error = mld_change_state(inm, &mtp, 0);
1577 	IN6M_UNLOCK(inm);
1578 #if MLD_DEBUG
1579 	if (error) {
1580 		MLD_PRINTF(("%s: failed mld downcall\n", __func__));
1581 	}
1582 #endif
1583 
1584 out_im6f_rollback:
1585 	if (error) {
1586 		im6f_rollback(imf);
1587 	} else {
1588 		im6f_commit(imf);
1589 	}
1590 
1591 	im6f_reap(imf);
1592 
1593 out_imo_locked:
1594 	IM6O_UNLOCK(imo);
1595 	IM6O_REMREF(imo);       /* from in6p_findmoptions() */
1596 
1597 	/* schedule timer now that we've dropped the lock(s) */
1598 	mld_set_fast_timeout(&mtp);
1599 
1600 	return error;
1601 }
1602 
1603 /*
1604  * Given an inpcb, return its multicast options structure pointer.  Accepts
1605  * an unlocked inpcb pointer, but will return it locked.  May sleep.
1606  *
1607  */
1608 static struct ip6_moptions *
in6p_findmoptions(struct inpcb * inp)1609 in6p_findmoptions(struct inpcb *inp)
1610 {
1611 	struct ip6_moptions      *imo;
1612 	struct in6_multi        **immp;
1613 	struct in6_mfilter       *imfp;
1614 	size_t                    idx;
1615 
1616 	if ((imo = inp->in6p_moptions) != NULL) {
1617 		IM6O_ADDREF(imo);       /* for caller */
1618 		return imo;
1619 	}
1620 
1621 	imo = ip6_allocmoptions(Z_WAITOK);
1622 	if (imo == NULL) {
1623 		return NULL;
1624 	}
1625 
1626 	immp = kalloc_type(struct in6_multi *, IPV6_MIN_MEMBERSHIPS,
1627 	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
1628 	imfp = kalloc_type(struct in6_mfilter, IPV6_MIN_MEMBERSHIPS,
1629 	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
1630 
1631 	imo->im6o_multicast_ifp = NULL;
1632 	imo->im6o_multicast_hlim = (u_char)ip6_defmcasthlim;
1633 	imo->im6o_multicast_loop = (u_char)in6_mcast_loop;
1634 	imo->im6o_num_memberships = 0;
1635 	imo->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
1636 	imo->im6o_membership = immp;
1637 	imo->im6o_max_filters = IPV6_MIN_MEMBERSHIPS;
1638 	imo->im6o_mfilters = imfp;
1639 
1640 	/* Initialize per-group source filters. */
1641 	for (idx = 0; idx < IPV6_MIN_MEMBERSHIPS; idx++) {
1642 		im6f_init(&imfp[idx], MCAST_UNDEFINED, MCAST_EXCLUDE);
1643 	}
1644 
1645 	inp->in6p_moptions = imo; /* keep reference from ip6_allocmoptions() */
1646 	IM6O_ADDREF(imo);       /* for caller */
1647 
1648 	return imo;
1649 }
1650 
1651 /*
1652  * Atomically get source filters on a socket for an IPv6 multicast group.
1653  * Called with INP lock held; returns with lock released.
1654  */
1655 static int
in6p_get_source_filters(struct inpcb * inp,struct sockopt * sopt)1656 in6p_get_source_filters(struct inpcb *inp, struct sockopt *sopt)
1657 {
1658 	struct __msfilterreq64  msfr = {}, msfr64;
1659 	struct __msfilterreq32  msfr32;
1660 	struct sockaddr_in6     *gsa;
1661 	struct ifnet            *ifp;
1662 	struct ip6_moptions     *imo;
1663 	struct in6_mfilter      *imf;
1664 	struct ip6_msource      *ims;
1665 	struct in6_msource      *lims;
1666 	struct sockaddr_in6     *psin;
1667 	struct sockaddr_storage *ptss;
1668 	struct sockaddr_storage *tss;
1669 	int                      error;
1670 	size_t                   idx, nsrcs, ncsrcs;
1671 	user_addr_t              tmp_ptr;
1672 
1673 	const bool is_currproc_64bit_proc = IS_64BIT_PROCESS(current_proc());
1674 
1675 	imo = inp->in6p_moptions;
1676 	VERIFY(imo != NULL);
1677 
1678 	if (is_currproc_64bit_proc) {
1679 		error = sooptcopyin(sopt, &msfr64,
1680 		    sizeof(struct __msfilterreq64),
1681 		    sizeof(struct __msfilterreq64));
1682 		if (error) {
1683 			return error;
1684 		}
1685 		/* we never use msfr.msfr_srcs; */
1686 		memcpy(&msfr, &msfr64, sizeof(msfr64));
1687 	} else {
1688 		error = sooptcopyin(sopt, &msfr32,
1689 		    sizeof(struct __msfilterreq32),
1690 		    sizeof(struct __msfilterreq32));
1691 		if (error) {
1692 			return error;
1693 		}
1694 		/* we never use msfr.msfr_srcs; */
1695 		memcpy(&msfr, &msfr32, sizeof(msfr32));
1696 	}
1697 
1698 	if (msfr.msfr_group.ss_family != AF_INET6 ||
1699 	    msfr.msfr_group.ss_len != sizeof(struct sockaddr_in6)) {
1700 		return EINVAL;
1701 	}
1702 
1703 	gsa = SIN6(&msfr.msfr_group);
1704 	if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6_addr)) {
1705 		return EINVAL;
1706 	}
1707 
1708 	ifnet_head_lock_shared();
1709 	if (msfr.msfr_ifindex == 0 || !IF_INDEX_IN_RANGE(msfr.msfr_ifindex)) {
1710 		ifnet_head_done();
1711 		return EADDRNOTAVAIL;
1712 	}
1713 	ifp = ifindex2ifnet[msfr.msfr_ifindex];
1714 	ifnet_head_done();
1715 
1716 	if (ifp == NULL) {
1717 		return EADDRNOTAVAIL;
1718 	}
1719 
1720 	if ((size_t) msfr.msfr_nsrcs >
1721 	    UINT32_MAX / sizeof(struct sockaddr_storage)) {
1722 		msfr.msfr_nsrcs = UINT32_MAX / sizeof(struct sockaddr_storage);
1723 	}
1724 
1725 	if (msfr.msfr_nsrcs > in6_mcast_maxsocksrc) {
1726 		msfr.msfr_nsrcs = (uint32_t)in6_mcast_maxsocksrc;
1727 	}
1728 
1729 	(void)in6_setscope(&gsa->sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&gsa->sin6_scope_id));
1730 
1731 	IM6O_LOCK(imo);
1732 	/*
1733 	 * Lookup group on the socket.
1734 	 */
1735 	idx = im6o_match_group(imo, ifp, gsa);
1736 	if (idx == (size_t)-1 || imo->im6o_mfilters == NULL) {
1737 		IM6O_UNLOCK(imo);
1738 		return EADDRNOTAVAIL;
1739 	}
1740 	imf = &imo->im6o_mfilters[idx];
1741 
1742 	/*
1743 	 * Ignore memberships which are in limbo.
1744 	 */
1745 	if (imf->im6f_st[1] == MCAST_UNDEFINED) {
1746 		IM6O_UNLOCK(imo);
1747 		return EAGAIN;
1748 	}
1749 	msfr.msfr_fmode = imf->im6f_st[1];
1750 
1751 	/*
1752 	 * If the user specified a buffer, copy out the source filter
1753 	 * entries to userland gracefully.
1754 	 * We only copy out the number of entries which userland
1755 	 * has asked for, but we always tell userland how big the
1756 	 * buffer really needs to be.
1757 	 */
1758 	tss = NULL;
1759 
1760 	if (is_currproc_64bit_proc) {
1761 		tmp_ptr = (user_addr_t)msfr64.msfr_srcs;
1762 	} else {
1763 		tmp_ptr = CAST_USER_ADDR_T(msfr32.msfr_srcs);
1764 	}
1765 
1766 	if (tmp_ptr != USER_ADDR_NULL && msfr.msfr_nsrcs > 0) {
1767 		tss = kalloc_data((size_t) msfr.msfr_nsrcs * sizeof(*tss),
1768 		    Z_WAITOK | Z_ZERO);
1769 		if (tss == NULL) {
1770 			IM6O_UNLOCK(imo);
1771 			return ENOBUFS;
1772 		}
1773 	}
1774 
1775 	/*
1776 	 * Count number of sources in-mode at t0.
1777 	 * If buffer space exists and remains, copy out source entries.
1778 	 */
1779 	nsrcs = msfr.msfr_nsrcs;
1780 	ncsrcs = 0;
1781 	ptss = tss;
1782 	RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
1783 		lims = (struct in6_msource *)ims;
1784 		if (lims->im6sl_st[0] == MCAST_UNDEFINED ||
1785 		    lims->im6sl_st[0] != imf->im6f_st[0]) {
1786 			continue;
1787 		}
1788 		if (tss != NULL && nsrcs > 0) {
1789 			psin = SIN6(ptss);
1790 			psin->sin6_family = AF_INET6;
1791 			psin->sin6_len = sizeof(struct sockaddr_in6);
1792 			psin->sin6_addr = lims->im6s_addr;
1793 			psin->sin6_port = 0;
1794 			--nsrcs;
1795 			++ptss;
1796 			++ncsrcs;
1797 		}
1798 	}
1799 
1800 	IM6O_UNLOCK(imo);
1801 
1802 	if (tss != NULL) {
1803 		error = copyout(tss, tmp_ptr, ncsrcs * sizeof(*tss));
1804 		kfree_data(tss, (size_t) msfr.msfr_nsrcs * sizeof(*tss));
1805 		if (error) {
1806 			return error;
1807 		}
1808 	}
1809 
1810 	msfr.msfr_nsrcs = (uint32_t)ncsrcs;
1811 	if (is_currproc_64bit_proc) {
1812 		msfr64.msfr_ifindex = msfr.msfr_ifindex;
1813 		msfr64.msfr_fmode   = msfr.msfr_fmode;
1814 		msfr64.msfr_nsrcs   = msfr.msfr_nsrcs;
1815 		memcpy(&msfr64.msfr_group, &msfr.msfr_group,
1816 		    sizeof(struct sockaddr_storage));
1817 		error = sooptcopyout(sopt, &msfr64,
1818 		    sizeof(struct __msfilterreq64));
1819 	} else {
1820 		msfr32.msfr_ifindex = msfr.msfr_ifindex;
1821 		msfr32.msfr_fmode   = msfr.msfr_fmode;
1822 		msfr32.msfr_nsrcs   = msfr.msfr_nsrcs;
1823 		memcpy(&msfr32.msfr_group, &msfr.msfr_group,
1824 		    sizeof(struct sockaddr_storage));
1825 		error = sooptcopyout(sopt, &msfr32,
1826 		    sizeof(struct __msfilterreq32));
1827 	}
1828 
1829 	return error;
1830 }
1831 
1832 /*
1833  * Return the IP multicast options in response to user getsockopt().
1834  */
1835 int
ip6_getmoptions(struct inpcb * inp,struct sockopt * sopt)1836 ip6_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1837 {
1838 	struct ip6_moptions     *im6o;
1839 	int                      error;
1840 	u_int                    optval;
1841 
1842 	im6o = inp->in6p_moptions;
1843 	/*
1844 	 * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
1845 	 * or is a divert socket, reject it.
1846 	 */
1847 	if (SOCK_PROTO(inp->inp_socket) == IPPROTO_DIVERT ||
1848 	    (SOCK_TYPE(inp->inp_socket) != SOCK_RAW &&
1849 	    SOCK_TYPE(inp->inp_socket) != SOCK_DGRAM)) {
1850 		return EOPNOTSUPP;
1851 	}
1852 
1853 	error = 0;
1854 	switch (sopt->sopt_name) {
1855 	case IPV6_MULTICAST_IF:
1856 		if (im6o != NULL) {
1857 			IM6O_LOCK(im6o);
1858 		}
1859 		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL) {
1860 			optval = 0;
1861 		} else {
1862 			optval = im6o->im6o_multicast_ifp->if_index;
1863 		}
1864 		if (im6o != NULL) {
1865 			IM6O_UNLOCK(im6o);
1866 		}
1867 		error = sooptcopyout(sopt, &optval, sizeof(u_int));
1868 		break;
1869 
1870 	case IPV6_MULTICAST_HOPS:
1871 		if (im6o == NULL) {
1872 			optval = ip6_defmcasthlim;
1873 		} else {
1874 			IM6O_LOCK(im6o);
1875 			optval = im6o->im6o_multicast_hlim;
1876 			IM6O_UNLOCK(im6o);
1877 		}
1878 		error = sooptcopyout(sopt, &optval, sizeof(u_int));
1879 		break;
1880 
1881 	case IPV6_MULTICAST_LOOP:
1882 		if (im6o == NULL) {
1883 			optval = in6_mcast_loop; /* XXX VIMAGE */
1884 		} else {
1885 			IM6O_LOCK(im6o);
1886 			optval = im6o->im6o_multicast_loop;
1887 			IM6O_UNLOCK(im6o);
1888 		}
1889 		error = sooptcopyout(sopt, &optval, sizeof(u_int));
1890 		break;
1891 
1892 	case IPV6_MSFILTER:
1893 		if (im6o == NULL) {
1894 			error = EADDRNOTAVAIL;
1895 		} else {
1896 			error = in6p_get_source_filters(inp, sopt);
1897 		}
1898 		break;
1899 
1900 	default:
1901 		error = ENOPROTOOPT;
1902 		break;
1903 	}
1904 
1905 	return error;
1906 }
1907 
1908 /*
1909  * Look up the ifnet to use for a multicast group membership,
1910  * given the address of an IPv6 group.
1911  *
1912  * This routine exists to support legacy IPv6 multicast applications.
1913  *
1914  * If inp is non-NULL and is bound to an interface, use this socket's
1915  * inp_boundif for any required routing table lookup.
1916  *
1917  * If the route lookup fails, return NULL.
1918  *
1919  * FUTURE: Support multiple forwarding tables for IPv6.
1920  *
1921  * Returns NULL if no ifp could be found.
1922  */
1923 static struct ifnet *
in6p_lookup_mcast_ifp(const struct inpcb * in6p,const struct sockaddr_in6 * gsin6)1924 in6p_lookup_mcast_ifp(const struct inpcb *in6p,
1925     const struct sockaddr_in6 *gsin6)
1926 {
1927 	struct route_in6         ro6;
1928 	struct ifnet            *ifp;
1929 	unsigned int            ifscope = IFSCOPE_NONE;
1930 
1931 	VERIFY(gsin6->sin6_family == AF_INET6);
1932 	if (IN6_IS_ADDR_MULTICAST(&gsin6->sin6_addr) == 0) {
1933 		return NULL;
1934 	}
1935 	if (in6p != NULL && (in6p->in6p_vflag & INP_IPV6) == 0) {
1936 		return NULL;
1937 	}
1938 
1939 	if (in6p != NULL && (in6p->inp_flags & INP_BOUND_IF)) {
1940 		ifscope = in6p->inp_boundifp->if_index;
1941 	}
1942 
1943 	ifp = NULL;
1944 	memset(&ro6, 0, sizeof(struct route_in6));
1945 	memcpy(&ro6.ro_dst, gsin6, sizeof(struct sockaddr_in6));
1946 	rtalloc_scoped_ign((struct route *)&ro6, 0, ifscope);
1947 	if (ro6.ro_rt != NULL) {
1948 		ifp = ro6.ro_rt->rt_ifp;
1949 		VERIFY(ifp != NULL);
1950 	}
1951 	ROUTE_RELEASE(&ro6);
1952 
1953 	return ifp;
1954 }
1955 
1956 /*
1957  * Since ipv6_mreq contains an ifindex and ip_mreq contains an AF_INET
1958  * address, we need to lookup the AF_INET address when translating an
1959  * ipv6_mreq structure into an ipmreq structure.
1960  * This is used when userland performs multicast setsockopt() on AF_INET6
1961  * sockets with AF_INET multicast addresses (IPv6 v4 mapped addresses).
1962  */
1963 static int
in6p_lookup_v4addr(struct ipv6_mreq * mreq,struct ip_mreq * v4mreq)1964 in6p_lookup_v4addr(struct ipv6_mreq *mreq, struct ip_mreq *v4mreq)
1965 {
1966 	struct ifnet *ifp;
1967 	struct ifaddr *ifa;
1968 	struct sockaddr_in *sin;
1969 
1970 	ifnet_head_lock_shared();
1971 	if (!IF_INDEX_IN_RANGE(mreq->ipv6mr_interface)) {
1972 		ifnet_head_done();
1973 		return EADDRNOTAVAIL;
1974 	} else {
1975 		ifp = ifindex2ifnet[mreq->ipv6mr_interface];
1976 	}
1977 	ifnet_head_done();
1978 	if (ifp == NULL) {
1979 		return EADDRNOTAVAIL;
1980 	}
1981 	ifa = ifa_ifpgetprimary(ifp, AF_INET);
1982 	if (ifa == NULL) {
1983 		return EADDRNOTAVAIL;
1984 	}
1985 	sin = SIN(ifa->ifa_addr);
1986 	v4mreq->imr_interface.s_addr = sin->sin_addr.s_addr;
1987 	ifa_remref(ifa);
1988 
1989 	return 0;
1990 }
1991 
1992 /*
1993  * Join an IPv6 multicast group, possibly with a source.
1994  *
1995  * FIXME: The KAME use of the unspecified address (::)
1996  * to join *all* multicast groups is currently unsupported.
1997  */
1998 static int
in6p_join_group(struct inpcb * inp,struct sockopt * sopt)1999 in6p_join_group(struct inpcb *inp, struct sockopt *sopt)
2000 {
2001 	struct group_source_req          gsr;
2002 	struct sockaddr_in6             *gsa, *ssa;
2003 	struct ifnet                    *ifp;
2004 	struct in6_mfilter              *imf;
2005 	struct ip6_moptions             *imo;
2006 	struct in6_multi                *__single inm = NULL;
2007 	struct in6_msource              *lims = NULL;
2008 	size_t                           idx;
2009 	int                              error, is_new;
2010 	struct mld_tparams              mtp;
2011 
2012 	bzero(&mtp, sizeof(mtp));
2013 	ifp = NULL;
2014 	imf = NULL;
2015 	error = 0;
2016 	is_new = 0;
2017 
2018 	memset(&gsr, 0, sizeof(struct group_source_req));
2019 	gsa = SIN6(&gsr.gsr_group);
2020 	ssa = SIN6(&gsr.gsr_source);
2021 
2022 	/*
2023 	 * Chew everything into struct group_source_req.
2024 	 * Overwrite the port field if present, as the sockaddr
2025 	 * being copied in may be matched with a binary comparison.
2026 	 * Ignore passed-in scope ID.
2027 	 */
2028 	switch (sopt->sopt_name) {
2029 	case IPV6_JOIN_GROUP: {
2030 		struct ipv6_mreq mreq;
2031 
2032 		error = sooptcopyin(sopt, &mreq, sizeof(struct ipv6_mreq),
2033 		    sizeof(struct ipv6_mreq));
2034 		if (error) {
2035 			return error;
2036 		}
2037 		if (IN6_IS_ADDR_V4MAPPED(&mreq.ipv6mr_multiaddr)) {
2038 			struct ip_mreq v4mreq;
2039 			struct sockopt v4sopt;
2040 
2041 			v4mreq.imr_multiaddr.s_addr =
2042 			    mreq.ipv6mr_multiaddr.s6_addr32[3];
2043 			if (mreq.ipv6mr_interface == 0) {
2044 				v4mreq.imr_interface.s_addr = INADDR_ANY;
2045 			} else {
2046 				error = in6p_lookup_v4addr(&mreq, &v4mreq);
2047 			}
2048 			if (error) {
2049 				return error;
2050 			}
2051 			v4sopt.sopt_dir     = SOPT_SET;
2052 			v4sopt.sopt_level   = sopt->sopt_level;
2053 			v4sopt.sopt_name    = IP_ADD_MEMBERSHIP;
2054 			v4sopt.sopt_val     = CAST_USER_ADDR_T(&v4mreq);
2055 			v4sopt.sopt_valsize = sizeof(v4mreq);
2056 			v4sopt.sopt_p       = kernproc;
2057 
2058 			return inp_join_group(inp, &v4sopt);
2059 		}
2060 		gsa->sin6_family = AF_INET6;
2061 		gsa->sin6_len = sizeof(struct sockaddr_in6);
2062 		gsa->sin6_addr = mreq.ipv6mr_multiaddr;
2063 
2064 		/* Only allow IPv6 multicast addresses */
2065 		if (IN6_IS_ADDR_MULTICAST(&gsa->sin6_addr) == 0) {
2066 			return EINVAL;
2067 		}
2068 
2069 		if (mreq.ipv6mr_interface == 0) {
2070 			ifp = in6p_lookup_mcast_ifp(inp, gsa);
2071 		} else {
2072 			ifnet_head_lock_shared();
2073 			if (!IF_INDEX_IN_RANGE(mreq.ipv6mr_interface)) {
2074 				ifnet_head_done();
2075 				return EADDRNOTAVAIL;
2076 			}
2077 			ifp = ifindex2ifnet[mreq.ipv6mr_interface];
2078 			ifnet_head_done();
2079 		}
2080 		MLD_PRINTF(("%s: ipv6mr_interface = %d, ifp = 0x%llx\n",
2081 		    __func__, mreq.ipv6mr_interface,
2082 		    (uint64_t)VM_KERNEL_ADDRPERM(ifp)));
2083 		break;
2084 	}
2085 
2086 	case MCAST_JOIN_GROUP:
2087 	case MCAST_JOIN_SOURCE_GROUP:
2088 		if (sopt->sopt_name == MCAST_JOIN_GROUP) {
2089 			error = sooptcopyin(sopt, &gsr,
2090 			    sizeof(struct group_req),
2091 			    sizeof(struct group_req));
2092 		} else if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
2093 			error = sooptcopyin(sopt, &gsr,
2094 			    sizeof(struct group_source_req),
2095 			    sizeof(struct group_source_req));
2096 		}
2097 		if (error) {
2098 			return error;
2099 		}
2100 
2101 		if (gsa->sin6_family != AF_INET6 ||
2102 		    gsa->sin6_len != sizeof(struct sockaddr_in6)) {
2103 			return EINVAL;
2104 		}
2105 
2106 		if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
2107 			if (ssa->sin6_family != AF_INET6 ||
2108 			    ssa->sin6_len != sizeof(struct sockaddr_in6)) {
2109 				return EINVAL;
2110 			}
2111 			if (IN6_IS_ADDR_MULTICAST(&ssa->sin6_addr)) {
2112 				return EINVAL;
2113 			}
2114 			/*
2115 			 * TODO: Validate embedded scope ID in source
2116 			 * list entry against passed-in ifp, if and only
2117 			 * if source list filter entry is iface or node local.
2118 			 */
2119 			in6_clearscope(&ssa->sin6_addr);
2120 			ssa->sin6_port = 0;
2121 			ssa->sin6_scope_id = 0;
2122 		}
2123 
2124 		ifnet_head_lock_shared();
2125 		if (gsr.gsr_interface == 0 ||
2126 		    !IF_INDEX_IN_RANGE(gsr.gsr_interface)) {
2127 			ifnet_head_done();
2128 			return EADDRNOTAVAIL;
2129 		}
2130 		ifp = ifindex2ifnet[gsr.gsr_interface];
2131 		ifnet_head_done();
2132 		break;
2133 
2134 	default:
2135 		MLD_PRINTF(("%s: unknown sopt_name %d\n",
2136 		    __func__, sopt->sopt_name));
2137 		return EOPNOTSUPP;
2138 	}
2139 
2140 	if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6_addr)) {
2141 		return EINVAL;
2142 	}
2143 
2144 	if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
2145 		return EADDRNOTAVAIL;
2146 	}
2147 
2148 	INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_mcast_join_total);
2149 	/*
2150 	 * TBD: revisit the criteria for non-OS initiated joins
2151 	 */
2152 	if (inp->inp_lport == htons(5353)) {
2153 		INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_mcast_join_os_total);
2154 	}
2155 
2156 	gsa->sin6_port = 0;
2157 	if (in6_embedded_scope) {
2158 		gsa->sin6_scope_id = 0;
2159 	}
2160 	(void)in6_setscope(&gsa->sin6_addr, ifp, &gsa->sin6_scope_id);
2161 	if (!in6_embedded_scope) {
2162 		if ((IN6_IS_ADDR_MC_LINKLOCAL(&gsa->sin6_addr) ||
2163 		    IN6_IS_ADDR_MC_INTFACELOCAL(&gsa->sin6_addr)) &&
2164 		    gsa->sin6_scope_id == 0) {
2165 			return EINVAL;
2166 		}
2167 	}
2168 
2169 	/*
2170 	 * Some addresses are not valid without an embedded scopeid.
2171 	 * This check must be present because otherwise we will later hit
2172 	 * a VERIFY() in in6_mc_join().
2173 	 */
2174 	if ((IN6_IS_ADDR_MC_LINKLOCAL(&gsa->sin6_addr) ||
2175 	    IN6_IS_ADDR_MC_INTFACELOCAL(&gsa->sin6_addr)) &&
2176 	    gsa->sin6_scope_id == 0) {
2177 		return EINVAL;
2178 	}
2179 
2180 	if (in6_embedded_scope) {
2181 		gsa->sin6_scope_id = 0;
2182 	}
2183 
2184 	imo = in6p_findmoptions(inp);
2185 	if (imo == NULL) {
2186 		return ENOMEM;
2187 	}
2188 
2189 	IM6O_LOCK(imo);
2190 	idx = im6o_match_group(imo, ifp, gsa);
2191 	if (idx == (size_t)-1) {
2192 		is_new = 1;
2193 	} else {
2194 		inm = imo->im6o_membership[idx];
2195 		imf = &imo->im6o_mfilters[idx];
2196 		if (ssa->sin6_family != AF_UNSPEC) {
2197 			/*
2198 			 * MCAST_JOIN_SOURCE_GROUP on an exclusive membership
2199 			 * is an error. On an existing inclusive membership,
2200 			 * it just adds the source to the filter list.
2201 			 */
2202 			if (imf->im6f_st[1] != MCAST_INCLUDE) {
2203 				error = EINVAL;
2204 				goto out_imo_locked;
2205 			}
2206 			/*
2207 			 * Throw out duplicates.
2208 			 *
2209 			 * XXX FIXME: This makes a naive assumption that
2210 			 * even if entries exist for *ssa in this imf,
2211 			 * they will be rejected as dupes, even if they
2212 			 * are not valid in the current mode (in-mode).
2213 			 *
2214 			 * in6_msource is transactioned just as for anything
2215 			 * else in SSM -- but note naive use of in6m_graft()
2216 			 * below for allocating new filter entries.
2217 			 *
2218 			 * This is only an issue if someone mixes the
2219 			 * full-state SSM API with the delta-based API,
2220 			 * which is discouraged in the relevant RFCs.
2221 			 */
2222 			lims = im6o_match_source(imo, idx, ssa);
2223 			if (lims != NULL /*&&
2224 			                  *  lims->im6sl_st[1] == MCAST_INCLUDE*/) {
2225 				error = EADDRNOTAVAIL;
2226 				goto out_imo_locked;
2227 			}
2228 		} else {
2229 			/*
2230 			 * MCAST_JOIN_GROUP on an existing exclusive
2231 			 * membership is an error; return EADDRINUSE
2232 			 * to preserve 4.4BSD API idempotence, and
2233 			 * avoid tedious detour to code below.
2234 			 * NOTE: This is bending RFC 3678 a bit.
2235 			 *
2236 			 * On an existing inclusive membership, this is also
2237 			 * an error; if you want to change filter mode,
2238 			 * you must use the userland API setsourcefilter().
2239 			 * XXX We don't reject this for imf in UNDEFINED
2240 			 * state at t1, because allocation of a filter
2241 			 * is atomic with allocation of a membership.
2242 			 */
2243 			error = EINVAL;
2244 			/* See comments above for EADDRINUSE */
2245 			if (imf->im6f_st[1] == MCAST_EXCLUDE) {
2246 				error = EADDRINUSE;
2247 			}
2248 			goto out_imo_locked;
2249 		}
2250 	}
2251 
2252 	/*
2253 	 * Begin state merge transaction at socket layer.
2254 	 */
2255 
2256 	if (is_new) {
2257 		if (imo->im6o_num_memberships == imo->im6o_max_memberships) {
2258 			error = im6o_grow(imo);
2259 			if (error) {
2260 				goto out_imo_locked;
2261 			}
2262 		}
2263 		/*
2264 		 * Allocate the new slot upfront so we can deal with
2265 		 * grafting the new source filter in same code path
2266 		 * as for join-source on existing membership.
2267 		 */
2268 		idx = imo->im6o_num_memberships;
2269 		imo->im6o_membership[idx] = NULL;
2270 		imo->im6o_num_memberships++;
2271 		VERIFY(imo->im6o_mfilters != NULL);
2272 		imf = &imo->im6o_mfilters[idx];
2273 		VERIFY(RB_EMPTY(&imf->im6f_sources));
2274 	}
2275 
2276 	/*
2277 	 * Graft new source into filter list for this inpcb's
2278 	 * membership of the group. The in6_multi may not have
2279 	 * been allocated yet if this is a new membership, however,
2280 	 * the in_mfilter slot will be allocated and must be initialized.
2281 	 *
2282 	 * Note: Grafting of exclusive mode filters doesn't happen
2283 	 * in this path.
2284 	 * XXX: Should check for non-NULL lims (node exists but may
2285 	 * not be in-mode) for interop with full-state API.
2286 	 */
2287 	if (ssa->sin6_family != AF_UNSPEC) {
2288 		/* Membership starts in IN mode */
2289 		if (is_new) {
2290 			MLD_PRINTF(("%s: new join w/source\n", __func__);
2291 			    im6f_init(imf, MCAST_UNDEFINED, MCAST_INCLUDE));
2292 		} else {
2293 			MLD_PRINTF(("%s: %s source\n", __func__, "allow"));
2294 		}
2295 		lims = im6f_graft(imf, MCAST_INCLUDE, ssa);
2296 		if (lims == NULL) {
2297 			MLD_PRINTF(("%s: merge imf state failed\n",
2298 			    __func__));
2299 			error = ENOMEM;
2300 			goto out_im6o_free;
2301 		}
2302 	} else {
2303 		/* No address specified; Membership starts in EX mode */
2304 		if (is_new) {
2305 			MLD_PRINTF(("%s: new join w/o source", __func__));
2306 			im6f_init(imf, MCAST_UNDEFINED, MCAST_EXCLUDE);
2307 		}
2308 	}
2309 
2310 	/*
2311 	 * Begin state merge transaction at MLD layer.
2312 	 */
2313 
2314 	if (is_new) {
2315 		VERIFY(inm == NULL);
2316 		error = in6_mc_join(ifp, &gsa->sin6_addr, imf, &inm, 0);
2317 		VERIFY(inm != NULL || error != 0);
2318 
2319 		if (error) {
2320 			goto out_im6o_free;
2321 		}
2322 		imo->im6o_membership[idx] = inm; /* from in6_mc_join() */
2323 	} else {
2324 		MLD_PRINTF(("%s: merge inm state\n", __func__));
2325 		IN6M_LOCK(inm);
2326 		error = in6m_merge(inm, imf);
2327 		if (error) {
2328 			MLD_PRINTF(("%s: failed to merge inm state\n",
2329 			    __func__));
2330 			IN6M_UNLOCK(inm);
2331 			goto out_im6f_rollback;
2332 		}
2333 		MLD_PRINTF(("%s: doing mld downcall\n", __func__));
2334 		error = mld_change_state(inm, &mtp, 0);
2335 		IN6M_UNLOCK(inm);
2336 		if (error) {
2337 			MLD_PRINTF(("%s: failed mld downcall\n",
2338 			    __func__));
2339 			goto out_im6f_rollback;
2340 		}
2341 	}
2342 
2343 out_im6f_rollback:
2344 	if (error) {
2345 		im6f_rollback(imf);
2346 		if (is_new) {
2347 			im6f_purge(imf);
2348 		} else {
2349 			im6f_reap(imf);
2350 		}
2351 	} else {
2352 		im6f_commit(imf);
2353 	}
2354 
2355 out_im6o_free:
2356 	if (error && is_new) {
2357 		VERIFY(inm == NULL);
2358 		imo->im6o_membership[idx] = NULL;
2359 		--imo->im6o_num_memberships;
2360 	}
2361 
2362 out_imo_locked:
2363 	IM6O_UNLOCK(imo);
2364 	IM6O_REMREF(imo);       /* from in6p_findmoptions() */
2365 
2366 	/* schedule timer now that we've dropped the lock(s) */
2367 	mld_set_fast_timeout(&mtp);
2368 
2369 	return error;
2370 }
2371 
2372 /*
2373  * Leave an IPv6 multicast group on an inpcb, possibly with a source.
2374  */
2375 static int
in6p_leave_group(struct inpcb * inp,struct sockopt * sopt)2376 in6p_leave_group(struct inpcb *inp, struct sockopt *sopt)
2377 {
2378 	struct ipv6_mreq                 mreq;
2379 	struct group_source_req          gsr;
2380 	struct sockaddr_in6             *gsa, *ssa;
2381 	struct ifnet                    *ifp;
2382 	struct in6_mfilter              *imf;
2383 	struct ip6_moptions             *imo;
2384 	struct in6_msource              *ims;
2385 	struct in6_multi                *inm = NULL;
2386 	uint32_t                         ifindex = 0;
2387 	size_t                           idx;
2388 	int                              error, is_final;
2389 	struct mld_tparams               mtp;
2390 
2391 	bzero(&mtp, sizeof(mtp));
2392 	ifp = NULL;
2393 	error = 0;
2394 	is_final = 1;
2395 
2396 	memset(&gsr, 0, sizeof(struct group_source_req));
2397 	gsa = SIN6(&gsr.gsr_group);
2398 	ssa = SIN6(&gsr.gsr_source);
2399 
2400 	/*
2401 	 * Chew everything passed in up into a struct group_source_req
2402 	 * as that is easier to process.
2403 	 * Note: Any embedded scope ID in the multicast group passed
2404 	 * in by userland is ignored, the interface index is the recommended
2405 	 * mechanism to specify an interface; see below.
2406 	 */
2407 	switch (sopt->sopt_name) {
2408 	case IPV6_LEAVE_GROUP: {
2409 		error = sooptcopyin(sopt, &mreq, sizeof(struct ipv6_mreq),
2410 		    sizeof(struct ipv6_mreq));
2411 		if (error) {
2412 			return error;
2413 		}
2414 		if (IN6_IS_ADDR_V4MAPPED(&mreq.ipv6mr_multiaddr)) {
2415 			struct ip_mreq v4mreq;
2416 			struct sockopt v4sopt;
2417 
2418 			v4mreq.imr_multiaddr.s_addr =
2419 			    mreq.ipv6mr_multiaddr.s6_addr32[3];
2420 			if (mreq.ipv6mr_interface == 0) {
2421 				v4mreq.imr_interface.s_addr = INADDR_ANY;
2422 			} else {
2423 				error = in6p_lookup_v4addr(&mreq, &v4mreq);
2424 			}
2425 			if (error) {
2426 				return error;
2427 			}
2428 			v4sopt.sopt_dir     = SOPT_SET;
2429 			v4sopt.sopt_level   = sopt->sopt_level;
2430 			v4sopt.sopt_name    = IP_DROP_MEMBERSHIP;
2431 			v4sopt.sopt_val     = CAST_USER_ADDR_T(&v4mreq);
2432 			v4sopt.sopt_valsize = sizeof(v4mreq);
2433 			v4sopt.sopt_p       = kernproc;
2434 
2435 			return inp_leave_group(inp, &v4sopt);
2436 		}
2437 		gsa->sin6_family = AF_INET6;
2438 		gsa->sin6_len = sizeof(struct sockaddr_in6);
2439 		gsa->sin6_addr = mreq.ipv6mr_multiaddr;
2440 		gsa->sin6_port = 0;
2441 		if (!in6_embedded_scope) {
2442 			gsa->sin6_scope_id = 0;
2443 		}
2444 		ifindex = mreq.ipv6mr_interface;
2445 		/* Only allow IPv6 multicast addresses */
2446 		if (IN6_IS_ADDR_MULTICAST(&gsa->sin6_addr) == 0) {
2447 			return EINVAL;
2448 		}
2449 		break;
2450 	}
2451 
2452 	case MCAST_LEAVE_GROUP:
2453 	case MCAST_LEAVE_SOURCE_GROUP:
2454 		if (sopt->sopt_name == MCAST_LEAVE_GROUP) {
2455 			error = sooptcopyin(sopt, &gsr,
2456 			    sizeof(struct group_req),
2457 			    sizeof(struct group_req));
2458 		} else if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2459 			error = sooptcopyin(sopt, &gsr,
2460 			    sizeof(struct group_source_req),
2461 			    sizeof(struct group_source_req));
2462 		}
2463 		if (error) {
2464 			return error;
2465 		}
2466 
2467 		if (gsa->sin6_family != AF_INET6 ||
2468 		    gsa->sin6_len != sizeof(struct sockaddr_in6)) {
2469 			return EINVAL;
2470 		}
2471 		if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2472 			if (ssa->sin6_family != AF_INET6 ||
2473 			    ssa->sin6_len != sizeof(struct sockaddr_in6)) {
2474 				return EINVAL;
2475 			}
2476 			if (IN6_IS_ADDR_MULTICAST(&ssa->sin6_addr)) {
2477 				return EINVAL;
2478 			}
2479 			/*
2480 			 * TODO: Validate embedded scope ID in source
2481 			 * list entry against passed-in ifp, if and only
2482 			 * if source list filter entry is iface or node local.
2483 			 */
2484 			in6_clearscope(&ssa->sin6_addr);
2485 		}
2486 		gsa->sin6_port = 0;
2487 		if (in6_embedded_scope) {
2488 			gsa->sin6_scope_id = 0;
2489 		}
2490 		ifindex = gsr.gsr_interface;
2491 		break;
2492 
2493 	default:
2494 		MLD_PRINTF(("%s: unknown sopt_name %d\n",
2495 		    __func__, sopt->sopt_name));
2496 		return EOPNOTSUPP;
2497 	}
2498 
2499 	if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6_addr)) {
2500 		return EINVAL;
2501 	}
2502 
2503 	/*
2504 	 * Validate interface index if provided. If no interface index
2505 	 * was provided separately, attempt to look the membership up
2506 	 * from the default scope as a last resort to disambiguate
2507 	 * the membership we are being asked to leave.
2508 	 * XXX SCOPE6 lock potentially taken here.
2509 	 */
2510 	if (ifindex != 0) {
2511 		ifnet_head_lock_shared();
2512 		if (!IF_INDEX_IN_RANGE(ifindex)) {
2513 			ifnet_head_done();
2514 			return EADDRNOTAVAIL;
2515 		}
2516 		ifp = ifindex2ifnet[ifindex];
2517 		ifnet_head_done();
2518 		if (ifp == NULL) {
2519 			return EADDRNOTAVAIL;
2520 		}
2521 		(void) in6_setscope(&gsa->sin6_addr, ifp, NULL);
2522 		if (!in6_embedded_scope) {
2523 			gsa->sin6_scope_id = ifindex;
2524 		}
2525 	} else {
2526 		error = sa6_embedscope(gsa, ip6_use_defzone, IN6_NULL_IF_EMBEDDED_SCOPE(&ifindex));
2527 		if (error) {
2528 			return EADDRNOTAVAIL;
2529 		}
2530 		/*
2531 		 * Some badly behaved applications don't pass an ifindex
2532 		 * or a scope ID, which is an API violation. In this case,
2533 		 * perform a lookup as per a v6 join.
2534 		 *
2535 		 * XXX For now, stomp on zone ID for the corner case.
2536 		 * This is not the 'KAME way', but we need to see the ifp
2537 		 * directly until such time as this implementation is
2538 		 * refactored, assuming the scope IDs are the way to go.
2539 		 */
2540 
2541 		if (in6_embedded_scope) {
2542 			ifindex = ntohs(gsa->sin6_addr.s6_addr16[1]);
2543 		}
2544 
2545 		if (ifindex == 0) {
2546 			MLD_PRINTF(("%s: warning: no ifindex, looking up "
2547 			    "ifp for group %s.\n", __func__,
2548 			    ip6_sprintf(&gsa->sin6_addr)));
2549 			ifp = in6p_lookup_mcast_ifp(inp, gsa);
2550 		} else {
2551 			if (!IF_INDEX_IN_RANGE(ifindex)) {
2552 				return EADDRNOTAVAIL;
2553 			}
2554 			ifnet_head_lock_shared();
2555 			ifp = ifindex2ifnet[ifindex];
2556 			ifnet_head_done();
2557 		}
2558 		if (ifp == NULL) {
2559 			return EADDRNOTAVAIL;
2560 		}
2561 	}
2562 
2563 	VERIFY(ifp != NULL);
2564 	MLD_PRINTF(("%s: ifp = 0x%llx\n", __func__,
2565 	    (uint64_t)VM_KERNEL_ADDRPERM(ifp)));
2566 
2567 	/*
2568 	 * Find the membership in the membership array.
2569 	 */
2570 	imo = in6p_findmoptions(inp);
2571 	if (imo == NULL) {
2572 		return ENOMEM;
2573 	}
2574 
2575 	IM6O_LOCK(imo);
2576 	idx = im6o_match_group(imo, ifp, gsa);
2577 	if (idx == (size_t)-1) {
2578 		error = EADDRNOTAVAIL;
2579 		goto out_locked;
2580 	}
2581 	inm = imo->im6o_membership[idx];
2582 	imf = &imo->im6o_mfilters[idx];
2583 
2584 	if (ssa->sin6_family != AF_UNSPEC) {
2585 		is_final = 0;
2586 	}
2587 
2588 	/*
2589 	 * Begin state merge transaction at socket layer.
2590 	 */
2591 
2592 	/*
2593 	 * If we were instructed only to leave a given source, do so.
2594 	 * MCAST_LEAVE_SOURCE_GROUP is only valid for inclusive memberships.
2595 	 */
2596 	if (is_final) {
2597 		im6f_leave(imf);
2598 	} else {
2599 		if (imf->im6f_st[0] == MCAST_EXCLUDE) {
2600 			error = EADDRNOTAVAIL;
2601 			goto out_locked;
2602 		}
2603 		ims = im6o_match_source(imo, idx, ssa);
2604 		if (ims == NULL) {
2605 			MLD_PRINTF(("%s: source %s %spresent\n", __func__,
2606 			    ip6_sprintf(&ssa->sin6_addr),
2607 			    "not "));
2608 			error = EADDRNOTAVAIL;
2609 			goto out_locked;
2610 		}
2611 		MLD_PRINTF(("%s: %s source\n", __func__, "block"));
2612 		error = im6f_prune(imf, ssa);
2613 		if (error) {
2614 			MLD_PRINTF(("%s: merge imf state failed\n",
2615 			    __func__));
2616 			goto out_locked;
2617 		}
2618 	}
2619 
2620 	/*
2621 	 * Begin state merge transaction at MLD layer.
2622 	 */
2623 
2624 	if (is_final) {
2625 		/*
2626 		 * Give up the multicast address record to which
2627 		 * the membership points.  Reference held in im6o
2628 		 * will be released below.
2629 		 */
2630 		(void) in6_mc_leave(inm, imf);
2631 	} else {
2632 		MLD_PRINTF(("%s: merge inm state\n", __func__));
2633 		IN6M_LOCK(inm);
2634 		error = in6m_merge(inm, imf);
2635 		if (error) {
2636 			MLD_PRINTF(("%s: failed to merge inm state\n",
2637 			    __func__));
2638 			IN6M_UNLOCK(inm);
2639 			goto out_im6f_rollback;
2640 		}
2641 
2642 		MLD_PRINTF(("%s: doing mld downcall\n", __func__));
2643 		error = mld_change_state(inm, &mtp, 0);
2644 		if (error) {
2645 			MLD_PRINTF(("%s: failed mld downcall\n", __func__));
2646 		}
2647 		IN6M_UNLOCK(inm);
2648 	}
2649 
2650 out_im6f_rollback:
2651 	if (error) {
2652 		im6f_rollback(imf);
2653 	} else {
2654 		im6f_commit(imf);
2655 	}
2656 
2657 	im6f_reap(imf);
2658 
2659 	if (is_final) {
2660 		/* Remove the gap in the membership array. */
2661 		VERIFY(inm == imo->im6o_membership[idx]);
2662 		IN6M_REMREF(inm);
2663 
2664 		for (++idx; idx < imo->im6o_num_memberships; ++idx) {
2665 			imo->im6o_membership[idx - 1] = imo->im6o_membership[idx];
2666 			imo->im6o_mfilters[idx - 1] = imo->im6o_mfilters[idx];
2667 		}
2668 		imo->im6o_num_memberships--;
2669 
2670 		/* Re-initialize the now unused tail of the list */
2671 		imo->im6o_membership[imo->im6o_num_memberships] = NULL;
2672 		im6f_init(&imo->im6o_mfilters[imo->im6o_num_memberships], MCAST_UNDEFINED, MCAST_EXCLUDE);
2673 	}
2674 
2675 out_locked:
2676 	IM6O_UNLOCK(imo);
2677 	IM6O_REMREF(imo);       /* from in6p_findmoptions() */
2678 
2679 	/* schedule timer now that we've dropped the lock(s) */
2680 	mld_set_fast_timeout(&mtp);
2681 
2682 	return error;
2683 }
2684 
2685 /*
2686  * Select the interface for transmitting IPv6 multicast datagrams.
2687  *
2688  * Either an instance of struct in6_addr or an instance of struct ipv6_mreqn
2689  * may be passed to this socket option. An address of in6addr_any or an
2690  * interface index of 0 is used to remove a previous selection.
2691  * When no interface is selected, one is chosen for every send.
2692  */
2693 static int
in6p_set_multicast_if(struct inpcb * inp,struct sockopt * sopt)2694 in6p_set_multicast_if(struct inpcb *inp, struct sockopt *sopt)
2695 {
2696 	struct ifnet            *ifp;
2697 	struct ip6_moptions     *imo;
2698 	u_int                    ifindex;
2699 	int                      error;
2700 
2701 	if (sopt->sopt_valsize != sizeof(u_int)) {
2702 		return EINVAL;
2703 	}
2704 
2705 	error = sooptcopyin(sopt, &ifindex, sizeof(u_int), sizeof(u_int));
2706 	if (error) {
2707 		return error;
2708 	}
2709 
2710 	ifnet_head_lock_shared();
2711 	if (!IF_INDEX_IN_RANGE(ifindex)) {
2712 		ifnet_head_done();
2713 		return EINVAL;
2714 	}
2715 
2716 	ifp = ifindex2ifnet[ifindex];
2717 	ifnet_head_done();
2718 	if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
2719 		return EADDRNOTAVAIL;
2720 	}
2721 
2722 	imo = in6p_findmoptions(inp);
2723 	if (imo == NULL) {
2724 		return ENOMEM;
2725 	}
2726 
2727 	IM6O_LOCK(imo);
2728 	imo->im6o_multicast_ifp = ifp;
2729 	IM6O_UNLOCK(imo);
2730 	IM6O_REMREF(imo);       /* from in6p_findmoptions() */
2731 
2732 	return 0;
2733 }
2734 
2735 /*
2736  * Atomically set source filters on a socket for an IPv6 multicast group.
2737  *
2738  */
2739 static int
in6p_set_source_filters(struct inpcb * inp,struct sockopt * sopt)2740 in6p_set_source_filters(struct inpcb *inp, struct sockopt *sopt)
2741 {
2742 	struct __msfilterreq64   msfr = {}, msfr64;
2743 	struct __msfilterreq32   msfr32;
2744 	struct sockaddr_in6     *gsa;
2745 	struct ifnet            *ifp;
2746 	struct in6_mfilter      *imf;
2747 	struct ip6_moptions     *imo;
2748 	struct in6_multi        *inm;
2749 	size_t                   idx;
2750 	int                      error;
2751 	user_addr_t              tmp_ptr;
2752 	struct mld_tparams       mtp;
2753 
2754 	const bool is_currproc_64bit_proc = IS_64BIT_PROCESS(current_proc());
2755 
2756 	bzero(&mtp, sizeof(mtp));
2757 
2758 	if (is_currproc_64bit_proc) {
2759 		error = sooptcopyin(sopt, &msfr64,
2760 		    sizeof(struct __msfilterreq64),
2761 		    sizeof(struct __msfilterreq64));
2762 		if (error) {
2763 			return error;
2764 		}
2765 		/* we never use msfr.msfr_srcs; */
2766 		memcpy(&msfr, &msfr64, sizeof(msfr64));
2767 	} else {
2768 		error = sooptcopyin(sopt, &msfr32,
2769 		    sizeof(struct __msfilterreq32),
2770 		    sizeof(struct __msfilterreq32));
2771 		if (error) {
2772 			return error;
2773 		}
2774 		/* we never use msfr.msfr_srcs; */
2775 		memcpy(&msfr, &msfr32, sizeof(msfr32));
2776 	}
2777 
2778 	if ((size_t) msfr.msfr_nsrcs >
2779 	    UINT32_MAX / sizeof(struct sockaddr_storage)) {
2780 		msfr.msfr_nsrcs = UINT32_MAX / sizeof(struct sockaddr_storage);
2781 	}
2782 
2783 	if (msfr.msfr_nsrcs > in6_mcast_maxsocksrc) {
2784 		return ENOBUFS;
2785 	}
2786 
2787 	if (msfr.msfr_fmode != MCAST_EXCLUDE &&
2788 	    msfr.msfr_fmode != MCAST_INCLUDE) {
2789 		return EINVAL;
2790 	}
2791 
2792 	if (msfr.msfr_group.ss_family != AF_INET6 ||
2793 	    msfr.msfr_group.ss_len != sizeof(struct sockaddr_in6)) {
2794 		return EINVAL;
2795 	}
2796 
2797 	gsa = SIN6(&msfr.msfr_group);
2798 	if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6_addr)) {
2799 		return EINVAL;
2800 	}
2801 
2802 	gsa->sin6_port = 0;     /* ignore port */
2803 
2804 	ifnet_head_lock_shared();
2805 	if (msfr.msfr_ifindex == 0 || !IF_INDEX_IN_RANGE(msfr.msfr_ifindex)) {
2806 		ifnet_head_done();
2807 		return EADDRNOTAVAIL;
2808 	}
2809 	ifp = ifindex2ifnet[msfr.msfr_ifindex];
2810 	ifnet_head_done();
2811 	if (ifp == NULL) {
2812 		return EADDRNOTAVAIL;
2813 	}
2814 
2815 	(void)in6_setscope(&gsa->sin6_addr, ifp, IN6_NULL_IF_EMBEDDED_SCOPE(&gsa->sin6_scope_id));
2816 
2817 	/*
2818 	 * Take the INP write lock.
2819 	 * Check if this socket is a member of this group.
2820 	 */
2821 	imo = in6p_findmoptions(inp);
2822 	if (imo == NULL) {
2823 		return ENOMEM;
2824 	}
2825 
2826 	IM6O_LOCK(imo);
2827 	idx = im6o_match_group(imo, ifp, gsa);
2828 	if (idx == (size_t)-1 || imo->im6o_mfilters == NULL) {
2829 		error = EADDRNOTAVAIL;
2830 		goto out_imo_locked;
2831 	}
2832 	inm = imo->im6o_membership[idx];
2833 	imf = &imo->im6o_mfilters[idx];
2834 
2835 	/*
2836 	 * Begin state merge transaction at socket layer.
2837 	 */
2838 
2839 	imf->im6f_st[1] = (uint8_t)msfr.msfr_fmode;
2840 
2841 	/*
2842 	 * Apply any new source filters, if present.
2843 	 * Make a copy of the user-space source vector so
2844 	 * that we may copy them with a single copyin. This
2845 	 * allows us to deal with page faults up-front.
2846 	 */
2847 	if (msfr.msfr_nsrcs > 0) {
2848 		struct in6_msource      *__single lims;
2849 		struct sockaddr_in6     *psin;
2850 		struct sockaddr_storage *kss, *pkss;
2851 		unsigned int             i;
2852 
2853 		if (is_currproc_64bit_proc) {
2854 			tmp_ptr = (user_addr_t)msfr64.msfr_srcs;
2855 		} else {
2856 			tmp_ptr = CAST_USER_ADDR_T(msfr32.msfr_srcs);
2857 		}
2858 
2859 		MLD_PRINTF(("%s: loading %lu source list entries\n",
2860 		    __func__, (unsigned long)msfr.msfr_nsrcs));
2861 		kss = kalloc_data((size_t) msfr.msfr_nsrcs * sizeof(*kss), Z_WAITOK);
2862 		if (kss == NULL) {
2863 			error = ENOMEM;
2864 			goto out_imo_locked;
2865 		}
2866 
2867 		error = copyin(tmp_ptr, kss,
2868 		    (size_t) msfr.msfr_nsrcs * sizeof(*kss));
2869 		if (error) {
2870 			kfree_data(kss, (size_t) msfr.msfr_nsrcs * sizeof(*kss));
2871 			goto out_imo_locked;
2872 		}
2873 
2874 		/*
2875 		 * Mark all source filters as UNDEFINED at t1.
2876 		 * Restore new group filter mode, as im6f_leave()
2877 		 * will set it to INCLUDE.
2878 		 */
2879 		im6f_leave(imf);
2880 		imf->im6f_st[1] = (uint8_t)msfr.msfr_fmode;
2881 
2882 		/*
2883 		 * Update socket layer filters at t1, lazy-allocating
2884 		 * new entries. This saves a bunch of memory at the
2885 		 * cost of one RB_FIND() per source entry; duplicate
2886 		 * entries in the msfr_nsrcs vector are ignored.
2887 		 * If we encounter an error, rollback transaction.
2888 		 *
2889 		 * XXX This too could be replaced with a set-symmetric
2890 		 * difference like loop to avoid walking from root
2891 		 * every time, as the key space is common.
2892 		 */
2893 		for (i = 0, pkss = kss; i < msfr.msfr_nsrcs; i++, pkss++) {
2894 			psin = SIN6(pkss);
2895 			if (psin->sin6_family != AF_INET6) {
2896 				error = EAFNOSUPPORT;
2897 				break;
2898 			}
2899 			if (psin->sin6_len != sizeof(struct sockaddr_in6)) {
2900 				error = EINVAL;
2901 				break;
2902 			}
2903 			if (IN6_IS_ADDR_MULTICAST(&psin->sin6_addr)) {
2904 				error = EINVAL;
2905 				break;
2906 			}
2907 			/*
2908 			 * TODO: Validate embedded scope ID in source
2909 			 * list entry against passed-in ifp, if and only
2910 			 * if source list filter entry is iface or node local.
2911 			 */
2912 			in6_clearscope(&psin->sin6_addr);
2913 			error = im6f_get_source(imf, psin, &lims);
2914 			if (error) {
2915 				break;
2916 			}
2917 			lims->im6sl_st[1] = imf->im6f_st[1];
2918 		}
2919 		kfree_data(kss, (size_t) msfr.msfr_nsrcs * sizeof(*kss));
2920 	}
2921 
2922 	if (error) {
2923 		goto out_im6f_rollback;
2924 	}
2925 
2926 	/*
2927 	 * Begin state merge transaction at MLD layer.
2928 	 */
2929 	IN6M_LOCK(inm);
2930 	MLD_PRINTF(("%s: merge inm state\n", __func__));
2931 	error = in6m_merge(inm, imf);
2932 	if (error) {
2933 		MLD_PRINTF(("%s: failed to merge inm state\n", __func__));
2934 		IN6M_UNLOCK(inm);
2935 		goto out_im6f_rollback;
2936 	}
2937 
2938 	MLD_PRINTF(("%s: doing mld downcall\n", __func__));
2939 	error = mld_change_state(inm, &mtp, 0);
2940 	IN6M_UNLOCK(inm);
2941 #if MLD_DEBUG
2942 	if (error) {
2943 		MLD_PRINTF(("%s: failed mld downcall\n", __func__));
2944 	}
2945 #endif
2946 
2947 out_im6f_rollback:
2948 	if (error) {
2949 		im6f_rollback(imf);
2950 	} else {
2951 		im6f_commit(imf);
2952 	}
2953 
2954 	im6f_reap(imf);
2955 
2956 out_imo_locked:
2957 	IM6O_UNLOCK(imo);
2958 	IM6O_REMREF(imo);       /* from in6p_findmoptions() */
2959 
2960 	/* schedule timer now that we've dropped the lock(s) */
2961 	mld_set_fast_timeout(&mtp);
2962 
2963 	return error;
2964 }
2965 
2966 /*
2967  * Set the IP multicast options in response to user setsockopt().
2968  *
2969  * Many of the socket options handled in this function duplicate the
2970  * functionality of socket options in the regular unicast API. However,
2971  * it is not possible to merge the duplicate code, because the idempotence
2972  * of the IPv6 multicast part of the BSD Sockets API must be preserved;
2973  * the effects of these options must be treated as separate and distinct.
2974  *
2975  */
2976 int
ip6_setmoptions(struct inpcb * inp,struct sockopt * sopt)2977 ip6_setmoptions(struct inpcb *inp, struct sockopt *sopt)
2978 {
2979 	struct ip6_moptions     *im6o;
2980 	int                      error;
2981 
2982 	error = 0;
2983 
2984 	/*
2985 	 * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
2986 	 * or is a divert socket, reject it.
2987 	 */
2988 	if (SOCK_PROTO(inp->inp_socket) == IPPROTO_DIVERT ||
2989 	    (SOCK_TYPE(inp->inp_socket) != SOCK_RAW &&
2990 	    SOCK_TYPE(inp->inp_socket) != SOCK_DGRAM)) {
2991 		return EOPNOTSUPP;
2992 	}
2993 
2994 	switch (sopt->sopt_name) {
2995 	case IPV6_MULTICAST_IF:
2996 		error = in6p_set_multicast_if(inp, sopt);
2997 		break;
2998 
2999 	case IPV6_MULTICAST_HOPS: {
3000 		int hlim;
3001 
3002 		if (sopt->sopt_valsize != sizeof(int)) {
3003 			error = EINVAL;
3004 			break;
3005 		}
3006 		error = sooptcopyin(sopt, &hlim, sizeof(hlim), sizeof(int));
3007 		if (error) {
3008 			break;
3009 		}
3010 		if (hlim < -1 || hlim > IPV6_MAXHLIM) {
3011 			error = EINVAL;
3012 			break;
3013 		} else if (hlim == -1) {
3014 			hlim = ip6_defmcasthlim;
3015 		}
3016 		im6o = in6p_findmoptions(inp);
3017 		if (im6o == NULL) {
3018 			error = ENOMEM;
3019 			break;
3020 		}
3021 		IM6O_LOCK(im6o);
3022 		im6o->im6o_multicast_hlim = (u_char)hlim;
3023 		IM6O_UNLOCK(im6o);
3024 		IM6O_REMREF(im6o);      /* from in6p_findmoptions() */
3025 		break;
3026 	}
3027 
3028 	case IPV6_MULTICAST_LOOP: {
3029 		u_int loop;
3030 
3031 		/*
3032 		 * Set the loopback flag for outgoing multicast packets.
3033 		 * Must be zero or one.
3034 		 */
3035 		if (sopt->sopt_valsize != sizeof(u_int)) {
3036 			error = EINVAL;
3037 			break;
3038 		}
3039 		error = sooptcopyin(sopt, &loop, sizeof(u_int), sizeof(u_int));
3040 		if (error) {
3041 			break;
3042 		}
3043 		if (loop > 1) {
3044 			error = EINVAL;
3045 			break;
3046 		}
3047 		im6o = in6p_findmoptions(inp);
3048 		if (im6o == NULL) {
3049 			error = ENOMEM;
3050 			break;
3051 		}
3052 		IM6O_LOCK(im6o);
3053 		im6o->im6o_multicast_loop = (u_char)loop;
3054 		IM6O_UNLOCK(im6o);
3055 		IM6O_REMREF(im6o);      /* from in6p_findmoptions() */
3056 		break;
3057 	}
3058 
3059 	case IPV6_JOIN_GROUP:
3060 	case MCAST_JOIN_GROUP:
3061 	case MCAST_JOIN_SOURCE_GROUP:
3062 		error = in6p_join_group(inp, sopt);
3063 		break;
3064 
3065 	case IPV6_LEAVE_GROUP:
3066 	case MCAST_LEAVE_GROUP:
3067 	case MCAST_LEAVE_SOURCE_GROUP:
3068 		error = in6p_leave_group(inp, sopt);
3069 		break;
3070 
3071 	case MCAST_BLOCK_SOURCE:
3072 	case MCAST_UNBLOCK_SOURCE:
3073 		error = in6p_block_unblock_source(inp, sopt);
3074 		break;
3075 
3076 	case IPV6_MSFILTER:
3077 		error = in6p_set_source_filters(inp, sopt);
3078 		break;
3079 
3080 	default:
3081 		error = EOPNOTSUPP;
3082 		break;
3083 	}
3084 
3085 	return error;
3086 }
3087 /*
3088  * Expose MLD's multicast filter mode and source list(s) to userland,
3089  * keyed by (ifindex, group).
3090  * The filter mode is written out as a uint32_t, followed by
3091  * 0..n of struct in6_addr.
3092  * For use by ifmcstat(8).
3093  */
3094 static int
3095 sysctl_ip6_mcast_filters SYSCTL_HANDLER_ARGS
3096 {
3097 #pragma unused(oidp)
3098 	/* int: ifindex + 4 * 32 bits of IPv6 address */
3099 	DECLARE_SYSCTL_HANDLER_ARG_ARRAY(int, 5, name, namelen);
3100 
3101 	struct in6_addr                  mcaddr;
3102 	struct in6_addr                  src;
3103 	struct ifnet                    *ifp;
3104 	struct in6_multi                *inm;
3105 	struct in6_multistep            step;
3106 	struct ip6_msource              *ims;
3107 	int                              retval = 0;
3108 	uint32_t                         fmode, ifindex;
3109 
3110 	if (req->newptr != USER_ADDR_NULL) {
3111 		return EPERM;
3112 	}
3113 
3114 	ifindex = name[0];
3115 	ifnet_head_lock_shared();
3116 	if (!IF_INDEX_IN_RANGE(ifindex)) {
3117 		MLD_PRINTF(("%s: ifindex %u out of range\n",
3118 		    __func__, ifindex));
3119 		ifnet_head_done();
3120 		return ENOENT;
3121 	}
3122 
3123 	memcpy(&mcaddr, &name[1], sizeof(struct in6_addr));
3124 	if (!IN6_IS_ADDR_MULTICAST(&mcaddr)) {
3125 		MLD_PRINTF(("%s: group %s is not multicast\n",
3126 		    __func__, ip6_sprintf(&mcaddr)));
3127 		ifnet_head_done();
3128 		return EINVAL;
3129 	}
3130 
3131 	ifp = ifindex2ifnet[ifindex];
3132 	ifnet_head_done();
3133 	if (ifp == NULL) {
3134 		MLD_PRINTF(("%s: no ifp for ifindex %u\n", __func__, ifindex));
3135 		return ENOENT;
3136 	}
3137 	/*
3138 	 * Internal MLD lookups require that scope/zone ID is set.
3139 	 */
3140 	uint32_t ifscope = IFSCOPE_NONE;
3141 	(void)in6_setscope(&mcaddr, ifp, &ifscope);
3142 
3143 	in6_multihead_lock_shared();
3144 	IN6_FIRST_MULTI(step, inm);
3145 	while (inm != NULL) {
3146 		IN6M_LOCK(inm);
3147 		if (inm->in6m_ifp != ifp) {
3148 			goto next;
3149 		}
3150 
3151 		if (!in6_are_addr_equal_scoped(&inm->in6m_addr, &mcaddr, inm->ifscope, ifscope)) {
3152 			goto next;
3153 		}
3154 
3155 		fmode = inm->in6m_st[1].iss_fmode;
3156 		retval = SYSCTL_OUT(req, &fmode, sizeof(uint32_t));
3157 		if (retval != 0) {
3158 			IN6M_UNLOCK(inm);
3159 			break;          /* abort */
3160 		}
3161 		RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
3162 			MLD_PRINTF(("%s: visit node 0x%llx\n", __func__,
3163 			    (uint64_t)VM_KERNEL_ADDRPERM(ims)));
3164 			/*
3165 			 * Only copy-out sources which are in-mode.
3166 			 */
3167 			if (fmode != im6s_get_mode(inm, ims, 1)) {
3168 				MLD_PRINTF(("%s: skip non-in-mode\n",
3169 				    __func__));
3170 				continue; /* process next source */
3171 			}
3172 			src = ims->im6s_addr;
3173 			retval = SYSCTL_OUT(req, &src, sizeof(struct in6_addr));
3174 			if (retval != 0) {
3175 				break;  /* process next inm */
3176 			}
3177 		}
3178 next:
3179 		IN6M_UNLOCK(inm);
3180 		IN6_NEXT_MULTI(step, inm);
3181 	}
3182 	in6_multihead_lock_done();
3183 
3184 	return retval;
3185 }
3186 
3187 static struct in6_multi *
in6_multi_alloc(zalloc_flags_t how)3188 in6_multi_alloc(zalloc_flags_t how)
3189 {
3190 	struct in6_multi *__single in6m;
3191 
3192 	if (in6m_debug == 0) {
3193 		in6m = kalloc_type(struct in6_multi, how | Z_ZERO);
3194 	} else {
3195 		struct in6_multi_dbg *__single in6m_dbg;
3196 		in6m_dbg = kalloc_type(struct in6_multi_dbg, how | Z_ZERO);
3197 		in6m = (struct in6_multi *__single)in6m_dbg;
3198 	}
3199 	if (in6m != NULL) {
3200 		lck_mtx_init(&in6m->in6m_lock, &in6_multihead_lock_grp,
3201 		    &in6_multihead_lock_attr);
3202 		in6m->in6m_debug |= IFD_ALLOC;
3203 		if (in6m_debug != 0) {
3204 			in6m->in6m_debug |= IFD_DEBUG;
3205 			in6m->in6m_trace = in6m_trace;
3206 		}
3207 		in6m->ifscope = IFSCOPE_NONE;
3208 	}
3209 	return in6m;
3210 }
3211 
3212 static void
in6_multi_free(struct in6_multi * in6m)3213 in6_multi_free(struct in6_multi *in6m)
3214 {
3215 	IN6M_LOCK(in6m);
3216 	if (in6m->in6m_debug & IFD_ATTACHED) {
3217 		panic("%s: attached in6m=%p is being freed", __func__, in6m);
3218 		/* NOTREACHED */
3219 	} else if (in6m->in6m_ifma != NULL) {
3220 		panic("%s: ifma not NULL for in6m=%p", __func__, in6m);
3221 		/* NOTREACHED */
3222 	} else if (!(in6m->in6m_debug & IFD_ALLOC)) {
3223 		panic("%s: in6m %p cannot be freed", __func__, in6m);
3224 		/* NOTREACHED */
3225 	} else if (in6m->in6m_refcount != 0) {
3226 		panic("%s: non-zero refcount in6m=%p", __func__, in6m);
3227 		/* NOTREACHED */
3228 	} else if (in6m->in6m_reqcnt != 0) {
3229 		panic("%s: non-zero reqcnt in6m=%p", __func__, in6m);
3230 		/* NOTREACHED */
3231 	}
3232 
3233 	/* Free any pending MLDv2 state-change records */
3234 	IF_DRAIN(&in6m->in6m_scq);
3235 
3236 	in6m->in6m_debug &= ~IFD_ALLOC;
3237 	if ((in6m->in6m_debug & (IFD_DEBUG | IFD_TRASHED)) ==
3238 	    (IFD_DEBUG | IFD_TRASHED)) {
3239 		lck_mtx_lock(&in6m_trash_lock);
3240 		TAILQ_REMOVE(&in6m_trash_head, (struct in6_multi_dbg *)in6m,
3241 		    in6m_trash_link);
3242 		lck_mtx_unlock(&in6m_trash_lock);
3243 		in6m->in6m_debug &= ~IFD_TRASHED;
3244 	}
3245 	IN6M_UNLOCK(in6m);
3246 
3247 	lck_mtx_destroy(&in6m->in6m_lock, &in6_multihead_lock_grp);
3248 	if (!in6m_debug) {
3249 		kfree_type(struct in6_multi, in6m);
3250 	} else {
3251 		struct in6_multi_dbg *__single in6m_dbg =
3252 		    (struct in6_multi_dbg *__single)in6m;
3253 		kfree_type(struct in6_multi_dbg, in6m_dbg);
3254 		in6m = NULL;
3255 	}
3256 }
3257 
3258 static void
in6_multi_attach(struct in6_multi * in6m)3259 in6_multi_attach(struct in6_multi *in6m)
3260 {
3261 	in6_multihead_lock_assert(LCK_RW_ASSERT_EXCLUSIVE);
3262 	IN6M_LOCK_ASSERT_HELD(in6m);
3263 
3264 	if (in6m->in6m_debug & IFD_ATTACHED) {
3265 		panic("%s: Attempt to attach an already attached in6m=%p",
3266 		    __func__, in6m);
3267 		/* NOTREACHED */
3268 	}
3269 
3270 	in6m->in6m_reqcnt++;
3271 	VERIFY(in6m->in6m_reqcnt == 1);
3272 	IN6M_ADDREF_LOCKED(in6m);
3273 	in6m->in6m_debug |= IFD_ATTACHED;
3274 	/*
3275 	 * Reattach case:  If debugging is enabled, take it
3276 	 * out of the trash list and clear IFD_TRASHED.
3277 	 */
3278 	if ((in6m->in6m_debug & (IFD_DEBUG | IFD_TRASHED)) ==
3279 	    (IFD_DEBUG | IFD_TRASHED)) {
3280 		/* Become a regular mutex, just in case */
3281 		IN6M_CONVERT_LOCK(in6m);
3282 		lck_mtx_lock(&in6m_trash_lock);
3283 		TAILQ_REMOVE(&in6m_trash_head, (struct in6_multi_dbg *)in6m,
3284 		    in6m_trash_link);
3285 		lck_mtx_unlock(&in6m_trash_lock);
3286 		in6m->in6m_debug &= ~IFD_TRASHED;
3287 	}
3288 
3289 	LIST_INSERT_HEAD(&in6_multihead, in6m, in6m_entry);
3290 }
3291 
3292 int
in6_multi_detach(struct in6_multi * in6m)3293 in6_multi_detach(struct in6_multi *in6m)
3294 {
3295 	in6_multihead_lock_assert(LCK_RW_ASSERT_EXCLUSIVE);
3296 	IN6M_LOCK_ASSERT_HELD(in6m);
3297 
3298 	if (in6m->in6m_reqcnt == 0) {
3299 		panic("%s: in6m=%p negative reqcnt", __func__, in6m);
3300 		/* NOTREACHED */
3301 	}
3302 
3303 	--in6m->in6m_reqcnt;
3304 	if (in6m->in6m_reqcnt > 0) {
3305 		return 0;
3306 	}
3307 
3308 	if (!(in6m->in6m_debug & IFD_ATTACHED)) {
3309 		panic("%s: Attempt to detach an unattached record in6m=%p",
3310 		    __func__, in6m);
3311 		/* NOTREACHED */
3312 	} else if (in6m->in6m_debug & IFD_TRASHED) {
3313 		panic("%s: in6m %p is already in trash list", __func__, in6m);
3314 		/* NOTREACHED */
3315 	}
3316 
3317 	/*
3318 	 * NOTE: Caller calls IFMA_REMREF
3319 	 */
3320 	in6m->in6m_debug &= ~IFD_ATTACHED;
3321 	LIST_REMOVE(in6m, in6m_entry);
3322 
3323 	if (in6m->in6m_debug & IFD_DEBUG) {
3324 		/* Become a regular mutex, just in case */
3325 		IN6M_CONVERT_LOCK(in6m);
3326 		lck_mtx_lock(&in6m_trash_lock);
3327 		TAILQ_INSERT_TAIL(&in6m_trash_head,
3328 		    (struct in6_multi_dbg *)in6m, in6m_trash_link);
3329 		lck_mtx_unlock(&in6m_trash_lock);
3330 		in6m->in6m_debug |= IFD_TRASHED;
3331 	}
3332 
3333 	return 1;
3334 }
3335 
3336 void
in6m_addref(struct in6_multi * in6m,int locked)3337 in6m_addref(struct in6_multi *in6m, int locked)
3338 {
3339 	if (!locked) {
3340 		IN6M_LOCK_SPIN(in6m);
3341 	} else {
3342 		IN6M_LOCK_ASSERT_HELD(in6m);
3343 	}
3344 
3345 	if (++in6m->in6m_refcount == 0) {
3346 		panic("%s: in6m=%p wraparound refcnt", __func__, in6m);
3347 		/* NOTREACHED */
3348 	} else if (in6m->in6m_trace != NULL) {
3349 		(*in6m->in6m_trace)(in6m, TRUE);
3350 	}
3351 	if (!locked) {
3352 		IN6M_UNLOCK(in6m);
3353 	}
3354 }
3355 
3356 void
in6m_remref(struct in6_multi * in6m,int locked)3357 in6m_remref(struct in6_multi *in6m, int locked)
3358 {
3359 	struct ifmultiaddr *ifma;
3360 	struct mld_ifinfo *mli;
3361 
3362 	if (!locked) {
3363 		IN6M_LOCK_SPIN(in6m);
3364 	} else {
3365 		IN6M_LOCK_ASSERT_HELD(in6m);
3366 	}
3367 
3368 	if (in6m->in6m_refcount == 0 || (in6m->in6m_refcount == 1 && locked)) {
3369 		panic("%s: in6m=%p negative refcnt", __func__, in6m);
3370 		/* NOTREACHED */
3371 	} else if (in6m->in6m_trace != NULL) {
3372 		(*in6m->in6m_trace)(in6m, FALSE);
3373 	}
3374 
3375 	--in6m->in6m_refcount;
3376 	if (in6m->in6m_refcount > 0) {
3377 		if (!locked) {
3378 			IN6M_UNLOCK(in6m);
3379 		}
3380 		return;
3381 	}
3382 
3383 	/*
3384 	 * Synchronization with in6_mc_get().  In the event the in6m has been
3385 	 * detached, the underlying ifma would still be in the if_multiaddrs
3386 	 * list, and thus can be looked up via if_addmulti().  At that point,
3387 	 * the only way to find this in6m is via ifma_protospec.  To avoid
3388 	 * race conditions between the last in6m_remref() of that in6m and its
3389 	 * use via ifma_protospec, in6_multihead lock is used for serialization.
3390 	 * In order to avoid violating the lock order, we must drop in6m_lock
3391 	 * before acquiring in6_multihead lock.  To prevent the in6m from being
3392 	 * freed prematurely, we hold an extra reference.
3393 	 */
3394 	++in6m->in6m_refcount;
3395 	IN6M_UNLOCK(in6m);
3396 	in6_multihead_lock_shared();
3397 	IN6M_LOCK_SPIN(in6m);
3398 	--in6m->in6m_refcount;
3399 	if (in6m->in6m_refcount > 0) {
3400 		/* We've lost the race, so abort since in6m is still in use */
3401 		IN6M_UNLOCK(in6m);
3402 		in6_multihead_lock_done();
3403 		/* If it was locked, return it as such */
3404 		if (locked) {
3405 			IN6M_LOCK(in6m);
3406 		}
3407 		return;
3408 	}
3409 	in6m_purge(in6m);
3410 	ifma = in6m->in6m_ifma;
3411 	in6m->in6m_ifma = NULL;
3412 	in6m->in6m_ifp = NULL;
3413 	mli = in6m->in6m_mli;
3414 	in6m->in6m_mli = NULL;
3415 	IN6M_UNLOCK(in6m);
3416 	IFMA_LOCK_SPIN(ifma);
3417 	ifma->ifma_protospec = NULL;
3418 	IFMA_UNLOCK(ifma);
3419 	in6_multihead_lock_done();
3420 
3421 	in6_multi_free(in6m);
3422 	if_delmulti_ifma(ifma);
3423 	/* Release reference held to the underlying ifmultiaddr */
3424 	IFMA_REMREF(ifma);
3425 
3426 	if (mli != NULL) {
3427 		MLI_REMREF(mli);
3428 	}
3429 }
3430 
3431 static void
in6m_trace(struct in6_multi * in6m,int refhold)3432 in6m_trace(struct in6_multi *in6m, int refhold)
3433 {
3434 	struct in6_multi_dbg *__single in6m_dbg =
3435 	    (struct in6_multi_dbg *__single)in6m;
3436 	ctrace_t *tr;
3437 	u_int32_t idx;
3438 	u_int16_t *cnt;
3439 
3440 	if (!(in6m->in6m_debug & IFD_DEBUG)) {
3441 		panic("%s: in6m %p has no debug structure", __func__, in6m);
3442 		/* NOTREACHED */
3443 	}
3444 	if (refhold) {
3445 		cnt = &in6m_dbg->in6m_refhold_cnt;
3446 		tr = in6m_dbg->in6m_refhold;
3447 	} else {
3448 		cnt = &in6m_dbg->in6m_refrele_cnt;
3449 		tr = in6m_dbg->in6m_refrele;
3450 	}
3451 
3452 	idx = os_atomic_inc_orig(cnt, relaxed) % IN6M_TRACE_HIST_SIZE;
3453 	ctrace_record(&tr[idx]);
3454 }
3455 
3456 static struct in6_multi_mship *
in6_multi_mship_alloc(zalloc_flags_t how)3457 in6_multi_mship_alloc(zalloc_flags_t how)
3458 {
3459 	return zalloc_flags(imm_zone, how | Z_ZERO);
3460 }
3461 
3462 static void
in6_multi_mship_free(struct in6_multi_mship * imm)3463 in6_multi_mship_free(struct in6_multi_mship *imm)
3464 {
3465 	if (imm->i6mm_maddr != NULL) {
3466 		panic("%s: i6mm_maddr not NULL for imm=%p", __func__, imm);
3467 		/* NOTREACHED */
3468 	}
3469 	zfree(imm_zone, imm);
3470 }
3471 
3472 void
in6_multihead_lock_exclusive(void)3473 in6_multihead_lock_exclusive(void)
3474 {
3475 	lck_rw_lock_exclusive(&in6_multihead_lock);
3476 }
3477 
3478 void
in6_multihead_lock_shared(void)3479 in6_multihead_lock_shared(void)
3480 {
3481 	lck_rw_lock_shared(&in6_multihead_lock);
3482 }
3483 
3484 void
in6_multihead_lock_assert(int what)3485 in6_multihead_lock_assert(int what)
3486 {
3487 #if !MACH_ASSERT
3488 #pragma unused(what)
3489 #endif
3490 	LCK_RW_ASSERT(&in6_multihead_lock, what);
3491 }
3492 
3493 void
in6_multihead_lock_done(void)3494 in6_multihead_lock_done(void)
3495 {
3496 	lck_rw_done(&in6_multihead_lock);
3497 }
3498 
3499 static struct ip6_msource *
ip6ms_alloc(zalloc_flags_t how)3500 ip6ms_alloc(zalloc_flags_t how)
3501 {
3502 	return zalloc_flags(ip6ms_zone, how | Z_ZERO);
3503 }
3504 
3505 static void
ip6ms_free(struct ip6_msource * i6ms)3506 ip6ms_free(struct ip6_msource *i6ms)
3507 {
3508 	zfree(ip6ms_zone, i6ms);
3509 }
3510 
3511 static struct in6_msource *
in6ms_alloc(zalloc_flags_t how)3512 in6ms_alloc(zalloc_flags_t how)
3513 {
3514 	return zalloc_flags(in6ms_zone, how | Z_ZERO);
3515 }
3516 
3517 static void
in6ms_free(struct in6_msource * in6ms)3518 in6ms_free(struct in6_msource *in6ms)
3519 {
3520 	zfree(in6ms_zone, in6ms);
3521 }
3522 
3523 #ifdef MLD_DEBUG
3524 
3525 static const char *in6m_modestrs[] = { "un", "in", "ex" };
3526 
3527 static const char *
in6m_mode_str(const int mode)3528 in6m_mode_str(const int mode)
3529 {
3530 	if (mode >= MCAST_UNDEFINED && mode <= MCAST_EXCLUDE) {
3531 		return in6m_modestrs[mode];
3532 	}
3533 	return "??";
3534 }
3535 
3536 static const char *in6m_statestrs[] = {
3537 	"not-member",
3538 	"silent",
3539 	"reporting",
3540 	"idle",
3541 	"lazy",
3542 	"sleeping",
3543 	"awakening",
3544 	"query-pending",
3545 	"sg-query-pending",
3546 	"leaving"
3547 };
3548 
3549 static const char *
in6m_state_str(const int state)3550 in6m_state_str(const int state)
3551 {
3552 	if (state >= MLD_NOT_MEMBER && state <= MLD_LEAVING_MEMBER) {
3553 		return in6m_statestrs[state];
3554 	}
3555 	return "??";
3556 }
3557 
3558 /*
3559  * Dump an in6_multi structure to the console.
3560  */
3561 void
in6m_print(const struct in6_multi * inm)3562 in6m_print(const struct in6_multi *inm)
3563 {
3564 	int t;
3565 
3566 	IN6M_LOCK_ASSERT_HELD(__DECONST(struct in6_multi *, inm));
3567 
3568 	if (mld_debug == 0) {
3569 		return;
3570 	}
3571 
3572 	printf("%s: --- begin in6m 0x%llx ---\n", __func__,
3573 	    (uint64_t)VM_KERNEL_ADDRPERM(inm));
3574 	printf("addr %s ifp 0x%llx(%s) ifma 0x%llx\n",
3575 	    ip6_sprintf(&inm->in6m_addr),
3576 	    (uint64_t)VM_KERNEL_ADDRPERM(inm->in6m_ifp),
3577 	    if_name(inm->in6m_ifp),
3578 	    (uint64_t)VM_KERNEL_ADDRPERM(inm->in6m_ifma));
3579 	printf("timer %u state %s refcount %u scq.len %u\n",
3580 	    inm->in6m_timer,
3581 	    in6m_state_str(inm->in6m_state),
3582 	    inm->in6m_refcount,
3583 	    inm->in6m_scq.ifq_len);
3584 	printf("mli 0x%llx nsrc %lu sctimer %u scrv %u\n",
3585 	    (uint64_t)VM_KERNEL_ADDRPERM(inm->in6m_mli),
3586 	    inm->in6m_nsrc,
3587 	    inm->in6m_sctimer,
3588 	    inm->in6m_scrv);
3589 	for (t = 0; t < 2; t++) {
3590 		printf("t%d: fmode %s asm %u ex %u in %u rec %u\n", t,
3591 		    in6m_mode_str(inm->in6m_st[t].iss_fmode),
3592 		    inm->in6m_st[t].iss_asm,
3593 		    inm->in6m_st[t].iss_ex,
3594 		    inm->in6m_st[t].iss_in,
3595 		    inm->in6m_st[t].iss_rec);
3596 	}
3597 	printf("%s: --- end in6m 0x%llx ---\n", __func__,
3598 	    (uint64_t)VM_KERNEL_ADDRPERM(inm));
3599 }
3600 
3601 #else
3602 
3603 void
in6m_print(__unused const struct in6_multi * inm)3604 in6m_print(__unused const struct in6_multi *inm)
3605 {
3606 }
3607 
3608 #endif
3609