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