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