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