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