xref: /freebsd/sys/netinet/igmp.c (revision 266f97b5)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2007-2009 Bruce Simpson.
5  * Copyright (c) 1988 Stephen Deering.
6  * Copyright (c) 1992, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Stephen Deering of Stanford University.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)igmp.c	8.1 (Berkeley) 7/19/93
37  */
38 
39 /*
40  * Internet Group Management Protocol (IGMP) routines.
41  * [RFC1112, RFC2236, RFC3376]
42  *
43  * Written by Steve Deering, Stanford, May 1988.
44  * Modified by Rosen Sharma, Stanford, Aug 1994.
45  * Modified by Bill Fenner, Xerox PARC, Feb 1995.
46  * Modified to fully comply to IGMPv2 by Bill Fenner, Oct 1995.
47  * Significantly rewritten for IGMPv3, VIMAGE, and SMP by Bruce Simpson.
48  *
49  * MULTICAST Revision: 3.5.1.4
50  */
51 
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54 
55 #include "opt_ddb.h"
56 
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/module.h>
60 #include <sys/malloc.h>
61 #include <sys/mbuf.h>
62 #include <sys/socket.h>
63 #include <sys/protosw.h>
64 #include <sys/kernel.h>
65 #include <sys/lock.h>
66 #include <sys/sysctl.h>
67 #include <sys/ktr.h>
68 #include <sys/condvar.h>
69 
70 #ifdef DDB
71 #include <ddb/ddb.h>
72 #endif
73 
74 #include <net/if.h>
75 #include <net/if_var.h>
76 #include <net/netisr.h>
77 #include <net/vnet.h>
78 
79 #include <netinet/in.h>
80 #include <netinet/in_var.h>
81 #include <netinet/in_systm.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_var.h>
84 #include <netinet/ip_options.h>
85 #include <netinet/igmp.h>
86 #include <netinet/igmp_var.h>
87 
88 #include <machine/in_cksum.h>
89 
90 #include <security/mac/mac_framework.h>
91 
92 #ifndef KTR_IGMPV3
93 #define KTR_IGMPV3 KTR_INET
94 #endif
95 
96 static struct igmp_ifsoftc *
97 		igi_alloc_locked(struct ifnet *);
98 static void	igi_delete_locked(const struct ifnet *);
99 static void	igmp_dispatch_queue(struct mbufq *, int, const int);
100 static void	igmp_fasttimo_vnet(void);
101 static void	igmp_final_leave(struct in_multi *, struct igmp_ifsoftc *);
102 static int	igmp_handle_state_change(struct in_multi *,
103 		    struct igmp_ifsoftc *);
104 static int	igmp_initial_join(struct in_multi *, struct igmp_ifsoftc *);
105 static int	igmp_input_v1_query(struct ifnet *, const struct ip *,
106 		    const struct igmp *);
107 static int	igmp_input_v2_query(struct ifnet *, const struct ip *,
108 		    const struct igmp *);
109 static int	igmp_input_v3_query(struct ifnet *, const struct ip *,
110 		    /*const*/ struct igmpv3 *);
111 static int	igmp_input_v3_group_query(struct in_multi *,
112 		    struct igmp_ifsoftc *, int, /*const*/ struct igmpv3 *);
113 static int	igmp_input_v1_report(struct ifnet *, /*const*/ struct ip *,
114 		    /*const*/ struct igmp *);
115 static int	igmp_input_v2_report(struct ifnet *, /*const*/ struct ip *,
116 		    /*const*/ struct igmp *);
117 static void	igmp_intr(struct mbuf *);
118 static int	igmp_isgroupreported(const struct in_addr);
119 static struct mbuf *
120 		igmp_ra_alloc(void);
121 #ifdef KTR
122 static char *	igmp_rec_type_to_str(const int);
123 #endif
124 static void	igmp_set_version(struct igmp_ifsoftc *, const int);
125 static void	igmp_slowtimo_vnet(void);
126 static int	igmp_v1v2_queue_report(struct in_multi *, const int);
127 static void	igmp_v1v2_process_group_timer(struct in_multi *, const int);
128 static void	igmp_v1v2_process_querier_timers(struct igmp_ifsoftc *);
129 static void	igmp_v2_update_group(struct in_multi *, const int);
130 static void	igmp_v3_cancel_link_timers(struct igmp_ifsoftc *);
131 static void	igmp_v3_dispatch_general_query(struct igmp_ifsoftc *);
132 static struct mbuf *
133 		igmp_v3_encap_report(struct ifnet *, struct mbuf *);
134 static int	igmp_v3_enqueue_group_record(struct mbufq *,
135 		    struct in_multi *, const int, const int, const int);
136 static int	igmp_v3_enqueue_filter_change(struct mbufq *,
137 		    struct in_multi *);
138 static void	igmp_v3_process_group_timers(struct in_multi_head *,
139 		    struct mbufq *, struct mbufq *, struct in_multi *,
140 		    const int);
141 static int	igmp_v3_merge_state_changes(struct in_multi *,
142 		    struct mbufq *);
143 static void	igmp_v3_suppress_group_record(struct in_multi *);
144 static int	sysctl_igmp_default_version(SYSCTL_HANDLER_ARGS);
145 static int	sysctl_igmp_gsr(SYSCTL_HANDLER_ARGS);
146 static int	sysctl_igmp_ifinfo(SYSCTL_HANDLER_ARGS);
147 static int	sysctl_igmp_stat(SYSCTL_HANDLER_ARGS);
148 
149 static const struct netisr_handler igmp_nh = {
150 	.nh_name = "igmp",
151 	.nh_handler = igmp_intr,
152 	.nh_proto = NETISR_IGMP,
153 	.nh_policy = NETISR_POLICY_SOURCE,
154 };
155 
156 /*
157  * System-wide globals.
158  *
159  * Unlocked access to these is OK, except for the global IGMP output
160  * queue. The IGMP subsystem lock ends up being system-wide for the moment,
161  * because all VIMAGEs have to share a global output queue, as netisrs
162  * themselves are not virtualized.
163  *
164  * Locking:
165  *  * The permitted lock order is: IN_MULTI_LIST_LOCK, IGMP_LOCK, IF_ADDR_LOCK.
166  *    Any may be taken independently; if any are held at the same
167  *    time, the above lock order must be followed.
168  *  * All output is delegated to the netisr.
169  *    Now that Giant has been eliminated, the netisr may be inlined.
170  *  * IN_MULTI_LIST_LOCK covers in_multi.
171  *  * IGMP_LOCK covers igmp_ifsoftc and any global variables in this file,
172  *    including the output queue.
173  *  * IF_ADDR_LOCK covers if_multiaddrs, which is used for a variety of
174  *    per-link state iterators.
175  *  * igmp_ifsoftc is valid as long as PF_INET is attached to the interface,
176  *    therefore it is not refcounted.
177  *    We allow unlocked reads of igmp_ifsoftc when accessed via in_multi.
178  *
179  * Reference counting
180  *  * IGMP acquires its own reference every time an in_multi is passed to
181  *    it and the group is being joined for the first time.
182  *  * IGMP releases its reference(s) on in_multi in a deferred way,
183  *    because the operations which process the release run as part of
184  *    a loop whose control variables are directly affected by the release
185  *    (that, and not recursing on the IF_ADDR_LOCK).
186  *
187  * VIMAGE: Each in_multi corresponds to an ifp, and each ifp corresponds
188  * to a vnet in ifp->if_vnet.
189  *
190  * SMPng: XXX We may potentially race operations on ifma_protospec.
191  * The problem is that we currently lack a clean way of taking the
192  * IF_ADDR_LOCK() between the ifnet and in layers w/o recursing,
193  * as anything which modifies ifma needs to be covered by that lock.
194  * So check for ifma_protospec being NULL before proceeding.
195  */
196 struct mtx		 igmp_mtx;
197 
198 struct mbuf		*m_raopt;		 /* Router Alert option */
199 static MALLOC_DEFINE(M_IGMP, "igmp", "igmp state");
200 
201 /*
202  * VIMAGE-wide globals.
203  *
204  * The IGMPv3 timers themselves need to run per-image, however,
205  * protosw timers run globally (see tcp).
206  * An ifnet can only be in one vimage at a time, and the loopback
207  * ifnet, loif, is itself virtualized.
208  * It would otherwise be possible to seriously hose IGMP state,
209  * and create inconsistencies in upstream multicast routing, if you have
210  * multiple VIMAGEs running on the same link joining different multicast
211  * groups, UNLESS the "primary IP address" is different. This is because
212  * IGMP for IPv4 does not force link-local addresses to be used for each
213  * node, unlike MLD for IPv6.
214  * Obviously the IGMPv3 per-interface state has per-vimage granularity
215  * also as a result.
216  *
217  * FUTURE: Stop using IFP_TO_IA/INADDR_ANY, and use source address selection
218  * policy to control the address used by IGMP on the link.
219  */
220 VNET_DEFINE_STATIC(int, interface_timers_running);	/* IGMPv3 general
221 							 * query response */
222 VNET_DEFINE_STATIC(int, state_change_timers_running);	/* IGMPv3 state-change
223 							 * retransmit */
224 VNET_DEFINE_STATIC(int, current_state_timers_running);	/* IGMPv1/v2 host
225 							 * report; IGMPv3 g/sg
226 							 * query response */
227 
228 #define	V_interface_timers_running	VNET(interface_timers_running)
229 #define	V_state_change_timers_running	VNET(state_change_timers_running)
230 #define	V_current_state_timers_running	VNET(current_state_timers_running)
231 
232 VNET_PCPUSTAT_DEFINE(struct igmpstat, igmpstat);
233 VNET_PCPUSTAT_SYSINIT(igmpstat);
234 VNET_PCPUSTAT_SYSUNINIT(igmpstat);
235 
236 VNET_DEFINE_STATIC(LIST_HEAD(, igmp_ifsoftc), igi_head) =
237     LIST_HEAD_INITIALIZER(igi_head);
238 VNET_DEFINE_STATIC(struct timeval, igmp_gsrdelay) = {10, 0};
239 
240 #define	V_igi_head			VNET(igi_head)
241 #define	V_igmp_gsrdelay			VNET(igmp_gsrdelay)
242 
243 VNET_DEFINE_STATIC(int, igmp_recvifkludge) = 1;
244 VNET_DEFINE_STATIC(int, igmp_sendra) = 1;
245 VNET_DEFINE_STATIC(int, igmp_sendlocal) = 1;
246 VNET_DEFINE_STATIC(int, igmp_v1enable) = 1;
247 VNET_DEFINE_STATIC(int, igmp_v2enable) = 1;
248 VNET_DEFINE_STATIC(int, igmp_legacysupp);
249 VNET_DEFINE_STATIC(int, igmp_default_version) = IGMP_VERSION_3;
250 
251 #define	V_igmp_recvifkludge		VNET(igmp_recvifkludge)
252 #define	V_igmp_sendra			VNET(igmp_sendra)
253 #define	V_igmp_sendlocal		VNET(igmp_sendlocal)
254 #define	V_igmp_v1enable			VNET(igmp_v1enable)
255 #define	V_igmp_v2enable			VNET(igmp_v2enable)
256 #define	V_igmp_legacysupp		VNET(igmp_legacysupp)
257 #define	V_igmp_default_version		VNET(igmp_default_version)
258 
259 /*
260  * Virtualized sysctls.
261  */
262 SYSCTL_PROC(_net_inet_igmp, IGMPCTL_STATS, stats,
263     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_MPSAFE,
264     &VNET_NAME(igmpstat), 0, sysctl_igmp_stat, "S,igmpstat",
265     "IGMP statistics (struct igmpstat, netinet/igmp_var.h)");
266 SYSCTL_INT(_net_inet_igmp, OID_AUTO, recvifkludge, CTLFLAG_VNET | CTLFLAG_RW,
267     &VNET_NAME(igmp_recvifkludge), 0,
268     "Rewrite IGMPv1/v2 reports from 0.0.0.0 to contain subnet address");
269 SYSCTL_INT(_net_inet_igmp, OID_AUTO, sendra, CTLFLAG_VNET | CTLFLAG_RW,
270     &VNET_NAME(igmp_sendra), 0,
271     "Send IP Router Alert option in IGMPv2/v3 messages");
272 SYSCTL_INT(_net_inet_igmp, OID_AUTO, sendlocal, CTLFLAG_VNET | CTLFLAG_RW,
273     &VNET_NAME(igmp_sendlocal), 0,
274     "Send IGMP membership reports for 224.0.0.0/24 groups");
275 SYSCTL_INT(_net_inet_igmp, OID_AUTO, v1enable, CTLFLAG_VNET | CTLFLAG_RW,
276     &VNET_NAME(igmp_v1enable), 0,
277     "Enable backwards compatibility with IGMPv1");
278 SYSCTL_INT(_net_inet_igmp, OID_AUTO, v2enable, CTLFLAG_VNET | CTLFLAG_RW,
279     &VNET_NAME(igmp_v2enable), 0,
280     "Enable backwards compatibility with IGMPv2");
281 SYSCTL_INT(_net_inet_igmp, OID_AUTO, legacysupp, CTLFLAG_VNET | CTLFLAG_RW,
282     &VNET_NAME(igmp_legacysupp), 0,
283     "Allow v1/v2 reports to suppress v3 group responses");
284 SYSCTL_PROC(_net_inet_igmp, OID_AUTO, default_version,
285     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
286     &VNET_NAME(igmp_default_version), 0, sysctl_igmp_default_version, "I",
287     "Default version of IGMP to run on each interface");
288 SYSCTL_PROC(_net_inet_igmp, OID_AUTO, gsrdelay,
289     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
290     &VNET_NAME(igmp_gsrdelay.tv_sec), 0, sysctl_igmp_gsr, "I",
291     "Rate limit for IGMPv3 Group-and-Source queries in seconds");
292 
293 /*
294  * Non-virtualized sysctls.
295  */
296 static SYSCTL_NODE(_net_inet_igmp, OID_AUTO, ifinfo,
297     CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_igmp_ifinfo,
298     "Per-interface IGMPv3 state");
299 
300 static __inline void
301 igmp_save_context(struct mbuf *m, struct ifnet *ifp)
302 {
303 
304 #ifdef VIMAGE
305 	m->m_pkthdr.PH_loc.ptr = ifp->if_vnet;
306 #endif /* VIMAGE */
307 	m->m_pkthdr.rcvif = ifp;
308 	m->m_pkthdr.flowid = ifp->if_index;
309 }
310 
311 static __inline void
312 igmp_scrub_context(struct mbuf *m)
313 {
314 
315 	m->m_pkthdr.PH_loc.ptr = NULL;
316 	m->m_pkthdr.flowid = 0;
317 }
318 
319 /*
320  * Restore context from a queued IGMP output chain.
321  * Return saved ifindex.
322  *
323  * VIMAGE: The assertion is there to make sure that we
324  * actually called CURVNET_SET() with what's in the mbuf chain.
325  */
326 static __inline uint32_t
327 igmp_restore_context(struct mbuf *m)
328 {
329 
330 #ifdef notyet
331 #if defined(VIMAGE) && defined(INVARIANTS)
332 	KASSERT(curvnet == (m->m_pkthdr.PH_loc.ptr),
333 	    ("%s: called when curvnet was not restored", __func__));
334 #endif
335 #endif
336 	return (m->m_pkthdr.flowid);
337 }
338 
339 /*
340  * IGMP statistics.
341  */
342 static int
343 sysctl_igmp_stat(SYSCTL_HANDLER_ARGS)
344 {
345 	struct igmpstat igps0;
346 	int error;
347 	char *p;
348 
349 	error = sysctl_wire_old_buffer(req, sizeof(struct igmpstat));
350 	if (error)
351 		return (error);
352 
353 	if (req->oldptr != NULL) {
354 		if (req->oldlen < sizeof(struct igmpstat))
355 			error = ENOMEM;
356 		else {
357 			/*
358 			 * Copy the counters, and explicitly set the struct's
359 			 * version and length fields.
360 			 */
361 			COUNTER_ARRAY_COPY(VNET(igmpstat), &igps0,
362 			    sizeof(struct igmpstat) / sizeof(uint64_t));
363 			igps0.igps_version = IGPS_VERSION_3;
364 			igps0.igps_len = IGPS_VERSION3_LEN;
365 			error = SYSCTL_OUT(req, &igps0,
366 			    sizeof(struct igmpstat));
367 		}
368 	} else
369 		req->validlen = sizeof(struct igmpstat);
370 	if (error)
371 		goto out;
372 	if (req->newptr != NULL) {
373 		if (req->newlen < sizeof(struct igmpstat))
374 			error = ENOMEM;
375 		else
376 			error = SYSCTL_IN(req, &igps0,
377 			    sizeof(igps0));
378 		if (error)
379 			goto out;
380 		/*
381 		 * igps0 must be "all zero".
382 		 */
383 		p = (char *)&igps0;
384 		while (p < (char *)&igps0 + sizeof(igps0) && *p == '\0')
385 			p++;
386 		if (p != (char *)&igps0 + sizeof(igps0)) {
387 			error = EINVAL;
388 			goto out;
389 		}
390 		COUNTER_ARRAY_ZERO(VNET(igmpstat),
391 		    sizeof(struct igmpstat) / sizeof(uint64_t));
392 	}
393 out:
394 	return (error);
395 }
396 
397 /*
398  * Retrieve or set default IGMP version.
399  *
400  * VIMAGE: Assume curvnet set by caller.
401  * SMPng: NOTE: Serialized by IGMP lock.
402  */
403 static int
404 sysctl_igmp_default_version(SYSCTL_HANDLER_ARGS)
405 {
406 	int	 error;
407 	int	 new;
408 
409 	error = sysctl_wire_old_buffer(req, sizeof(int));
410 	if (error)
411 		return (error);
412 
413 	IGMP_LOCK();
414 
415 	new = V_igmp_default_version;
416 
417 	error = sysctl_handle_int(oidp, &new, 0, req);
418 	if (error || !req->newptr)
419 		goto out_locked;
420 
421 	if (new < IGMP_VERSION_1 || new > IGMP_VERSION_3) {
422 		error = EINVAL;
423 		goto out_locked;
424 	}
425 
426 	CTR2(KTR_IGMPV3, "change igmp_default_version from %d to %d",
427 	     V_igmp_default_version, new);
428 
429 	V_igmp_default_version = new;
430 
431 out_locked:
432 	IGMP_UNLOCK();
433 	return (error);
434 }
435 
436 /*
437  * Retrieve or set threshold between group-source queries in seconds.
438  *
439  * VIMAGE: Assume curvnet set by caller.
440  * SMPng: NOTE: Serialized by IGMP lock.
441  */
442 static int
443 sysctl_igmp_gsr(SYSCTL_HANDLER_ARGS)
444 {
445 	int error;
446 	int i;
447 
448 	error = sysctl_wire_old_buffer(req, sizeof(int));
449 	if (error)
450 		return (error);
451 
452 	IGMP_LOCK();
453 
454 	i = V_igmp_gsrdelay.tv_sec;
455 
456 	error = sysctl_handle_int(oidp, &i, 0, req);
457 	if (error || !req->newptr)
458 		goto out_locked;
459 
460 	if (i < -1 || i >= 60) {
461 		error = EINVAL;
462 		goto out_locked;
463 	}
464 
465 	CTR2(KTR_IGMPV3, "change igmp_gsrdelay from %d to %d",
466 	     V_igmp_gsrdelay.tv_sec, i);
467 	V_igmp_gsrdelay.tv_sec = i;
468 
469 out_locked:
470 	IGMP_UNLOCK();
471 	return (error);
472 }
473 
474 /*
475  * Expose struct igmp_ifsoftc to userland, keyed by ifindex.
476  * For use by ifmcstat(8).
477  *
478  * SMPng: NOTE: Does an unlocked ifindex space read.
479  * VIMAGE: Assume curvnet set by caller. The node handler itself
480  * is not directly virtualized.
481  */
482 static int
483 sysctl_igmp_ifinfo(SYSCTL_HANDLER_ARGS)
484 {
485 	int			*name;
486 	int			 error;
487 	u_int			 namelen;
488 	struct ifnet		*ifp;
489 	struct igmp_ifsoftc	*igi;
490 
491 	name = (int *)arg1;
492 	namelen = arg2;
493 
494 	if (req->newptr != NULL)
495 		return (EPERM);
496 
497 	if (namelen != 1)
498 		return (EINVAL);
499 
500 	error = sysctl_wire_old_buffer(req, sizeof(struct igmp_ifinfo));
501 	if (error)
502 		return (error);
503 
504 	IN_MULTI_LIST_LOCK();
505 	IGMP_LOCK();
506 
507 	if (name[0] <= 0 || name[0] > V_if_index) {
508 		error = ENOENT;
509 		goto out_locked;
510 	}
511 
512 	error = ENOENT;
513 
514 	ifp = ifnet_byindex(name[0]);
515 	if (ifp == NULL)
516 		goto out_locked;
517 
518 	LIST_FOREACH(igi, &V_igi_head, igi_link) {
519 		if (ifp == igi->igi_ifp) {
520 			struct igmp_ifinfo info;
521 
522 			info.igi_version = igi->igi_version;
523 			info.igi_v1_timer = igi->igi_v1_timer;
524 			info.igi_v2_timer = igi->igi_v2_timer;
525 			info.igi_v3_timer = igi->igi_v3_timer;
526 			info.igi_flags = igi->igi_flags;
527 			info.igi_rv = igi->igi_rv;
528 			info.igi_qi = igi->igi_qi;
529 			info.igi_qri = igi->igi_qri;
530 			info.igi_uri = igi->igi_uri;
531 			error = SYSCTL_OUT(req, &info, sizeof(info));
532 			break;
533 		}
534 	}
535 
536 out_locked:
537 	IGMP_UNLOCK();
538 	IN_MULTI_LIST_UNLOCK();
539 	return (error);
540 }
541 
542 /*
543  * Dispatch an entire queue of pending packet chains
544  * using the netisr.
545  * VIMAGE: Assumes the vnet pointer has been set.
546  */
547 static void
548 igmp_dispatch_queue(struct mbufq *mq, int limit, const int loop)
549 {
550 	struct epoch_tracker et;
551 	struct mbuf *m;
552 
553 	NET_EPOCH_ENTER(et);
554 	while ((m = mbufq_dequeue(mq)) != NULL) {
555 		CTR3(KTR_IGMPV3, "%s: dispatch %p from %p", __func__, mq, m);
556 		if (loop)
557 			m->m_flags |= M_IGMP_LOOP;
558 		netisr_dispatch(NETISR_IGMP, m);
559 		if (--limit == 0)
560 			break;
561 	}
562 	NET_EPOCH_EXIT(et);
563 }
564 
565 /*
566  * Filter outgoing IGMP report state by group.
567  *
568  * Reports are ALWAYS suppressed for ALL-HOSTS (224.0.0.1).
569  * If the net.inet.igmp.sendlocal sysctl is 0, then IGMP reports are
570  * disabled for all groups in the 224.0.0.0/24 link-local scope. However,
571  * this may break certain IGMP snooping switches which rely on the old
572  * report behaviour.
573  *
574  * Return zero if the given group is one for which IGMP reports
575  * should be suppressed, or non-zero if reports should be issued.
576  */
577 static __inline int
578 igmp_isgroupreported(const struct in_addr addr)
579 {
580 
581 	if (in_allhosts(addr) ||
582 	    ((!V_igmp_sendlocal && IN_LOCAL_GROUP(ntohl(addr.s_addr)))))
583 		return (0);
584 
585 	return (1);
586 }
587 
588 /*
589  * Construct a Router Alert option to use in outgoing packets.
590  */
591 static struct mbuf *
592 igmp_ra_alloc(void)
593 {
594 	struct mbuf	*m;
595 	struct ipoption	*p;
596 
597 	m = m_get(M_WAITOK, MT_DATA);
598 	p = mtod(m, struct ipoption *);
599 	p->ipopt_dst.s_addr = INADDR_ANY;
600 	p->ipopt_list[0] = (char)IPOPT_RA;	/* Router Alert Option */
601 	p->ipopt_list[1] = 0x04;		/* 4 bytes long */
602 	p->ipopt_list[2] = IPOPT_EOL;		/* End of IP option list */
603 	p->ipopt_list[3] = 0x00;		/* pad byte */
604 	m->m_len = sizeof(p->ipopt_dst) + p->ipopt_list[1];
605 
606 	return (m);
607 }
608 
609 /*
610  * Attach IGMP when PF_INET is attached to an interface.
611  */
612 struct igmp_ifsoftc *
613 igmp_domifattach(struct ifnet *ifp)
614 {
615 	struct igmp_ifsoftc *igi;
616 
617 	CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)",
618 	    __func__, ifp, ifp->if_xname);
619 
620 	IGMP_LOCK();
621 
622 	igi = igi_alloc_locked(ifp);
623 	if (!(ifp->if_flags & IFF_MULTICAST))
624 		igi->igi_flags |= IGIF_SILENT;
625 
626 	IGMP_UNLOCK();
627 
628 	return (igi);
629 }
630 
631 /*
632  * VIMAGE: assume curvnet set by caller.
633  */
634 static struct igmp_ifsoftc *
635 igi_alloc_locked(/*const*/ struct ifnet *ifp)
636 {
637 	struct igmp_ifsoftc *igi;
638 
639 	IGMP_LOCK_ASSERT();
640 
641 	igi = malloc(sizeof(struct igmp_ifsoftc), M_IGMP, M_NOWAIT|M_ZERO);
642 	if (igi == NULL)
643 		goto out;
644 
645 	igi->igi_ifp = ifp;
646 	igi->igi_version = V_igmp_default_version;
647 	igi->igi_flags = 0;
648 	igi->igi_rv = IGMP_RV_INIT;
649 	igi->igi_qi = IGMP_QI_INIT;
650 	igi->igi_qri = IGMP_QRI_INIT;
651 	igi->igi_uri = IGMP_URI_INIT;
652 	mbufq_init(&igi->igi_gq, IGMP_MAX_RESPONSE_PACKETS);
653 
654 	LIST_INSERT_HEAD(&V_igi_head, igi, igi_link);
655 
656 	CTR2(KTR_IGMPV3, "allocate igmp_ifsoftc for ifp %p(%s)",
657 	     ifp, ifp->if_xname);
658 
659 out:
660 	return (igi);
661 }
662 
663 /*
664  * Hook for ifdetach.
665  *
666  * NOTE: Some finalization tasks need to run before the protocol domain
667  * is detached, but also before the link layer does its cleanup.
668  *
669  * SMPNG: igmp_ifdetach() needs to take IF_ADDR_LOCK().
670  * XXX This is also bitten by unlocked ifma_protospec access.
671  */
672 void
673 igmp_ifdetach(struct ifnet *ifp)
674 {
675 	struct igmp_ifsoftc	*igi;
676 	struct ifmultiaddr	*ifma, *next;
677 	struct in_multi		*inm;
678 	struct in_multi_head inm_free_tmp;
679 	CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)", __func__, ifp,
680 	    ifp->if_xname);
681 
682 	SLIST_INIT(&inm_free_tmp);
683 	IGMP_LOCK();
684 
685 	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
686 	if (igi->igi_version == IGMP_VERSION_3) {
687 		IF_ADDR_WLOCK(ifp);
688 	restart:
689 		CK_STAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next) {
690 			if (ifma->ifma_addr->sa_family != AF_INET ||
691 			    ifma->ifma_protospec == NULL)
692 				continue;
693 			inm = (struct in_multi *)ifma->ifma_protospec;
694 			if (inm->inm_state == IGMP_LEAVING_MEMBER)
695 				inm_rele_locked(&inm_free_tmp, inm);
696 			inm_clear_recorded(inm);
697 			if (__predict_false(ifma_restart)) {
698 				ifma_restart = false;
699 				goto restart;
700 			}
701 		}
702 		IF_ADDR_WUNLOCK(ifp);
703 		inm_release_list_deferred(&inm_free_tmp);
704 	}
705 	IGMP_UNLOCK();
706 
707 }
708 
709 /*
710  * Hook for domifdetach.
711  */
712 void
713 igmp_domifdetach(struct ifnet *ifp)
714 {
715 
716 	CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)",
717 	    __func__, ifp, ifp->if_xname);
718 
719 	IGMP_LOCK();
720 	igi_delete_locked(ifp);
721 	IGMP_UNLOCK();
722 }
723 
724 static void
725 igi_delete_locked(const struct ifnet *ifp)
726 {
727 	struct igmp_ifsoftc *igi, *tigi;
728 
729 	CTR3(KTR_IGMPV3, "%s: freeing igmp_ifsoftc for ifp %p(%s)",
730 	    __func__, ifp, ifp->if_xname);
731 
732 	IGMP_LOCK_ASSERT();
733 
734 	LIST_FOREACH_SAFE(igi, &V_igi_head, igi_link, tigi) {
735 		if (igi->igi_ifp == ifp) {
736 			/*
737 			 * Free deferred General Query responses.
738 			 */
739 			mbufq_drain(&igi->igi_gq);
740 
741 			LIST_REMOVE(igi, igi_link);
742 			free(igi, M_IGMP);
743 			return;
744 		}
745 	}
746 }
747 
748 /*
749  * Process a received IGMPv1 query.
750  * Return non-zero if the message should be dropped.
751  *
752  * VIMAGE: The curvnet pointer is derived from the input ifp.
753  */
754 static int
755 igmp_input_v1_query(struct ifnet *ifp, const struct ip *ip,
756     const struct igmp *igmp)
757 {
758 	struct ifmultiaddr	*ifma;
759 	struct igmp_ifsoftc	*igi;
760 	struct in_multi		*inm;
761 
762 	NET_EPOCH_ASSERT();
763 
764 	/*
765 	 * IGMPv1 Host Mmembership Queries SHOULD always be addressed to
766 	 * 224.0.0.1. They are always treated as General Queries.
767 	 * igmp_group is always ignored. Do not drop it as a userland
768 	 * daemon may wish to see it.
769 	 * XXX SMPng: unlocked increments in igmpstat assumed atomic.
770 	 */
771 	if (!in_allhosts(ip->ip_dst) || !in_nullhost(igmp->igmp_group)) {
772 		IGMPSTAT_INC(igps_rcv_badqueries);
773 		return (0);
774 	}
775 	IGMPSTAT_INC(igps_rcv_gen_queries);
776 
777 	IN_MULTI_LIST_LOCK();
778 	IGMP_LOCK();
779 
780 	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
781 	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
782 
783 	if (igi->igi_flags & IGIF_LOOPBACK) {
784 		CTR2(KTR_IGMPV3, "ignore v1 query on IGIF_LOOPBACK ifp %p(%s)",
785 		    ifp, ifp->if_xname);
786 		goto out_locked;
787 	}
788 
789 	/*
790 	 * Switch to IGMPv1 host compatibility mode.
791 	 */
792 	igmp_set_version(igi, IGMP_VERSION_1);
793 
794 	CTR2(KTR_IGMPV3, "process v1 query on ifp %p(%s)", ifp, ifp->if_xname);
795 
796 	/*
797 	 * Start the timers in all of our group records
798 	 * for the interface on which the query arrived,
799 	 * except those which are already running.
800 	 */
801 	CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
802 		if (ifma->ifma_addr->sa_family != AF_INET ||
803 		    ifma->ifma_protospec == NULL)
804 			continue;
805 		inm = (struct in_multi *)ifma->ifma_protospec;
806 		if (inm->inm_timer != 0)
807 			continue;
808 		switch (inm->inm_state) {
809 		case IGMP_NOT_MEMBER:
810 		case IGMP_SILENT_MEMBER:
811 			break;
812 		case IGMP_G_QUERY_PENDING_MEMBER:
813 		case IGMP_SG_QUERY_PENDING_MEMBER:
814 		case IGMP_REPORTING_MEMBER:
815 		case IGMP_IDLE_MEMBER:
816 		case IGMP_LAZY_MEMBER:
817 		case IGMP_SLEEPING_MEMBER:
818 		case IGMP_AWAKENING_MEMBER:
819 			inm->inm_state = IGMP_REPORTING_MEMBER;
820 			inm->inm_timer = IGMP_RANDOM_DELAY(
821 			    IGMP_V1V2_MAX_RI * PR_FASTHZ);
822 			V_current_state_timers_running = 1;
823 			break;
824 		case IGMP_LEAVING_MEMBER:
825 			break;
826 		}
827 	}
828 
829 out_locked:
830 	IGMP_UNLOCK();
831 	IN_MULTI_LIST_UNLOCK();
832 
833 	return (0);
834 }
835 
836 /*
837  * Process a received IGMPv2 general or group-specific query.
838  */
839 static int
840 igmp_input_v2_query(struct ifnet *ifp, const struct ip *ip,
841     const struct igmp *igmp)
842 {
843 	struct ifmultiaddr	*ifma;
844 	struct igmp_ifsoftc	*igi;
845 	struct in_multi		*inm;
846 	int			 is_general_query;
847 	uint16_t		 timer;
848 
849 	NET_EPOCH_ASSERT();
850 
851 	is_general_query = 0;
852 
853 	/*
854 	 * Validate address fields upfront.
855 	 * XXX SMPng: unlocked increments in igmpstat assumed atomic.
856 	 */
857 	if (in_nullhost(igmp->igmp_group)) {
858 		/*
859 		 * IGMPv2 General Query.
860 		 * If this was not sent to the all-hosts group, ignore it.
861 		 */
862 		if (!in_allhosts(ip->ip_dst))
863 			return (0);
864 		IGMPSTAT_INC(igps_rcv_gen_queries);
865 		is_general_query = 1;
866 	} else {
867 		/* IGMPv2 Group-Specific Query. */
868 		IGMPSTAT_INC(igps_rcv_group_queries);
869 	}
870 
871 	IN_MULTI_LIST_LOCK();
872 	IGMP_LOCK();
873 
874 	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
875 	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
876 
877 	if (igi->igi_flags & IGIF_LOOPBACK) {
878 		CTR2(KTR_IGMPV3, "ignore v2 query on IGIF_LOOPBACK ifp %p(%s)",
879 		    ifp, ifp->if_xname);
880 		goto out_locked;
881 	}
882 
883 	/*
884 	 * Ignore v2 query if in v1 Compatibility Mode.
885 	 */
886 	if (igi->igi_version == IGMP_VERSION_1)
887 		goto out_locked;
888 
889 	igmp_set_version(igi, IGMP_VERSION_2);
890 
891 	timer = igmp->igmp_code * PR_FASTHZ / IGMP_TIMER_SCALE;
892 	if (timer == 0)
893 		timer = 1;
894 
895 	if (is_general_query) {
896 		/*
897 		 * For each reporting group joined on this
898 		 * interface, kick the report timer.
899 		 */
900 		CTR2(KTR_IGMPV3, "process v2 general query on ifp %p(%s)",
901 		    ifp, ifp->if_xname);
902 		CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
903 			if (ifma->ifma_addr->sa_family != AF_INET ||
904 			    ifma->ifma_protospec == NULL)
905 				continue;
906 			inm = (struct in_multi *)ifma->ifma_protospec;
907 			igmp_v2_update_group(inm, timer);
908 		}
909 	} else {
910 		/*
911 		 * Group-specific IGMPv2 query, we need only
912 		 * look up the single group to process it.
913 		 */
914 		inm = inm_lookup(ifp, igmp->igmp_group);
915 		if (inm != NULL) {
916 			CTR3(KTR_IGMPV3,
917 			    "process v2 query 0x%08x on ifp %p(%s)",
918 			    ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
919 			igmp_v2_update_group(inm, timer);
920 		}
921 	}
922 
923 out_locked:
924 	IGMP_UNLOCK();
925 	IN_MULTI_LIST_UNLOCK();
926 
927 	return (0);
928 }
929 
930 /*
931  * Update the report timer on a group in response to an IGMPv2 query.
932  *
933  * If we are becoming the reporting member for this group, start the timer.
934  * If we already are the reporting member for this group, and timer is
935  * below the threshold, reset it.
936  *
937  * We may be updating the group for the first time since we switched
938  * to IGMPv3. If we are, then we must clear any recorded source lists,
939  * and transition to REPORTING state; the group timer is overloaded
940  * for group and group-source query responses.
941  *
942  * Unlike IGMPv3, the delay per group should be jittered
943  * to avoid bursts of IGMPv2 reports.
944  */
945 static void
946 igmp_v2_update_group(struct in_multi *inm, const int timer)
947 {
948 
949 	CTR4(KTR_IGMPV3, "0x%08x: %s/%s timer=%d", __func__,
950 	    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname, timer);
951 
952 	IN_MULTI_LIST_LOCK_ASSERT();
953 
954 	switch (inm->inm_state) {
955 	case IGMP_NOT_MEMBER:
956 	case IGMP_SILENT_MEMBER:
957 		break;
958 	case IGMP_REPORTING_MEMBER:
959 		if (inm->inm_timer != 0 &&
960 		    inm->inm_timer <= timer) {
961 			CTR1(KTR_IGMPV3, "%s: REPORTING and timer running, "
962 			    "skipping.", __func__);
963 			break;
964 		}
965 		/* FALLTHROUGH */
966 	case IGMP_SG_QUERY_PENDING_MEMBER:
967 	case IGMP_G_QUERY_PENDING_MEMBER:
968 	case IGMP_IDLE_MEMBER:
969 	case IGMP_LAZY_MEMBER:
970 	case IGMP_AWAKENING_MEMBER:
971 		CTR1(KTR_IGMPV3, "%s: ->REPORTING", __func__);
972 		inm->inm_state = IGMP_REPORTING_MEMBER;
973 		inm->inm_timer = IGMP_RANDOM_DELAY(timer);
974 		V_current_state_timers_running = 1;
975 		break;
976 	case IGMP_SLEEPING_MEMBER:
977 		CTR1(KTR_IGMPV3, "%s: ->AWAKENING", __func__);
978 		inm->inm_state = IGMP_AWAKENING_MEMBER;
979 		break;
980 	case IGMP_LEAVING_MEMBER:
981 		break;
982 	}
983 }
984 
985 /*
986  * Process a received IGMPv3 general, group-specific or
987  * group-and-source-specific query.
988  * Assumes m has already been pulled up to the full IGMP message length.
989  * Return 0 if successful, otherwise an appropriate error code is returned.
990  */
991 static int
992 igmp_input_v3_query(struct ifnet *ifp, const struct ip *ip,
993     /*const*/ struct igmpv3 *igmpv3)
994 {
995 	struct igmp_ifsoftc	*igi;
996 	struct in_multi		*inm;
997 	int			 is_general_query;
998 	uint32_t		 maxresp, nsrc, qqi;
999 	uint16_t		 timer;
1000 	uint8_t			 qrv;
1001 
1002 	is_general_query = 0;
1003 
1004 	CTR2(KTR_IGMPV3, "process v3 query on ifp %p(%s)", ifp, ifp->if_xname);
1005 
1006 	maxresp = igmpv3->igmp_code;	/* in 1/10ths of a second */
1007 	if (maxresp >= 128) {
1008 		maxresp = IGMP_MANT(igmpv3->igmp_code) <<
1009 			  (IGMP_EXP(igmpv3->igmp_code) + 3);
1010 	}
1011 
1012 	/*
1013 	 * Robustness must never be less than 2 for on-wire IGMPv3.
1014 	 * FUTURE: Check if ifp has IGIF_LOOPBACK set, as we will make
1015 	 * an exception for interfaces whose IGMPv3 state changes
1016 	 * are redirected to loopback (e.g. MANET).
1017 	 */
1018 	qrv = IGMP_QRV(igmpv3->igmp_misc);
1019 	if (qrv < 2) {
1020 		CTR3(KTR_IGMPV3, "%s: clamping qrv %d to %d", __func__,
1021 		    qrv, IGMP_RV_INIT);
1022 		qrv = IGMP_RV_INIT;
1023 	}
1024 
1025 	qqi = igmpv3->igmp_qqi;
1026 	if (qqi >= 128) {
1027 		qqi = IGMP_MANT(igmpv3->igmp_qqi) <<
1028 		     (IGMP_EXP(igmpv3->igmp_qqi) + 3);
1029 	}
1030 
1031 	timer = maxresp * PR_FASTHZ / IGMP_TIMER_SCALE;
1032 	if (timer == 0)
1033 		timer = 1;
1034 
1035 	nsrc = ntohs(igmpv3->igmp_numsrc);
1036 
1037 	/*
1038 	 * Validate address fields and versions upfront before
1039 	 * accepting v3 query.
1040 	 * XXX SMPng: Unlocked access to igmpstat counters here.
1041 	 */
1042 	if (in_nullhost(igmpv3->igmp_group)) {
1043 		/*
1044 		 * IGMPv3 General Query.
1045 		 *
1046 		 * General Queries SHOULD be directed to 224.0.0.1.
1047 		 * A general query with a source list has undefined
1048 		 * behaviour; discard it.
1049 		 */
1050 		IGMPSTAT_INC(igps_rcv_gen_queries);
1051 		if (!in_allhosts(ip->ip_dst) || nsrc > 0) {
1052 			IGMPSTAT_INC(igps_rcv_badqueries);
1053 			return (0);
1054 		}
1055 		is_general_query = 1;
1056 	} else {
1057 		/* Group or group-source specific query. */
1058 		if (nsrc == 0)
1059 			IGMPSTAT_INC(igps_rcv_group_queries);
1060 		else
1061 			IGMPSTAT_INC(igps_rcv_gsr_queries);
1062 	}
1063 
1064 	IN_MULTI_LIST_LOCK();
1065 	IGMP_LOCK();
1066 
1067 	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
1068 	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
1069 
1070 	if (igi->igi_flags & IGIF_LOOPBACK) {
1071 		CTR2(KTR_IGMPV3, "ignore v3 query on IGIF_LOOPBACK ifp %p(%s)",
1072 		    ifp, ifp->if_xname);
1073 		goto out_locked;
1074 	}
1075 
1076 	/*
1077 	 * Discard the v3 query if we're in Compatibility Mode.
1078 	 * The RFC is not obviously worded that hosts need to stay in
1079 	 * compatibility mode until the Old Version Querier Present
1080 	 * timer expires.
1081 	 */
1082 	if (igi->igi_version != IGMP_VERSION_3) {
1083 		CTR3(KTR_IGMPV3, "ignore v3 query in v%d mode on ifp %p(%s)",
1084 		    igi->igi_version, ifp, ifp->if_xname);
1085 		goto out_locked;
1086 	}
1087 
1088 	igmp_set_version(igi, IGMP_VERSION_3);
1089 	igi->igi_rv = qrv;
1090 	igi->igi_qi = qqi;
1091 	igi->igi_qri = maxresp;
1092 
1093 	CTR4(KTR_IGMPV3, "%s: qrv %d qi %d qri %d", __func__, qrv, qqi,
1094 	    maxresp);
1095 
1096 	if (is_general_query) {
1097 		/*
1098 		 * Schedule a current-state report on this ifp for
1099 		 * all groups, possibly containing source lists.
1100 		 * If there is a pending General Query response
1101 		 * scheduled earlier than the selected delay, do
1102 		 * not schedule any other reports.
1103 		 * Otherwise, reset the interface timer.
1104 		 */
1105 		CTR2(KTR_IGMPV3, "process v3 general query on ifp %p(%s)",
1106 		    ifp, ifp->if_xname);
1107 		if (igi->igi_v3_timer == 0 || igi->igi_v3_timer >= timer) {
1108 			igi->igi_v3_timer = IGMP_RANDOM_DELAY(timer);
1109 			V_interface_timers_running = 1;
1110 		}
1111 	} else {
1112 		/*
1113 		 * Group-source-specific queries are throttled on
1114 		 * a per-group basis to defeat denial-of-service attempts.
1115 		 * Queries for groups we are not a member of on this
1116 		 * link are simply ignored.
1117 		 */
1118 		inm = inm_lookup(ifp, igmpv3->igmp_group);
1119 		if (inm == NULL)
1120 			goto out_locked;
1121 		if (nsrc > 0) {
1122 			if (!ratecheck(&inm->inm_lastgsrtv,
1123 			    &V_igmp_gsrdelay)) {
1124 				CTR1(KTR_IGMPV3, "%s: GS query throttled.",
1125 				    __func__);
1126 				IGMPSTAT_INC(igps_drop_gsr_queries);
1127 				goto out_locked;
1128 			}
1129 		}
1130 		CTR3(KTR_IGMPV3, "process v3 0x%08x query on ifp %p(%s)",
1131 		     ntohl(igmpv3->igmp_group.s_addr), ifp, ifp->if_xname);
1132 		/*
1133 		 * If there is a pending General Query response
1134 		 * scheduled sooner than the selected delay, no
1135 		 * further report need be scheduled.
1136 		 * Otherwise, prepare to respond to the
1137 		 * group-specific or group-and-source query.
1138 		 */
1139 		if (igi->igi_v3_timer == 0 || igi->igi_v3_timer >= timer)
1140 			igmp_input_v3_group_query(inm, igi, timer, igmpv3);
1141 	}
1142 
1143 out_locked:
1144 	IGMP_UNLOCK();
1145 	IN_MULTI_LIST_UNLOCK();
1146 
1147 	return (0);
1148 }
1149 
1150 /*
1151  * Process a received IGMPv3 group-specific or group-and-source-specific
1152  * query.
1153  * Return <0 if any error occurred. Currently this is ignored.
1154  */
1155 static int
1156 igmp_input_v3_group_query(struct in_multi *inm, struct igmp_ifsoftc *igi,
1157     int timer, /*const*/ struct igmpv3 *igmpv3)
1158 {
1159 	int			 retval;
1160 	uint16_t		 nsrc;
1161 
1162 	IN_MULTI_LIST_LOCK_ASSERT();
1163 	IGMP_LOCK_ASSERT();
1164 
1165 	retval = 0;
1166 
1167 	switch (inm->inm_state) {
1168 	case IGMP_NOT_MEMBER:
1169 	case IGMP_SILENT_MEMBER:
1170 	case IGMP_SLEEPING_MEMBER:
1171 	case IGMP_LAZY_MEMBER:
1172 	case IGMP_AWAKENING_MEMBER:
1173 	case IGMP_IDLE_MEMBER:
1174 	case IGMP_LEAVING_MEMBER:
1175 		return (retval);
1176 		break;
1177 	case IGMP_REPORTING_MEMBER:
1178 	case IGMP_G_QUERY_PENDING_MEMBER:
1179 	case IGMP_SG_QUERY_PENDING_MEMBER:
1180 		break;
1181 	}
1182 
1183 	nsrc = ntohs(igmpv3->igmp_numsrc);
1184 
1185 	/*
1186 	 * Deal with group-specific queries upfront.
1187 	 * If any group query is already pending, purge any recorded
1188 	 * source-list state if it exists, and schedule a query response
1189 	 * for this group-specific query.
1190 	 */
1191 	if (nsrc == 0) {
1192 		if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER ||
1193 		    inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER) {
1194 			inm_clear_recorded(inm);
1195 			timer = min(inm->inm_timer, timer);
1196 		}
1197 		inm->inm_state = IGMP_G_QUERY_PENDING_MEMBER;
1198 		inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1199 		V_current_state_timers_running = 1;
1200 		return (retval);
1201 	}
1202 
1203 	/*
1204 	 * Deal with the case where a group-and-source-specific query has
1205 	 * been received but a group-specific query is already pending.
1206 	 */
1207 	if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER) {
1208 		timer = min(inm->inm_timer, timer);
1209 		inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1210 		V_current_state_timers_running = 1;
1211 		return (retval);
1212 	}
1213 
1214 	/*
1215 	 * Finally, deal with the case where a group-and-source-specific
1216 	 * query has been received, where a response to a previous g-s-r
1217 	 * query exists, or none exists.
1218 	 * In this case, we need to parse the source-list which the Querier
1219 	 * has provided us with and check if we have any source list filter
1220 	 * entries at T1 for these sources. If we do not, there is no need
1221 	 * schedule a report and the query may be dropped.
1222 	 * If we do, we must record them and schedule a current-state
1223 	 * report for those sources.
1224 	 * FIXME: Handling source lists larger than 1 mbuf requires that
1225 	 * we pass the mbuf chain pointer down to this function, and use
1226 	 * m_getptr() to walk the chain.
1227 	 */
1228 	if (inm->inm_nsrc > 0) {
1229 		const struct in_addr	*ap;
1230 		int			 i, nrecorded;
1231 
1232 		ap = (const struct in_addr *)(igmpv3 + 1);
1233 		nrecorded = 0;
1234 		for (i = 0; i < nsrc; i++, ap++) {
1235 			retval = inm_record_source(inm, ap->s_addr);
1236 			if (retval < 0)
1237 				break;
1238 			nrecorded += retval;
1239 		}
1240 		if (nrecorded > 0) {
1241 			CTR1(KTR_IGMPV3,
1242 			    "%s: schedule response to SG query", __func__);
1243 			inm->inm_state = IGMP_SG_QUERY_PENDING_MEMBER;
1244 			inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1245 			V_current_state_timers_running = 1;
1246 		}
1247 	}
1248 
1249 	return (retval);
1250 }
1251 
1252 /*
1253  * Process a received IGMPv1 host membership report.
1254  *
1255  * NOTE: 0.0.0.0 workaround breaks const correctness.
1256  */
1257 static int
1258 igmp_input_v1_report(struct ifnet *ifp, /*const*/ struct ip *ip,
1259     /*const*/ struct igmp *igmp)
1260 {
1261 	struct in_ifaddr *ia;
1262 	struct in_multi *inm;
1263 
1264 	IGMPSTAT_INC(igps_rcv_reports);
1265 
1266 	if (ifp->if_flags & IFF_LOOPBACK)
1267 		return (0);
1268 
1269 	if (!IN_MULTICAST(ntohl(igmp->igmp_group.s_addr)) ||
1270 	    !in_hosteq(igmp->igmp_group, ip->ip_dst)) {
1271 		IGMPSTAT_INC(igps_rcv_badreports);
1272 		return (EINVAL);
1273 	}
1274 
1275 	/*
1276 	 * RFC 3376, Section 4.2.13, 9.2, 9.3:
1277 	 * Booting clients may use the source address 0.0.0.0. Some
1278 	 * IGMP daemons may not know how to use IP_RECVIF to determine
1279 	 * the interface upon which this message was received.
1280 	 * Replace 0.0.0.0 with the subnet address if told to do so.
1281 	 */
1282 	if (V_igmp_recvifkludge && in_nullhost(ip->ip_src)) {
1283 		IFP_TO_IA(ifp, ia);
1284 		if (ia != NULL)
1285 			ip->ip_src.s_addr = htonl(ia->ia_subnet);
1286 	}
1287 
1288 	CTR3(KTR_IGMPV3, "process v1 report 0x%08x on ifp %p(%s)",
1289 	     ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1290 
1291 	/*
1292 	 * IGMPv1 report suppression.
1293 	 * If we are a member of this group, and our membership should be
1294 	 * reported, stop our group timer and transition to the 'lazy' state.
1295 	 */
1296 	IN_MULTI_LIST_LOCK();
1297 	inm = inm_lookup(ifp, igmp->igmp_group);
1298 	if (inm != NULL) {
1299 		struct igmp_ifsoftc *igi;
1300 
1301 		igi = inm->inm_igi;
1302 		if (igi == NULL) {
1303 			KASSERT(igi != NULL,
1304 			    ("%s: no igi for ifp %p", __func__, ifp));
1305 			goto out_locked;
1306 		}
1307 
1308 		IGMPSTAT_INC(igps_rcv_ourreports);
1309 
1310 		/*
1311 		 * If we are in IGMPv3 host mode, do not allow the
1312 		 * other host's IGMPv1 report to suppress our reports
1313 		 * unless explicitly configured to do so.
1314 		 */
1315 		if (igi->igi_version == IGMP_VERSION_3) {
1316 			if (V_igmp_legacysupp)
1317 				igmp_v3_suppress_group_record(inm);
1318 			goto out_locked;
1319 		}
1320 
1321 		inm->inm_timer = 0;
1322 
1323 		switch (inm->inm_state) {
1324 		case IGMP_NOT_MEMBER:
1325 		case IGMP_SILENT_MEMBER:
1326 			break;
1327 		case IGMP_IDLE_MEMBER:
1328 		case IGMP_LAZY_MEMBER:
1329 		case IGMP_AWAKENING_MEMBER:
1330 			CTR3(KTR_IGMPV3,
1331 			    "report suppressed for 0x%08x on ifp %p(%s)",
1332 			    ntohl(igmp->igmp_group.s_addr), ifp,
1333 			    ifp->if_xname);
1334 		case IGMP_SLEEPING_MEMBER:
1335 			inm->inm_state = IGMP_SLEEPING_MEMBER;
1336 			break;
1337 		case IGMP_REPORTING_MEMBER:
1338 			CTR3(KTR_IGMPV3,
1339 			    "report suppressed for 0x%08x on ifp %p(%s)",
1340 			    ntohl(igmp->igmp_group.s_addr), ifp,
1341 			    ifp->if_xname);
1342 			if (igi->igi_version == IGMP_VERSION_1)
1343 				inm->inm_state = IGMP_LAZY_MEMBER;
1344 			else if (igi->igi_version == IGMP_VERSION_2)
1345 				inm->inm_state = IGMP_SLEEPING_MEMBER;
1346 			break;
1347 		case IGMP_G_QUERY_PENDING_MEMBER:
1348 		case IGMP_SG_QUERY_PENDING_MEMBER:
1349 		case IGMP_LEAVING_MEMBER:
1350 			break;
1351 		}
1352 	}
1353 
1354 out_locked:
1355 	IN_MULTI_LIST_UNLOCK();
1356 
1357 	return (0);
1358 }
1359 
1360 /*
1361  * Process a received IGMPv2 host membership report.
1362  *
1363  * NOTE: 0.0.0.0 workaround breaks const correctness.
1364  */
1365 static int
1366 igmp_input_v2_report(struct ifnet *ifp, /*const*/ struct ip *ip,
1367     /*const*/ struct igmp *igmp)
1368 {
1369 	struct in_ifaddr *ia;
1370 	struct in_multi *inm;
1371 
1372 	/*
1373 	 * Make sure we don't hear our own membership report.  Fast
1374 	 * leave requires knowing that we are the only member of a
1375 	 * group.
1376 	 */
1377 	IFP_TO_IA(ifp, ia);
1378 	if (ia != NULL && in_hosteq(ip->ip_src, IA_SIN(ia)->sin_addr)) {
1379 		return (0);
1380 	}
1381 
1382 	IGMPSTAT_INC(igps_rcv_reports);
1383 
1384 	if (ifp->if_flags & IFF_LOOPBACK) {
1385 		return (0);
1386 	}
1387 
1388 	if (!IN_MULTICAST(ntohl(igmp->igmp_group.s_addr)) ||
1389 	    !in_hosteq(igmp->igmp_group, ip->ip_dst)) {
1390 		IGMPSTAT_INC(igps_rcv_badreports);
1391 		return (EINVAL);
1392 	}
1393 
1394 	/*
1395 	 * RFC 3376, Section 4.2.13, 9.2, 9.3:
1396 	 * Booting clients may use the source address 0.0.0.0. Some
1397 	 * IGMP daemons may not know how to use IP_RECVIF to determine
1398 	 * the interface upon which this message was received.
1399 	 * Replace 0.0.0.0 with the subnet address if told to do so.
1400 	 */
1401 	if (V_igmp_recvifkludge && in_nullhost(ip->ip_src)) {
1402 		if (ia != NULL)
1403 			ip->ip_src.s_addr = htonl(ia->ia_subnet);
1404 	}
1405 
1406 	CTR3(KTR_IGMPV3, "process v2 report 0x%08x on ifp %p(%s)",
1407 	     ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1408 
1409 	/*
1410 	 * IGMPv2 report suppression.
1411 	 * If we are a member of this group, and our membership should be
1412 	 * reported, and our group timer is pending or about to be reset,
1413 	 * stop our group timer by transitioning to the 'lazy' state.
1414 	 */
1415 	IN_MULTI_LIST_LOCK();
1416 	inm = inm_lookup(ifp, igmp->igmp_group);
1417 	if (inm != NULL) {
1418 		struct igmp_ifsoftc *igi;
1419 
1420 		igi = inm->inm_igi;
1421 		KASSERT(igi != NULL, ("%s: no igi for ifp %p", __func__, ifp));
1422 
1423 		IGMPSTAT_INC(igps_rcv_ourreports);
1424 
1425 		/*
1426 		 * If we are in IGMPv3 host mode, do not allow the
1427 		 * other host's IGMPv1 report to suppress our reports
1428 		 * unless explicitly configured to do so.
1429 		 */
1430 		if (igi->igi_version == IGMP_VERSION_3) {
1431 			if (V_igmp_legacysupp)
1432 				igmp_v3_suppress_group_record(inm);
1433 			goto out_locked;
1434 		}
1435 
1436 		inm->inm_timer = 0;
1437 
1438 		switch (inm->inm_state) {
1439 		case IGMP_NOT_MEMBER:
1440 		case IGMP_SILENT_MEMBER:
1441 		case IGMP_SLEEPING_MEMBER:
1442 			break;
1443 		case IGMP_REPORTING_MEMBER:
1444 		case IGMP_IDLE_MEMBER:
1445 		case IGMP_AWAKENING_MEMBER:
1446 			CTR3(KTR_IGMPV3,
1447 			    "report suppressed for 0x%08x on ifp %p(%s)",
1448 			    ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1449 		case IGMP_LAZY_MEMBER:
1450 			inm->inm_state = IGMP_LAZY_MEMBER;
1451 			break;
1452 		case IGMP_G_QUERY_PENDING_MEMBER:
1453 		case IGMP_SG_QUERY_PENDING_MEMBER:
1454 		case IGMP_LEAVING_MEMBER:
1455 			break;
1456 		}
1457 	}
1458 
1459 out_locked:
1460 	IN_MULTI_LIST_UNLOCK();
1461 
1462 	return (0);
1463 }
1464 
1465 int
1466 igmp_input(struct mbuf **mp, int *offp, int proto)
1467 {
1468 	int iphlen;
1469 	struct ifnet *ifp;
1470 	struct igmp *igmp;
1471 	struct ip *ip;
1472 	struct mbuf *m;
1473 	int igmplen;
1474 	int minlen;
1475 	int queryver;
1476 
1477 	CTR3(KTR_IGMPV3, "%s: called w/mbuf (%p,%d)", __func__, *mp, *offp);
1478 
1479 	m = *mp;
1480 	ifp = m->m_pkthdr.rcvif;
1481 	*mp = NULL;
1482 
1483 	IGMPSTAT_INC(igps_rcv_total);
1484 
1485 	ip = mtod(m, struct ip *);
1486 	iphlen = *offp;
1487 	igmplen = ntohs(ip->ip_len) - iphlen;
1488 
1489 	/*
1490 	 * Validate lengths.
1491 	 */
1492 	if (igmplen < IGMP_MINLEN) {
1493 		IGMPSTAT_INC(igps_rcv_tooshort);
1494 		m_freem(m);
1495 		return (IPPROTO_DONE);
1496 	}
1497 
1498 	/*
1499 	 * Always pullup to the minimum size for v1/v2 or v3
1500 	 * to amortize calls to m_pullup().
1501 	 */
1502 	minlen = iphlen;
1503 	if (igmplen >= IGMP_V3_QUERY_MINLEN)
1504 		minlen += IGMP_V3_QUERY_MINLEN;
1505 	else
1506 		minlen += IGMP_MINLEN;
1507 	if ((!M_WRITABLE(m) || m->m_len < minlen) &&
1508 	    (m = m_pullup(m, minlen)) == NULL) {
1509 		IGMPSTAT_INC(igps_rcv_tooshort);
1510 		return (IPPROTO_DONE);
1511 	}
1512 	ip = mtod(m, struct ip *);
1513 
1514 	/*
1515 	 * Validate checksum.
1516 	 */
1517 	m->m_data += iphlen;
1518 	m->m_len -= iphlen;
1519 	igmp = mtod(m, struct igmp *);
1520 	if (in_cksum(m, igmplen)) {
1521 		IGMPSTAT_INC(igps_rcv_badsum);
1522 		m_freem(m);
1523 		return (IPPROTO_DONE);
1524 	}
1525 	m->m_data -= iphlen;
1526 	m->m_len += iphlen;
1527 
1528 	/*
1529 	 * IGMP control traffic is link-scope, and must have a TTL of 1.
1530 	 * DVMRP traffic (e.g. mrinfo, mtrace) is an exception;
1531 	 * probe packets may come from beyond the LAN.
1532 	 */
1533 	if (igmp->igmp_type != IGMP_DVMRP && ip->ip_ttl != 1) {
1534 		IGMPSTAT_INC(igps_rcv_badttl);
1535 		m_freem(m);
1536 		return (IPPROTO_DONE);
1537 	}
1538 
1539 	switch (igmp->igmp_type) {
1540 	case IGMP_HOST_MEMBERSHIP_QUERY:
1541 		if (igmplen == IGMP_MINLEN) {
1542 			if (igmp->igmp_code == 0)
1543 				queryver = IGMP_VERSION_1;
1544 			else
1545 				queryver = IGMP_VERSION_2;
1546 		} else if (igmplen >= IGMP_V3_QUERY_MINLEN) {
1547 			queryver = IGMP_VERSION_3;
1548 		} else {
1549 			IGMPSTAT_INC(igps_rcv_tooshort);
1550 			m_freem(m);
1551 			return (IPPROTO_DONE);
1552 		}
1553 
1554 		switch (queryver) {
1555 		case IGMP_VERSION_1:
1556 			IGMPSTAT_INC(igps_rcv_v1v2_queries);
1557 			if (!V_igmp_v1enable)
1558 				break;
1559 			if (igmp_input_v1_query(ifp, ip, igmp) != 0) {
1560 				m_freem(m);
1561 				return (IPPROTO_DONE);
1562 			}
1563 			break;
1564 
1565 		case IGMP_VERSION_2:
1566 			IGMPSTAT_INC(igps_rcv_v1v2_queries);
1567 			if (!V_igmp_v2enable)
1568 				break;
1569 			if (igmp_input_v2_query(ifp, ip, igmp) != 0) {
1570 				m_freem(m);
1571 				return (IPPROTO_DONE);
1572 			}
1573 			break;
1574 
1575 		case IGMP_VERSION_3: {
1576 				struct igmpv3 *igmpv3;
1577 				uint16_t igmpv3len;
1578 				uint16_t nsrc;
1579 
1580 				IGMPSTAT_INC(igps_rcv_v3_queries);
1581 				igmpv3 = (struct igmpv3 *)igmp;
1582 				/*
1583 				 * Validate length based on source count.
1584 				 */
1585 				nsrc = ntohs(igmpv3->igmp_numsrc);
1586 				if (nsrc * sizeof(in_addr_t) >
1587 				    UINT16_MAX - iphlen - IGMP_V3_QUERY_MINLEN) {
1588 					IGMPSTAT_INC(igps_rcv_tooshort);
1589 					m_freem(m);
1590 					return (IPPROTO_DONE);
1591 				}
1592 				/*
1593 				 * m_pullup() may modify m, so pullup in
1594 				 * this scope.
1595 				 */
1596 				igmpv3len = iphlen + IGMP_V3_QUERY_MINLEN +
1597 				   sizeof(struct in_addr) * nsrc;
1598 				if ((!M_WRITABLE(m) ||
1599 				     m->m_len < igmpv3len) &&
1600 				    (m = m_pullup(m, igmpv3len)) == NULL) {
1601 					IGMPSTAT_INC(igps_rcv_tooshort);
1602 					return (IPPROTO_DONE);
1603 				}
1604 				igmpv3 = (struct igmpv3 *)(mtod(m, uint8_t *)
1605 				    + iphlen);
1606 				if (igmp_input_v3_query(ifp, ip, igmpv3) != 0) {
1607 					m_freem(m);
1608 					return (IPPROTO_DONE);
1609 				}
1610 			}
1611 			break;
1612 		}
1613 		break;
1614 
1615 	case IGMP_v1_HOST_MEMBERSHIP_REPORT:
1616 		if (!V_igmp_v1enable)
1617 			break;
1618 		if (igmp_input_v1_report(ifp, ip, igmp) != 0) {
1619 			m_freem(m);
1620 			return (IPPROTO_DONE);
1621 		}
1622 		break;
1623 
1624 	case IGMP_v2_HOST_MEMBERSHIP_REPORT:
1625 		if (!V_igmp_v2enable)
1626 			break;
1627 		if (!ip_checkrouteralert(m))
1628 			IGMPSTAT_INC(igps_rcv_nora);
1629 		if (igmp_input_v2_report(ifp, ip, igmp) != 0) {
1630 			m_freem(m);
1631 			return (IPPROTO_DONE);
1632 		}
1633 		break;
1634 
1635 	case IGMP_v3_HOST_MEMBERSHIP_REPORT:
1636 		/*
1637 		 * Hosts do not need to process IGMPv3 membership reports,
1638 		 * as report suppression is no longer required.
1639 		 */
1640 		if (!ip_checkrouteralert(m))
1641 			IGMPSTAT_INC(igps_rcv_nora);
1642 		break;
1643 
1644 	default:
1645 		break;
1646 	}
1647 
1648 	/*
1649 	 * Pass all valid IGMP packets up to any process(es) listening on a
1650 	 * raw IGMP socket.
1651 	 */
1652 	*mp = m;
1653 	return (rip_input(mp, offp, proto));
1654 }
1655 
1656 /*
1657  * Fast timeout handler (global).
1658  * VIMAGE: Timeout handlers are expected to service all vimages.
1659  */
1660 void
1661 igmp_fasttimo(void)
1662 {
1663 	VNET_ITERATOR_DECL(vnet_iter);
1664 
1665 	VNET_LIST_RLOCK_NOSLEEP();
1666 	VNET_FOREACH(vnet_iter) {
1667 		CURVNET_SET(vnet_iter);
1668 		igmp_fasttimo_vnet();
1669 		CURVNET_RESTORE();
1670 	}
1671 	VNET_LIST_RUNLOCK_NOSLEEP();
1672 }
1673 
1674 /*
1675  * Fast timeout handler (per-vnet).
1676  * Sends are shuffled off to a netisr to deal with Giant.
1677  *
1678  * VIMAGE: Assume caller has set up our curvnet.
1679  */
1680 static void
1681 igmp_fasttimo_vnet(void)
1682 {
1683 	struct mbufq		 scq;	/* State-change packets */
1684 	struct mbufq		 qrq;	/* Query response packets */
1685 	struct ifnet		*ifp;
1686 	struct igmp_ifsoftc	*igi;
1687 	struct ifmultiaddr	*ifma, *next;
1688 	struct in_multi		*inm;
1689 	struct in_multi_head inm_free_tmp;
1690 	int			 loop, uri_fasthz;
1691 
1692 	loop = 0;
1693 	uri_fasthz = 0;
1694 
1695 	/*
1696 	 * Quick check to see if any work needs to be done, in order to
1697 	 * minimize the overhead of fasttimo processing.
1698 	 * SMPng: XXX Unlocked reads.
1699 	 */
1700 	if (!V_current_state_timers_running &&
1701 	    !V_interface_timers_running &&
1702 	    !V_state_change_timers_running)
1703 		return;
1704 
1705 	SLIST_INIT(&inm_free_tmp);
1706 	IN_MULTI_LIST_LOCK();
1707 	IGMP_LOCK();
1708 
1709 	/*
1710 	 * IGMPv3 General Query response timer processing.
1711 	 */
1712 	if (V_interface_timers_running) {
1713 		CTR1(KTR_IGMPV3, "%s: interface timers running", __func__);
1714 
1715 		V_interface_timers_running = 0;
1716 		LIST_FOREACH(igi, &V_igi_head, igi_link) {
1717 			if (igi->igi_v3_timer == 0) {
1718 				/* Do nothing. */
1719 			} else if (--igi->igi_v3_timer == 0) {
1720 				igmp_v3_dispatch_general_query(igi);
1721 			} else {
1722 				V_interface_timers_running = 1;
1723 			}
1724 		}
1725 	}
1726 
1727 	if (!V_current_state_timers_running &&
1728 	    !V_state_change_timers_running)
1729 		goto out_locked;
1730 
1731 	V_current_state_timers_running = 0;
1732 	V_state_change_timers_running = 0;
1733 
1734 	CTR1(KTR_IGMPV3, "%s: state change timers running", __func__);
1735 
1736 	/*
1737 	 * IGMPv1/v2/v3 host report and state-change timer processing.
1738 	 * Note: Processing a v3 group timer may remove a node.
1739 	 */
1740 	LIST_FOREACH(igi, &V_igi_head, igi_link) {
1741 		ifp = igi->igi_ifp;
1742 
1743 		if (igi->igi_version == IGMP_VERSION_3) {
1744 			loop = (igi->igi_flags & IGIF_LOOPBACK) ? 1 : 0;
1745 			uri_fasthz = IGMP_RANDOM_DELAY(igi->igi_uri *
1746 			    PR_FASTHZ);
1747 			mbufq_init(&qrq, IGMP_MAX_G_GS_PACKETS);
1748 			mbufq_init(&scq, IGMP_MAX_STATE_CHANGE_PACKETS);
1749 		}
1750 
1751 		IF_ADDR_WLOCK(ifp);
1752 	restart:
1753 		CK_STAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next) {
1754 			if (ifma->ifma_addr->sa_family != AF_INET ||
1755 			    ifma->ifma_protospec == NULL)
1756 				continue;
1757 			inm = (struct in_multi *)ifma->ifma_protospec;
1758 			switch (igi->igi_version) {
1759 			case IGMP_VERSION_1:
1760 			case IGMP_VERSION_2:
1761 				igmp_v1v2_process_group_timer(inm,
1762 				    igi->igi_version);
1763 				break;
1764 			case IGMP_VERSION_3:
1765 				igmp_v3_process_group_timers(&inm_free_tmp, &qrq,
1766 				    &scq, inm, uri_fasthz);
1767 				break;
1768 			}
1769 			if (__predict_false(ifma_restart)) {
1770 				ifma_restart = false;
1771 				goto restart;
1772 			}
1773 		}
1774 		IF_ADDR_WUNLOCK(ifp);
1775 
1776 		if (igi->igi_version == IGMP_VERSION_3) {
1777 			igmp_dispatch_queue(&qrq, 0, loop);
1778 			igmp_dispatch_queue(&scq, 0, loop);
1779 
1780 			/*
1781 			 * Free the in_multi reference(s) for this
1782 			 * IGMP lifecycle.
1783 			 */
1784 			inm_release_list_deferred(&inm_free_tmp);
1785 		}
1786 	}
1787 
1788 out_locked:
1789 	IGMP_UNLOCK();
1790 	IN_MULTI_LIST_UNLOCK();
1791 }
1792 
1793 /*
1794  * Update host report group timer for IGMPv1/v2.
1795  * Will update the global pending timer flags.
1796  */
1797 static void
1798 igmp_v1v2_process_group_timer(struct in_multi *inm, const int version)
1799 {
1800 	int report_timer_expired;
1801 
1802 	IN_MULTI_LIST_LOCK_ASSERT();
1803 	IGMP_LOCK_ASSERT();
1804 
1805 	if (inm->inm_timer == 0) {
1806 		report_timer_expired = 0;
1807 	} else if (--inm->inm_timer == 0) {
1808 		report_timer_expired = 1;
1809 	} else {
1810 		V_current_state_timers_running = 1;
1811 		return;
1812 	}
1813 
1814 	switch (inm->inm_state) {
1815 	case IGMP_NOT_MEMBER:
1816 	case IGMP_SILENT_MEMBER:
1817 	case IGMP_IDLE_MEMBER:
1818 	case IGMP_LAZY_MEMBER:
1819 	case IGMP_SLEEPING_MEMBER:
1820 	case IGMP_AWAKENING_MEMBER:
1821 		break;
1822 	case IGMP_REPORTING_MEMBER:
1823 		if (report_timer_expired) {
1824 			inm->inm_state = IGMP_IDLE_MEMBER;
1825 			(void)igmp_v1v2_queue_report(inm,
1826 			    (version == IGMP_VERSION_2) ?
1827 			     IGMP_v2_HOST_MEMBERSHIP_REPORT :
1828 			     IGMP_v1_HOST_MEMBERSHIP_REPORT);
1829 		}
1830 		break;
1831 	case IGMP_G_QUERY_PENDING_MEMBER:
1832 	case IGMP_SG_QUERY_PENDING_MEMBER:
1833 	case IGMP_LEAVING_MEMBER:
1834 		break;
1835 	}
1836 }
1837 
1838 /*
1839  * Update a group's timers for IGMPv3.
1840  * Will update the global pending timer flags.
1841  * Note: Unlocked read from igi.
1842  */
1843 static void
1844 igmp_v3_process_group_timers(struct in_multi_head *inmh,
1845     struct mbufq *qrq, struct mbufq *scq,
1846     struct in_multi *inm, const int uri_fasthz)
1847 {
1848 	int query_response_timer_expired;
1849 	int state_change_retransmit_timer_expired;
1850 
1851 	IN_MULTI_LIST_LOCK_ASSERT();
1852 	IGMP_LOCK_ASSERT();
1853 
1854 	query_response_timer_expired = 0;
1855 	state_change_retransmit_timer_expired = 0;
1856 
1857 	/*
1858 	 * During a transition from v1/v2 compatibility mode back to v3,
1859 	 * a group record in REPORTING state may still have its group
1860 	 * timer active. This is a no-op in this function; it is easier
1861 	 * to deal with it here than to complicate the slow-timeout path.
1862 	 */
1863 	if (inm->inm_timer == 0) {
1864 		query_response_timer_expired = 0;
1865 	} else if (--inm->inm_timer == 0) {
1866 		query_response_timer_expired = 1;
1867 	} else {
1868 		V_current_state_timers_running = 1;
1869 	}
1870 
1871 	if (inm->inm_sctimer == 0) {
1872 		state_change_retransmit_timer_expired = 0;
1873 	} else if (--inm->inm_sctimer == 0) {
1874 		state_change_retransmit_timer_expired = 1;
1875 	} else {
1876 		V_state_change_timers_running = 1;
1877 	}
1878 
1879 	/* We are in fasttimo, so be quick about it. */
1880 	if (!state_change_retransmit_timer_expired &&
1881 	    !query_response_timer_expired)
1882 		return;
1883 
1884 	switch (inm->inm_state) {
1885 	case IGMP_NOT_MEMBER:
1886 	case IGMP_SILENT_MEMBER:
1887 	case IGMP_SLEEPING_MEMBER:
1888 	case IGMP_LAZY_MEMBER:
1889 	case IGMP_AWAKENING_MEMBER:
1890 	case IGMP_IDLE_MEMBER:
1891 		break;
1892 	case IGMP_G_QUERY_PENDING_MEMBER:
1893 	case IGMP_SG_QUERY_PENDING_MEMBER:
1894 		/*
1895 		 * Respond to a previously pending Group-Specific
1896 		 * or Group-and-Source-Specific query by enqueueing
1897 		 * the appropriate Current-State report for
1898 		 * immediate transmission.
1899 		 */
1900 		if (query_response_timer_expired) {
1901 			int retval __unused;
1902 
1903 			retval = igmp_v3_enqueue_group_record(qrq, inm, 0, 1,
1904 			    (inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER));
1905 			CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
1906 			    __func__, retval);
1907 			inm->inm_state = IGMP_REPORTING_MEMBER;
1908 			/* XXX Clear recorded sources for next time. */
1909 			inm_clear_recorded(inm);
1910 		}
1911 		/* FALLTHROUGH */
1912 	case IGMP_REPORTING_MEMBER:
1913 	case IGMP_LEAVING_MEMBER:
1914 		if (state_change_retransmit_timer_expired) {
1915 			/*
1916 			 * State-change retransmission timer fired.
1917 			 * If there are any further pending retransmissions,
1918 			 * set the global pending state-change flag, and
1919 			 * reset the timer.
1920 			 */
1921 			if (--inm->inm_scrv > 0) {
1922 				inm->inm_sctimer = uri_fasthz;
1923 				V_state_change_timers_running = 1;
1924 			}
1925 			/*
1926 			 * Retransmit the previously computed state-change
1927 			 * report. If there are no further pending
1928 			 * retransmissions, the mbuf queue will be consumed.
1929 			 * Update T0 state to T1 as we have now sent
1930 			 * a state-change.
1931 			 */
1932 			(void)igmp_v3_merge_state_changes(inm, scq);
1933 
1934 			inm_commit(inm);
1935 			CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
1936 			    ntohl(inm->inm_addr.s_addr),
1937 			    inm->inm_ifp->if_xname);
1938 
1939 			/*
1940 			 * If we are leaving the group for good, make sure
1941 			 * we release IGMP's reference to it.
1942 			 * This release must be deferred using a SLIST,
1943 			 * as we are called from a loop which traverses
1944 			 * the in_ifmultiaddr TAILQ.
1945 			 */
1946 			if (inm->inm_state == IGMP_LEAVING_MEMBER &&
1947 			    inm->inm_scrv == 0) {
1948 				inm->inm_state = IGMP_NOT_MEMBER;
1949 				inm_rele_locked(inmh, inm);
1950 			}
1951 		}
1952 		break;
1953 	}
1954 }
1955 
1956 /*
1957  * Suppress a group's pending response to a group or source/group query.
1958  *
1959  * Do NOT suppress state changes. This leads to IGMPv3 inconsistency.
1960  * Do NOT update ST1/ST0 as this operation merely suppresses
1961  * the currently pending group record.
1962  * Do NOT suppress the response to a general query. It is possible but
1963  * it would require adding another state or flag.
1964  */
1965 static void
1966 igmp_v3_suppress_group_record(struct in_multi *inm)
1967 {
1968 
1969 	IN_MULTI_LIST_LOCK_ASSERT();
1970 
1971 	KASSERT(inm->inm_igi->igi_version == IGMP_VERSION_3,
1972 		("%s: not IGMPv3 mode on link", __func__));
1973 
1974 	if (inm->inm_state != IGMP_G_QUERY_PENDING_MEMBER ||
1975 	    inm->inm_state != IGMP_SG_QUERY_PENDING_MEMBER)
1976 		return;
1977 
1978 	if (inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER)
1979 		inm_clear_recorded(inm);
1980 
1981 	inm->inm_timer = 0;
1982 	inm->inm_state = IGMP_REPORTING_MEMBER;
1983 }
1984 
1985 /*
1986  * Switch to a different IGMP version on the given interface,
1987  * as per Section 7.2.1.
1988  */
1989 static void
1990 igmp_set_version(struct igmp_ifsoftc *igi, const int version)
1991 {
1992 	int old_version_timer;
1993 
1994 	IGMP_LOCK_ASSERT();
1995 
1996 	CTR4(KTR_IGMPV3, "%s: switching to v%d on ifp %p(%s)", __func__,
1997 	    version, igi->igi_ifp, igi->igi_ifp->if_xname);
1998 
1999 	if (version == IGMP_VERSION_1 || version == IGMP_VERSION_2) {
2000 		/*
2001 		 * Compute the "Older Version Querier Present" timer as per
2002 		 * Section 8.12.
2003 		 */
2004 		old_version_timer = igi->igi_rv * igi->igi_qi + igi->igi_qri;
2005 		old_version_timer *= PR_SLOWHZ;
2006 
2007 		if (version == IGMP_VERSION_1) {
2008 			igi->igi_v1_timer = old_version_timer;
2009 			igi->igi_v2_timer = 0;
2010 		} else if (version == IGMP_VERSION_2) {
2011 			igi->igi_v1_timer = 0;
2012 			igi->igi_v2_timer = old_version_timer;
2013 		}
2014 	}
2015 
2016 	if (igi->igi_v1_timer == 0 && igi->igi_v2_timer > 0) {
2017 		if (igi->igi_version != IGMP_VERSION_2) {
2018 			igi->igi_version = IGMP_VERSION_2;
2019 			igmp_v3_cancel_link_timers(igi);
2020 		}
2021 	} else if (igi->igi_v1_timer > 0) {
2022 		if (igi->igi_version != IGMP_VERSION_1) {
2023 			igi->igi_version = IGMP_VERSION_1;
2024 			igmp_v3_cancel_link_timers(igi);
2025 		}
2026 	}
2027 }
2028 
2029 /*
2030  * Cancel pending IGMPv3 timers for the given link and all groups
2031  * joined on it; state-change, general-query, and group-query timers.
2032  *
2033  * Only ever called on a transition from v3 to Compatibility mode. Kill
2034  * the timers stone dead (this may be expensive for large N groups), they
2035  * will be restarted if Compatibility Mode deems that they must be due to
2036  * query processing.
2037  */
2038 static void
2039 igmp_v3_cancel_link_timers(struct igmp_ifsoftc *igi)
2040 {
2041 	struct ifmultiaddr	*ifma, *ifmatmp;
2042 	struct ifnet		*ifp;
2043 	struct in_multi		*inm;
2044 	struct in_multi_head inm_free_tmp;
2045 
2046 	CTR3(KTR_IGMPV3, "%s: cancel v3 timers on ifp %p(%s)", __func__,
2047 	    igi->igi_ifp, igi->igi_ifp->if_xname);
2048 
2049 	IN_MULTI_LIST_LOCK_ASSERT();
2050 	IGMP_LOCK_ASSERT();
2051 	NET_EPOCH_ASSERT();
2052 
2053 	SLIST_INIT(&inm_free_tmp);
2054 
2055 	/*
2056 	 * Stop the v3 General Query Response on this link stone dead.
2057 	 * If fasttimo is woken up due to V_interface_timers_running,
2058 	 * the flag will be cleared if there are no pending link timers.
2059 	 */
2060 	igi->igi_v3_timer = 0;
2061 
2062 	/*
2063 	 * Now clear the current-state and state-change report timers
2064 	 * for all memberships scoped to this link.
2065 	 */
2066 	ifp = igi->igi_ifp;
2067 	IF_ADDR_WLOCK(ifp);
2068 	CK_STAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, ifmatmp) {
2069 		if (ifma->ifma_addr->sa_family != AF_INET ||
2070 		    ifma->ifma_protospec == NULL)
2071 			continue;
2072 		inm = (struct in_multi *)ifma->ifma_protospec;
2073 		switch (inm->inm_state) {
2074 		case IGMP_NOT_MEMBER:
2075 		case IGMP_SILENT_MEMBER:
2076 		case IGMP_IDLE_MEMBER:
2077 		case IGMP_LAZY_MEMBER:
2078 		case IGMP_SLEEPING_MEMBER:
2079 		case IGMP_AWAKENING_MEMBER:
2080 			/*
2081 			 * These states are either not relevant in v3 mode,
2082 			 * or are unreported. Do nothing.
2083 			 */
2084 			break;
2085 		case IGMP_LEAVING_MEMBER:
2086 			/*
2087 			 * If we are leaving the group and switching to
2088 			 * compatibility mode, we need to release the final
2089 			 * reference held for issuing the INCLUDE {}, and
2090 			 * transition to REPORTING to ensure the host leave
2091 			 * message is sent upstream to the old querier --
2092 			 * transition to NOT would lose the leave and race.
2093 			 */
2094 			inm_rele_locked(&inm_free_tmp, inm);
2095 			/* FALLTHROUGH */
2096 		case IGMP_G_QUERY_PENDING_MEMBER:
2097 		case IGMP_SG_QUERY_PENDING_MEMBER:
2098 			inm_clear_recorded(inm);
2099 			/* FALLTHROUGH */
2100 		case IGMP_REPORTING_MEMBER:
2101 			inm->inm_state = IGMP_REPORTING_MEMBER;
2102 			break;
2103 		}
2104 		/*
2105 		 * Always clear state-change and group report timers.
2106 		 * Free any pending IGMPv3 state-change records.
2107 		 */
2108 		inm->inm_sctimer = 0;
2109 		inm->inm_timer = 0;
2110 		mbufq_drain(&inm->inm_scq);
2111 	}
2112 	IF_ADDR_WUNLOCK(ifp);
2113 
2114 	inm_release_list_deferred(&inm_free_tmp);
2115 }
2116 
2117 /*
2118  * Update the Older Version Querier Present timers for a link.
2119  * See Section 7.2.1 of RFC 3376.
2120  */
2121 static void
2122 igmp_v1v2_process_querier_timers(struct igmp_ifsoftc *igi)
2123 {
2124 
2125 	IGMP_LOCK_ASSERT();
2126 
2127 	if (igi->igi_v1_timer == 0 && igi->igi_v2_timer == 0) {
2128 		/*
2129 		 * IGMPv1 and IGMPv2 Querier Present timers expired.
2130 		 *
2131 		 * Revert to IGMPv3.
2132 		 */
2133 		if (igi->igi_version != IGMP_VERSION_3) {
2134 			CTR5(KTR_IGMPV3,
2135 			    "%s: transition from v%d -> v%d on %p(%s)",
2136 			    __func__, igi->igi_version, IGMP_VERSION_3,
2137 			    igi->igi_ifp, igi->igi_ifp->if_xname);
2138 			igi->igi_version = IGMP_VERSION_3;
2139 		}
2140 	} else if (igi->igi_v1_timer == 0 && igi->igi_v2_timer > 0) {
2141 		/*
2142 		 * IGMPv1 Querier Present timer expired,
2143 		 * IGMPv2 Querier Present timer running.
2144 		 * If IGMPv2 was disabled since last timeout,
2145 		 * revert to IGMPv3.
2146 		 * If IGMPv2 is enabled, revert to IGMPv2.
2147 		 */
2148 		if (!V_igmp_v2enable) {
2149 			CTR5(KTR_IGMPV3,
2150 			    "%s: transition from v%d -> v%d on %p(%s)",
2151 			    __func__, igi->igi_version, IGMP_VERSION_3,
2152 			    igi->igi_ifp, igi->igi_ifp->if_xname);
2153 			igi->igi_v2_timer = 0;
2154 			igi->igi_version = IGMP_VERSION_3;
2155 		} else {
2156 			--igi->igi_v2_timer;
2157 			if (igi->igi_version != IGMP_VERSION_2) {
2158 				CTR5(KTR_IGMPV3,
2159 				    "%s: transition from v%d -> v%d on %p(%s)",
2160 				    __func__, igi->igi_version, IGMP_VERSION_2,
2161 				    igi->igi_ifp, igi->igi_ifp->if_xname);
2162 				igi->igi_version = IGMP_VERSION_2;
2163 				igmp_v3_cancel_link_timers(igi);
2164 			}
2165 		}
2166 	} else if (igi->igi_v1_timer > 0) {
2167 		/*
2168 		 * IGMPv1 Querier Present timer running.
2169 		 * Stop IGMPv2 timer if running.
2170 		 *
2171 		 * If IGMPv1 was disabled since last timeout,
2172 		 * revert to IGMPv3.
2173 		 * If IGMPv1 is enabled, reset IGMPv2 timer if running.
2174 		 */
2175 		if (!V_igmp_v1enable) {
2176 			CTR5(KTR_IGMPV3,
2177 			    "%s: transition from v%d -> v%d on %p(%s)",
2178 			    __func__, igi->igi_version, IGMP_VERSION_3,
2179 			    igi->igi_ifp, igi->igi_ifp->if_xname);
2180 			igi->igi_v1_timer = 0;
2181 			igi->igi_version = IGMP_VERSION_3;
2182 		} else {
2183 			--igi->igi_v1_timer;
2184 		}
2185 		if (igi->igi_v2_timer > 0) {
2186 			CTR3(KTR_IGMPV3,
2187 			    "%s: cancel v2 timer on %p(%s)",
2188 			    __func__, igi->igi_ifp, igi->igi_ifp->if_xname);
2189 			igi->igi_v2_timer = 0;
2190 		}
2191 	}
2192 }
2193 
2194 /*
2195  * Global slowtimo handler.
2196  * VIMAGE: Timeout handlers are expected to service all vimages.
2197  */
2198 void
2199 igmp_slowtimo(void)
2200 {
2201 	VNET_ITERATOR_DECL(vnet_iter);
2202 
2203 	VNET_LIST_RLOCK_NOSLEEP();
2204 	VNET_FOREACH(vnet_iter) {
2205 		CURVNET_SET(vnet_iter);
2206 		igmp_slowtimo_vnet();
2207 		CURVNET_RESTORE();
2208 	}
2209 	VNET_LIST_RUNLOCK_NOSLEEP();
2210 }
2211 
2212 /*
2213  * Per-vnet slowtimo handler.
2214  */
2215 static void
2216 igmp_slowtimo_vnet(void)
2217 {
2218 	struct igmp_ifsoftc *igi;
2219 
2220 	IGMP_LOCK();
2221 
2222 	LIST_FOREACH(igi, &V_igi_head, igi_link) {
2223 		igmp_v1v2_process_querier_timers(igi);
2224 	}
2225 
2226 	IGMP_UNLOCK();
2227 }
2228 
2229 /*
2230  * Dispatch an IGMPv1/v2 host report or leave message.
2231  * These are always small enough to fit inside a single mbuf.
2232  */
2233 static int
2234 igmp_v1v2_queue_report(struct in_multi *inm, const int type)
2235 {
2236 	struct epoch_tracker 	et;
2237 	struct ifnet		*ifp;
2238 	struct igmp		*igmp;
2239 	struct ip		*ip;
2240 	struct mbuf		*m;
2241 
2242 	IN_MULTI_LIST_LOCK_ASSERT();
2243 	IGMP_LOCK_ASSERT();
2244 
2245 	ifp = inm->inm_ifp;
2246 
2247 	m = m_gethdr(M_NOWAIT, MT_DATA);
2248 	if (m == NULL)
2249 		return (ENOMEM);
2250 	M_ALIGN(m, sizeof(struct ip) + sizeof(struct igmp));
2251 
2252 	m->m_pkthdr.len = sizeof(struct ip) + sizeof(struct igmp);
2253 
2254 	m->m_data += sizeof(struct ip);
2255 	m->m_len = sizeof(struct igmp);
2256 
2257 	igmp = mtod(m, struct igmp *);
2258 	igmp->igmp_type = type;
2259 	igmp->igmp_code = 0;
2260 	igmp->igmp_group = inm->inm_addr;
2261 	igmp->igmp_cksum = 0;
2262 	igmp->igmp_cksum = in_cksum(m, sizeof(struct igmp));
2263 
2264 	m->m_data -= sizeof(struct ip);
2265 	m->m_len += sizeof(struct ip);
2266 
2267 	ip = mtod(m, struct ip *);
2268 	ip->ip_tos = 0;
2269 	ip->ip_len = htons(sizeof(struct ip) + sizeof(struct igmp));
2270 	ip->ip_off = 0;
2271 	ip->ip_p = IPPROTO_IGMP;
2272 	ip->ip_src.s_addr = INADDR_ANY;
2273 
2274 	if (type == IGMP_HOST_LEAVE_MESSAGE)
2275 		ip->ip_dst.s_addr = htonl(INADDR_ALLRTRS_GROUP);
2276 	else
2277 		ip->ip_dst = inm->inm_addr;
2278 
2279 	igmp_save_context(m, ifp);
2280 
2281 	m->m_flags |= M_IGMPV2;
2282 	if (inm->inm_igi->igi_flags & IGIF_LOOPBACK)
2283 		m->m_flags |= M_IGMP_LOOP;
2284 
2285 	CTR2(KTR_IGMPV3, "%s: netisr_dispatch(NETISR_IGMP, %p)", __func__, m);
2286 	NET_EPOCH_ENTER(et);
2287 	netisr_dispatch(NETISR_IGMP, m);
2288 	NET_EPOCH_EXIT(et);
2289 
2290 	return (0);
2291 }
2292 
2293 /*
2294  * Process a state change from the upper layer for the given IPv4 group.
2295  *
2296  * Each socket holds a reference on the in_multi in its own ip_moptions.
2297  * The socket layer will have made the necessary updates to.the group
2298  * state, it is now up to IGMP to issue a state change report if there
2299  * has been any change between T0 (when the last state-change was issued)
2300  * and T1 (now).
2301  *
2302  * We use the IGMPv3 state machine at group level. The IGMP module
2303  * however makes the decision as to which IGMP protocol version to speak.
2304  * A state change *from* INCLUDE {} always means an initial join.
2305  * A state change *to* INCLUDE {} always means a final leave.
2306  *
2307  * FUTURE: If IGIF_V3LITE is enabled for this interface, then we can
2308  * save ourselves a bunch of work; any exclusive mode groups need not
2309  * compute source filter lists.
2310  *
2311  * VIMAGE: curvnet should have been set by caller, as this routine
2312  * is called from the socket option handlers.
2313  */
2314 int
2315 igmp_change_state(struct in_multi *inm)
2316 {
2317 	struct igmp_ifsoftc *igi;
2318 	struct ifnet *ifp;
2319 	int error;
2320 
2321 	error = 0;
2322 	IN_MULTI_LOCK_ASSERT();
2323 	/*
2324 	 * Try to detect if the upper layer just asked us to change state
2325 	 * for an interface which has now gone away.
2326 	 */
2327 	KASSERT(inm->inm_ifma != NULL, ("%s: no ifma", __func__));
2328 	ifp = inm->inm_ifma->ifma_ifp;
2329 	/*
2330 	 * Sanity check that netinet's notion of ifp is the
2331 	 * same as net's.
2332 	 */
2333 	KASSERT(inm->inm_ifp == ifp, ("%s: bad ifp", __func__));
2334 
2335 	IGMP_LOCK();
2336 
2337 	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
2338 	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
2339 
2340 	/*
2341 	 * If we detect a state transition to or from MCAST_UNDEFINED
2342 	 * for this group, then we are starting or finishing an IGMP
2343 	 * life cycle for this group.
2344 	 */
2345 	if (inm->inm_st[1].iss_fmode != inm->inm_st[0].iss_fmode) {
2346 		CTR3(KTR_IGMPV3, "%s: inm transition %d -> %d", __func__,
2347 		    inm->inm_st[0].iss_fmode, inm->inm_st[1].iss_fmode);
2348 		if (inm->inm_st[0].iss_fmode == MCAST_UNDEFINED) {
2349 			CTR1(KTR_IGMPV3, "%s: initial join", __func__);
2350 			error = igmp_initial_join(inm, igi);
2351 			goto out_locked;
2352 		} else if (inm->inm_st[1].iss_fmode == MCAST_UNDEFINED) {
2353 			CTR1(KTR_IGMPV3, "%s: final leave", __func__);
2354 			igmp_final_leave(inm, igi);
2355 			goto out_locked;
2356 		}
2357 	} else {
2358 		CTR1(KTR_IGMPV3, "%s: filter set change", __func__);
2359 	}
2360 
2361 	error = igmp_handle_state_change(inm, igi);
2362 
2363 out_locked:
2364 	IGMP_UNLOCK();
2365 	return (error);
2366 }
2367 
2368 /*
2369  * Perform the initial join for an IGMP group.
2370  *
2371  * When joining a group:
2372  *  If the group should have its IGMP traffic suppressed, do nothing.
2373  *  IGMPv1 starts sending IGMPv1 host membership reports.
2374  *  IGMPv2 starts sending IGMPv2 host membership reports.
2375  *  IGMPv3 will schedule an IGMPv3 state-change report containing the
2376  *  initial state of the membership.
2377  */
2378 static int
2379 igmp_initial_join(struct in_multi *inm, struct igmp_ifsoftc *igi)
2380 {
2381 	struct ifnet		*ifp;
2382 	struct mbufq		*mq;
2383 	int			 error, retval, syncstates;
2384 
2385 	CTR4(KTR_IGMPV3, "%s: initial join 0x%08x on ifp %p(%s)", __func__,
2386 	    ntohl(inm->inm_addr.s_addr), inm->inm_ifp, inm->inm_ifp->if_xname);
2387 
2388 	error = 0;
2389 	syncstates = 1;
2390 
2391 	ifp = inm->inm_ifp;
2392 
2393 	IN_MULTI_LOCK_ASSERT();
2394 	IGMP_LOCK_ASSERT();
2395 
2396 	KASSERT(igi && igi->igi_ifp == ifp, ("%s: inconsistent ifp", __func__));
2397 
2398 	/*
2399 	 * Groups joined on loopback or marked as 'not reported',
2400 	 * e.g. 224.0.0.1, enter the IGMP_SILENT_MEMBER state and
2401 	 * are never reported in any IGMP protocol exchanges.
2402 	 * All other groups enter the appropriate IGMP state machine
2403 	 * for the version in use on this link.
2404 	 * A link marked as IGIF_SILENT causes IGMP to be completely
2405 	 * disabled for the link.
2406 	 */
2407 	if ((ifp->if_flags & IFF_LOOPBACK) ||
2408 	    (igi->igi_flags & IGIF_SILENT) ||
2409 	    !igmp_isgroupreported(inm->inm_addr)) {
2410 		CTR1(KTR_IGMPV3,
2411 "%s: not kicking state machine for silent group", __func__);
2412 		inm->inm_state = IGMP_SILENT_MEMBER;
2413 		inm->inm_timer = 0;
2414 	} else {
2415 		/*
2416 		 * Deal with overlapping in_multi lifecycle.
2417 		 * If this group was LEAVING, then make sure
2418 		 * we drop the reference we picked up to keep the
2419 		 * group around for the final INCLUDE {} enqueue.
2420 		 */
2421 		if (igi->igi_version == IGMP_VERSION_3 &&
2422 		    inm->inm_state == IGMP_LEAVING_MEMBER) {
2423 			MPASS(inm->inm_refcount > 1);
2424 			inm_rele_locked(NULL, inm);
2425 		}
2426 		inm->inm_state = IGMP_REPORTING_MEMBER;
2427 
2428 		switch (igi->igi_version) {
2429 		case IGMP_VERSION_1:
2430 		case IGMP_VERSION_2:
2431 			inm->inm_state = IGMP_IDLE_MEMBER;
2432 			error = igmp_v1v2_queue_report(inm,
2433 			    (igi->igi_version == IGMP_VERSION_2) ?
2434 			     IGMP_v2_HOST_MEMBERSHIP_REPORT :
2435 			     IGMP_v1_HOST_MEMBERSHIP_REPORT);
2436 			if (error == 0) {
2437 				inm->inm_timer = IGMP_RANDOM_DELAY(
2438 				    IGMP_V1V2_MAX_RI * PR_FASTHZ);
2439 				V_current_state_timers_running = 1;
2440 			}
2441 			break;
2442 
2443 		case IGMP_VERSION_3:
2444 			/*
2445 			 * Defer update of T0 to T1, until the first copy
2446 			 * of the state change has been transmitted.
2447 			 */
2448 			syncstates = 0;
2449 
2450 			/*
2451 			 * Immediately enqueue a State-Change Report for
2452 			 * this interface, freeing any previous reports.
2453 			 * Don't kick the timers if there is nothing to do,
2454 			 * or if an error occurred.
2455 			 */
2456 			mq = &inm->inm_scq;
2457 			mbufq_drain(mq);
2458 			retval = igmp_v3_enqueue_group_record(mq, inm, 1,
2459 			    0, 0);
2460 			CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
2461 			    __func__, retval);
2462 			if (retval <= 0) {
2463 				error = retval * -1;
2464 				break;
2465 			}
2466 
2467 			/*
2468 			 * Schedule transmission of pending state-change
2469 			 * report up to RV times for this link. The timer
2470 			 * will fire at the next igmp_fasttimo (~200ms),
2471 			 * giving us an opportunity to merge the reports.
2472 			 */
2473 			if (igi->igi_flags & IGIF_LOOPBACK) {
2474 				inm->inm_scrv = 1;
2475 			} else {
2476 				KASSERT(igi->igi_rv > 1,
2477 				   ("%s: invalid robustness %d", __func__,
2478 				    igi->igi_rv));
2479 				inm->inm_scrv = igi->igi_rv;
2480 			}
2481 			inm->inm_sctimer = 1;
2482 			V_state_change_timers_running = 1;
2483 
2484 			error = 0;
2485 			break;
2486 		}
2487 	}
2488 
2489 	/*
2490 	 * Only update the T0 state if state change is atomic,
2491 	 * i.e. we don't need to wait for a timer to fire before we
2492 	 * can consider the state change to have been communicated.
2493 	 */
2494 	if (syncstates) {
2495 		inm_commit(inm);
2496 		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2497 		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2498 	}
2499 
2500 	return (error);
2501 }
2502 
2503 /*
2504  * Issue an intermediate state change during the IGMP life-cycle.
2505  */
2506 static int
2507 igmp_handle_state_change(struct in_multi *inm, struct igmp_ifsoftc *igi)
2508 {
2509 	struct ifnet		*ifp;
2510 	int			 retval;
2511 
2512 	CTR4(KTR_IGMPV3, "%s: state change for 0x%08x on ifp %p(%s)", __func__,
2513 	    ntohl(inm->inm_addr.s_addr), inm->inm_ifp, inm->inm_ifp->if_xname);
2514 
2515 	ifp = inm->inm_ifp;
2516 
2517 	IN_MULTI_LIST_LOCK_ASSERT();
2518 	IGMP_LOCK_ASSERT();
2519 
2520 	KASSERT(igi && igi->igi_ifp == ifp, ("%s: inconsistent ifp", __func__));
2521 
2522 	if ((ifp->if_flags & IFF_LOOPBACK) ||
2523 	    (igi->igi_flags & IGIF_SILENT) ||
2524 	    !igmp_isgroupreported(inm->inm_addr) ||
2525 	    (igi->igi_version != IGMP_VERSION_3)) {
2526 		if (!igmp_isgroupreported(inm->inm_addr)) {
2527 			CTR1(KTR_IGMPV3,
2528 "%s: not kicking state machine for silent group", __func__);
2529 		}
2530 		CTR1(KTR_IGMPV3, "%s: nothing to do", __func__);
2531 		inm_commit(inm);
2532 		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2533 		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2534 		return (0);
2535 	}
2536 
2537 	mbufq_drain(&inm->inm_scq);
2538 
2539 	retval = igmp_v3_enqueue_group_record(&inm->inm_scq, inm, 1, 0, 0);
2540 	CTR2(KTR_IGMPV3, "%s: enqueue record = %d", __func__, retval);
2541 	if (retval <= 0)
2542 		return (-retval);
2543 
2544 	/*
2545 	 * If record(s) were enqueued, start the state-change
2546 	 * report timer for this group.
2547 	 */
2548 	inm->inm_scrv = ((igi->igi_flags & IGIF_LOOPBACK) ? 1 : igi->igi_rv);
2549 	inm->inm_sctimer = 1;
2550 	V_state_change_timers_running = 1;
2551 
2552 	return (0);
2553 }
2554 
2555 /*
2556  * Perform the final leave for an IGMP group.
2557  *
2558  * When leaving a group:
2559  *  IGMPv1 does nothing.
2560  *  IGMPv2 sends a host leave message, if and only if we are the reporter.
2561  *  IGMPv3 enqueues a state-change report containing a transition
2562  *  to INCLUDE {} for immediate transmission.
2563  */
2564 static void
2565 igmp_final_leave(struct in_multi *inm, struct igmp_ifsoftc *igi)
2566 {
2567 	int syncstates;
2568 
2569 	syncstates = 1;
2570 
2571 	CTR4(KTR_IGMPV3, "%s: final leave 0x%08x on ifp %p(%s)",
2572 	    __func__, ntohl(inm->inm_addr.s_addr), inm->inm_ifp,
2573 	    inm->inm_ifp->if_xname);
2574 
2575 	IN_MULTI_LIST_LOCK_ASSERT();
2576 	IGMP_LOCK_ASSERT();
2577 
2578 	switch (inm->inm_state) {
2579 	case IGMP_NOT_MEMBER:
2580 	case IGMP_SILENT_MEMBER:
2581 	case IGMP_LEAVING_MEMBER:
2582 		/* Already leaving or left; do nothing. */
2583 		CTR1(KTR_IGMPV3,
2584 "%s: not kicking state machine for silent group", __func__);
2585 		break;
2586 	case IGMP_REPORTING_MEMBER:
2587 	case IGMP_IDLE_MEMBER:
2588 	case IGMP_G_QUERY_PENDING_MEMBER:
2589 	case IGMP_SG_QUERY_PENDING_MEMBER:
2590 		if (igi->igi_version == IGMP_VERSION_2) {
2591 #ifdef INVARIANTS
2592 			if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER ||
2593 			    inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER)
2594 			panic("%s: IGMPv3 state reached, not IGMPv3 mode",
2595 			     __func__);
2596 #endif
2597 			igmp_v1v2_queue_report(inm, IGMP_HOST_LEAVE_MESSAGE);
2598 			inm->inm_state = IGMP_NOT_MEMBER;
2599 		} else if (igi->igi_version == IGMP_VERSION_3) {
2600 			/*
2601 			 * Stop group timer and all pending reports.
2602 			 * Immediately enqueue a state-change report
2603 			 * TO_IN {} to be sent on the next fast timeout,
2604 			 * giving us an opportunity to merge reports.
2605 			 */
2606 			mbufq_drain(&inm->inm_scq);
2607 			inm->inm_timer = 0;
2608 			if (igi->igi_flags & IGIF_LOOPBACK) {
2609 				inm->inm_scrv = 1;
2610 			} else {
2611 				inm->inm_scrv = igi->igi_rv;
2612 			}
2613 			CTR4(KTR_IGMPV3, "%s: Leaving 0x%08x/%s with %d "
2614 			    "pending retransmissions.", __func__,
2615 			    ntohl(inm->inm_addr.s_addr),
2616 			    inm->inm_ifp->if_xname, inm->inm_scrv);
2617 			if (inm->inm_scrv == 0) {
2618 				inm->inm_state = IGMP_NOT_MEMBER;
2619 				inm->inm_sctimer = 0;
2620 			} else {
2621 				int retval __unused;
2622 
2623 				inm_acquire_locked(inm);
2624 
2625 				retval = igmp_v3_enqueue_group_record(
2626 				    &inm->inm_scq, inm, 1, 0, 0);
2627 				KASSERT(retval != 0,
2628 				    ("%s: enqueue record = %d", __func__,
2629 				     retval));
2630 
2631 				inm->inm_state = IGMP_LEAVING_MEMBER;
2632 				inm->inm_sctimer = 1;
2633 				V_state_change_timers_running = 1;
2634 				syncstates = 0;
2635 			}
2636 			break;
2637 		}
2638 		break;
2639 	case IGMP_LAZY_MEMBER:
2640 	case IGMP_SLEEPING_MEMBER:
2641 	case IGMP_AWAKENING_MEMBER:
2642 		/* Our reports are suppressed; do nothing. */
2643 		break;
2644 	}
2645 
2646 	if (syncstates) {
2647 		inm_commit(inm);
2648 		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2649 		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2650 		inm->inm_st[1].iss_fmode = MCAST_UNDEFINED;
2651 		CTR3(KTR_IGMPV3, "%s: T1 now MCAST_UNDEFINED for 0x%08x/%s",
2652 		    __func__, ntohl(inm->inm_addr.s_addr),
2653 		    inm->inm_ifp->if_xname);
2654 	}
2655 }
2656 
2657 /*
2658  * Enqueue an IGMPv3 group record to the given output queue.
2659  *
2660  * XXX This function could do with having the allocation code
2661  * split out, and the multiple-tree-walks coalesced into a single
2662  * routine as has been done in igmp_v3_enqueue_filter_change().
2663  *
2664  * If is_state_change is zero, a current-state record is appended.
2665  * If is_state_change is non-zero, a state-change report is appended.
2666  *
2667  * If is_group_query is non-zero, an mbuf packet chain is allocated.
2668  * If is_group_query is zero, and if there is a packet with free space
2669  * at the tail of the queue, it will be appended to providing there
2670  * is enough free space.
2671  * Otherwise a new mbuf packet chain is allocated.
2672  *
2673  * If is_source_query is non-zero, each source is checked to see if
2674  * it was recorded for a Group-Source query, and will be omitted if
2675  * it is not both in-mode and recorded.
2676  *
2677  * The function will attempt to allocate leading space in the packet
2678  * for the IP/IGMP header to be prepended without fragmenting the chain.
2679  *
2680  * If successful the size of all data appended to the queue is returned,
2681  * otherwise an error code less than zero is returned, or zero if
2682  * no record(s) were appended.
2683  */
2684 static int
2685 igmp_v3_enqueue_group_record(struct mbufq *mq, struct in_multi *inm,
2686     const int is_state_change, const int is_group_query,
2687     const int is_source_query)
2688 {
2689 	struct igmp_grouprec	 ig;
2690 	struct igmp_grouprec	*pig;
2691 	struct ifnet		*ifp;
2692 	struct ip_msource	*ims, *nims;
2693 	struct mbuf		*m0, *m, *md;
2694 	int			 is_filter_list_change;
2695 	int			 minrec0len, m0srcs, msrcs, nbytes, off;
2696 	int			 record_has_sources;
2697 	int			 now;
2698 	int			 type;
2699 	in_addr_t		 naddr;
2700 	uint8_t			 mode;
2701 
2702 	IN_MULTI_LIST_LOCK_ASSERT();
2703 
2704 	ifp = inm->inm_ifp;
2705 	is_filter_list_change = 0;
2706 	m = NULL;
2707 	m0 = NULL;
2708 	m0srcs = 0;
2709 	msrcs = 0;
2710 	nbytes = 0;
2711 	nims = NULL;
2712 	record_has_sources = 1;
2713 	pig = NULL;
2714 	type = IGMP_DO_NOTHING;
2715 	mode = inm->inm_st[1].iss_fmode;
2716 
2717 	/*
2718 	 * If we did not transition out of ASM mode during t0->t1,
2719 	 * and there are no source nodes to process, we can skip
2720 	 * the generation of source records.
2721 	 */
2722 	if (inm->inm_st[0].iss_asm > 0 && inm->inm_st[1].iss_asm > 0 &&
2723 	    inm->inm_nsrc == 0)
2724 		record_has_sources = 0;
2725 
2726 	if (is_state_change) {
2727 		/*
2728 		 * Queue a state change record.
2729 		 * If the mode did not change, and there are non-ASM
2730 		 * listeners or source filters present,
2731 		 * we potentially need to issue two records for the group.
2732 		 * If we are transitioning to MCAST_UNDEFINED, we need
2733 		 * not send any sources.
2734 		 * If there are ASM listeners, and there was no filter
2735 		 * mode transition of any kind, do nothing.
2736 		 */
2737 		if (mode != inm->inm_st[0].iss_fmode) {
2738 			if (mode == MCAST_EXCLUDE) {
2739 				CTR1(KTR_IGMPV3, "%s: change to EXCLUDE",
2740 				    __func__);
2741 				type = IGMP_CHANGE_TO_EXCLUDE_MODE;
2742 			} else {
2743 				CTR1(KTR_IGMPV3, "%s: change to INCLUDE",
2744 				    __func__);
2745 				type = IGMP_CHANGE_TO_INCLUDE_MODE;
2746 				if (mode == MCAST_UNDEFINED)
2747 					record_has_sources = 0;
2748 			}
2749 		} else {
2750 			if (record_has_sources) {
2751 				is_filter_list_change = 1;
2752 			} else {
2753 				type = IGMP_DO_NOTHING;
2754 			}
2755 		}
2756 	} else {
2757 		/*
2758 		 * Queue a current state record.
2759 		 */
2760 		if (mode == MCAST_EXCLUDE) {
2761 			type = IGMP_MODE_IS_EXCLUDE;
2762 		} else if (mode == MCAST_INCLUDE) {
2763 			type = IGMP_MODE_IS_INCLUDE;
2764 			KASSERT(inm->inm_st[1].iss_asm == 0,
2765 			    ("%s: inm %p is INCLUDE but ASM count is %d",
2766 			     __func__, inm, inm->inm_st[1].iss_asm));
2767 		}
2768 	}
2769 
2770 	/*
2771 	 * Generate the filter list changes using a separate function.
2772 	 */
2773 	if (is_filter_list_change)
2774 		return (igmp_v3_enqueue_filter_change(mq, inm));
2775 
2776 	if (type == IGMP_DO_NOTHING) {
2777 		CTR3(KTR_IGMPV3, "%s: nothing to do for 0x%08x/%s", __func__,
2778 		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2779 		return (0);
2780 	}
2781 
2782 	/*
2783 	 * If any sources are present, we must be able to fit at least
2784 	 * one in the trailing space of the tail packet's mbuf,
2785 	 * ideally more.
2786 	 */
2787 	minrec0len = sizeof(struct igmp_grouprec);
2788 	if (record_has_sources)
2789 		minrec0len += sizeof(in_addr_t);
2790 
2791 	CTR4(KTR_IGMPV3, "%s: queueing %s for 0x%08x/%s", __func__,
2792 	    igmp_rec_type_to_str(type), ntohl(inm->inm_addr.s_addr),
2793 	    inm->inm_ifp->if_xname);
2794 
2795 	/*
2796 	 * Check if we have a packet in the tail of the queue for this
2797 	 * group into which the first group record for this group will fit.
2798 	 * Otherwise allocate a new packet.
2799 	 * Always allocate leading space for IP+RA_OPT+IGMP+REPORT.
2800 	 * Note: Group records for G/GSR query responses MUST be sent
2801 	 * in their own packet.
2802 	 */
2803 	m0 = mbufq_last(mq);
2804 	if (!is_group_query &&
2805 	    m0 != NULL &&
2806 	    (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <= IGMP_V3_REPORT_MAXRECS) &&
2807 	    (m0->m_pkthdr.len + minrec0len) <
2808 	     (ifp->if_mtu - IGMP_LEADINGSPACE)) {
2809 		m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
2810 			    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2811 		m = m0;
2812 		CTR1(KTR_IGMPV3, "%s: use existing packet", __func__);
2813 	} else {
2814 		if (mbufq_full(mq)) {
2815 			CTR1(KTR_IGMPV3, "%s: outbound queue full", __func__);
2816 			return (-ENOMEM);
2817 		}
2818 		m = NULL;
2819 		m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
2820 		    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2821 		if (!is_state_change && !is_group_query) {
2822 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2823 			if (m)
2824 				m->m_data += IGMP_LEADINGSPACE;
2825 		}
2826 		if (m == NULL) {
2827 			m = m_gethdr(M_NOWAIT, MT_DATA);
2828 			if (m)
2829 				M_ALIGN(m, IGMP_LEADINGSPACE);
2830 		}
2831 		if (m == NULL)
2832 			return (-ENOMEM);
2833 
2834 		igmp_save_context(m, ifp);
2835 
2836 		CTR1(KTR_IGMPV3, "%s: allocated first packet", __func__);
2837 	}
2838 
2839 	/*
2840 	 * Append group record.
2841 	 * If we have sources, we don't know how many yet.
2842 	 */
2843 	ig.ig_type = type;
2844 	ig.ig_datalen = 0;
2845 	ig.ig_numsrc = 0;
2846 	ig.ig_group = inm->inm_addr;
2847 	if (!m_append(m, sizeof(struct igmp_grouprec), (void *)&ig)) {
2848 		if (m != m0)
2849 			m_freem(m);
2850 		CTR1(KTR_IGMPV3, "%s: m_append() failed.", __func__);
2851 		return (-ENOMEM);
2852 	}
2853 	nbytes += sizeof(struct igmp_grouprec);
2854 
2855 	/*
2856 	 * Append as many sources as will fit in the first packet.
2857 	 * If we are appending to a new packet, the chain allocation
2858 	 * may potentially use clusters; use m_getptr() in this case.
2859 	 * If we are appending to an existing packet, we need to obtain
2860 	 * a pointer to the group record after m_append(), in case a new
2861 	 * mbuf was allocated.
2862 	 * Only append sources which are in-mode at t1. If we are
2863 	 * transitioning to MCAST_UNDEFINED state on the group, do not
2864 	 * include source entries.
2865 	 * Only report recorded sources in our filter set when responding
2866 	 * to a group-source query.
2867 	 */
2868 	if (record_has_sources) {
2869 		if (m == m0) {
2870 			md = m_last(m);
2871 			pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) +
2872 			    md->m_len - nbytes);
2873 		} else {
2874 			md = m_getptr(m, 0, &off);
2875 			pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) +
2876 			    off);
2877 		}
2878 		msrcs = 0;
2879 		RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, nims) {
2880 			CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2881 			    ims->ims_haddr);
2882 			now = ims_get_mode(inm, ims, 1);
2883 			CTR2(KTR_IGMPV3, "%s: node is %d", __func__, now);
2884 			if ((now != mode) ||
2885 			    (now == mode && mode == MCAST_UNDEFINED)) {
2886 				CTR1(KTR_IGMPV3, "%s: skip node", __func__);
2887 				continue;
2888 			}
2889 			if (is_source_query && ims->ims_stp == 0) {
2890 				CTR1(KTR_IGMPV3, "%s: skip unrecorded node",
2891 				    __func__);
2892 				continue;
2893 			}
2894 			CTR1(KTR_IGMPV3, "%s: append node", __func__);
2895 			naddr = htonl(ims->ims_haddr);
2896 			if (!m_append(m, sizeof(in_addr_t), (void *)&naddr)) {
2897 				if (m != m0)
2898 					m_freem(m);
2899 				CTR1(KTR_IGMPV3, "%s: m_append() failed.",
2900 				    __func__);
2901 				return (-ENOMEM);
2902 			}
2903 			nbytes += sizeof(in_addr_t);
2904 			++msrcs;
2905 			if (msrcs == m0srcs)
2906 				break;
2907 		}
2908 		CTR2(KTR_IGMPV3, "%s: msrcs is %d this packet", __func__,
2909 		    msrcs);
2910 		pig->ig_numsrc = htons(msrcs);
2911 		nbytes += (msrcs * sizeof(in_addr_t));
2912 	}
2913 
2914 	if (is_source_query && msrcs == 0) {
2915 		CTR1(KTR_IGMPV3, "%s: no recorded sources to report", __func__);
2916 		if (m != m0)
2917 			m_freem(m);
2918 		return (0);
2919 	}
2920 
2921 	/*
2922 	 * We are good to go with first packet.
2923 	 */
2924 	if (m != m0) {
2925 		CTR1(KTR_IGMPV3, "%s: enqueueing first packet", __func__);
2926 		m->m_pkthdr.PH_vt.vt_nrecs = 1;
2927 		mbufq_enqueue(mq, m);
2928 	} else
2929 		m->m_pkthdr.PH_vt.vt_nrecs++;
2930 
2931 	/*
2932 	 * No further work needed if no source list in packet(s).
2933 	 */
2934 	if (!record_has_sources)
2935 		return (nbytes);
2936 
2937 	/*
2938 	 * Whilst sources remain to be announced, we need to allocate
2939 	 * a new packet and fill out as many sources as will fit.
2940 	 * Always try for a cluster first.
2941 	 */
2942 	while (nims != NULL) {
2943 		if (mbufq_full(mq)) {
2944 			CTR1(KTR_IGMPV3, "%s: outbound queue full", __func__);
2945 			return (-ENOMEM);
2946 		}
2947 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2948 		if (m)
2949 			m->m_data += IGMP_LEADINGSPACE;
2950 		if (m == NULL) {
2951 			m = m_gethdr(M_NOWAIT, MT_DATA);
2952 			if (m)
2953 				M_ALIGN(m, IGMP_LEADINGSPACE);
2954 		}
2955 		if (m == NULL)
2956 			return (-ENOMEM);
2957 		igmp_save_context(m, ifp);
2958 		md = m_getptr(m, 0, &off);
2959 		pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) + off);
2960 		CTR1(KTR_IGMPV3, "%s: allocated next packet", __func__);
2961 
2962 		if (!m_append(m, sizeof(struct igmp_grouprec), (void *)&ig)) {
2963 			if (m != m0)
2964 				m_freem(m);
2965 			CTR1(KTR_IGMPV3, "%s: m_append() failed.", __func__);
2966 			return (-ENOMEM);
2967 		}
2968 		m->m_pkthdr.PH_vt.vt_nrecs = 1;
2969 		nbytes += sizeof(struct igmp_grouprec);
2970 
2971 		m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
2972 		    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2973 
2974 		msrcs = 0;
2975 		RB_FOREACH_FROM(ims, ip_msource_tree, nims) {
2976 			CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2977 			    ims->ims_haddr);
2978 			now = ims_get_mode(inm, ims, 1);
2979 			if ((now != mode) ||
2980 			    (now == mode && mode == MCAST_UNDEFINED)) {
2981 				CTR1(KTR_IGMPV3, "%s: skip node", __func__);
2982 				continue;
2983 			}
2984 			if (is_source_query && ims->ims_stp == 0) {
2985 				CTR1(KTR_IGMPV3, "%s: skip unrecorded node",
2986 				    __func__);
2987 				continue;
2988 			}
2989 			CTR1(KTR_IGMPV3, "%s: append node", __func__);
2990 			naddr = htonl(ims->ims_haddr);
2991 			if (!m_append(m, sizeof(in_addr_t), (void *)&naddr)) {
2992 				if (m != m0)
2993 					m_freem(m);
2994 				CTR1(KTR_IGMPV3, "%s: m_append() failed.",
2995 				    __func__);
2996 				return (-ENOMEM);
2997 			}
2998 			++msrcs;
2999 			if (msrcs == m0srcs)
3000 				break;
3001 		}
3002 		pig->ig_numsrc = htons(msrcs);
3003 		nbytes += (msrcs * sizeof(in_addr_t));
3004 
3005 		CTR1(KTR_IGMPV3, "%s: enqueueing next packet", __func__);
3006 		mbufq_enqueue(mq, m);
3007 	}
3008 
3009 	return (nbytes);
3010 }
3011 
3012 /*
3013  * Type used to mark record pass completion.
3014  * We exploit the fact we can cast to this easily from the
3015  * current filter modes on each ip_msource node.
3016  */
3017 typedef enum {
3018 	REC_NONE = 0x00,	/* MCAST_UNDEFINED */
3019 	REC_ALLOW = 0x01,	/* MCAST_INCLUDE */
3020 	REC_BLOCK = 0x02,	/* MCAST_EXCLUDE */
3021 	REC_FULL = REC_ALLOW | REC_BLOCK
3022 } rectype_t;
3023 
3024 /*
3025  * Enqueue an IGMPv3 filter list change to the given output queue.
3026  *
3027  * Source list filter state is held in an RB-tree. When the filter list
3028  * for a group is changed without changing its mode, we need to compute
3029  * the deltas between T0 and T1 for each source in the filter set,
3030  * and enqueue the appropriate ALLOW_NEW/BLOCK_OLD records.
3031  *
3032  * As we may potentially queue two record types, and the entire R-B tree
3033  * needs to be walked at once, we break this out into its own function
3034  * so we can generate a tightly packed queue of packets.
3035  *
3036  * XXX This could be written to only use one tree walk, although that makes
3037  * serializing into the mbuf chains a bit harder. For now we do two walks
3038  * which makes things easier on us, and it may or may not be harder on
3039  * the L2 cache.
3040  *
3041  * If successful the size of all data appended to the queue is returned,
3042  * otherwise an error code less than zero is returned, or zero if
3043  * no record(s) were appended.
3044  */
3045 static int
3046 igmp_v3_enqueue_filter_change(struct mbufq *mq, struct in_multi *inm)
3047 {
3048 	static const int MINRECLEN =
3049 	    sizeof(struct igmp_grouprec) + sizeof(in_addr_t);
3050 	struct ifnet		*ifp;
3051 	struct igmp_grouprec	 ig;
3052 	struct igmp_grouprec	*pig;
3053 	struct ip_msource	*ims, *nims;
3054 	struct mbuf		*m, *m0, *md;
3055 	in_addr_t		 naddr;
3056 	int			 m0srcs, nbytes, npbytes, off, rsrcs, schanged;
3057 	int			 nallow, nblock;
3058 	uint8_t			 mode, now, then;
3059 	rectype_t		 crt, drt, nrt;
3060 
3061 	IN_MULTI_LIST_LOCK_ASSERT();
3062 
3063 	if (inm->inm_nsrc == 0 ||
3064 	    (inm->inm_st[0].iss_asm > 0 && inm->inm_st[1].iss_asm > 0))
3065 		return (0);
3066 
3067 	ifp = inm->inm_ifp;			/* interface */
3068 	mode = inm->inm_st[1].iss_fmode;	/* filter mode at t1 */
3069 	crt = REC_NONE;	/* current group record type */
3070 	drt = REC_NONE;	/* mask of completed group record types */
3071 	nrt = REC_NONE;	/* record type for current node */
3072 	m0srcs = 0;	/* # source which will fit in current mbuf chain */
3073 	nbytes = 0;	/* # of bytes appended to group's state-change queue */
3074 	npbytes = 0;	/* # of bytes appended this packet */
3075 	rsrcs = 0;	/* # sources encoded in current record */
3076 	schanged = 0;	/* # nodes encoded in overall filter change */
3077 	nallow = 0;	/* # of source entries in ALLOW_NEW */
3078 	nblock = 0;	/* # of source entries in BLOCK_OLD */
3079 	nims = NULL;	/* next tree node pointer */
3080 
3081 	/*
3082 	 * For each possible filter record mode.
3083 	 * The first kind of source we encounter tells us which
3084 	 * is the first kind of record we start appending.
3085 	 * If a node transitioned to UNDEFINED at t1, its mode is treated
3086 	 * as the inverse of the group's filter mode.
3087 	 */
3088 	while (drt != REC_FULL) {
3089 		do {
3090 			m0 = mbufq_last(mq);
3091 			if (m0 != NULL &&
3092 			    (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <=
3093 			     IGMP_V3_REPORT_MAXRECS) &&
3094 			    (m0->m_pkthdr.len + MINRECLEN) <
3095 			     (ifp->if_mtu - IGMP_LEADINGSPACE)) {
3096 				m = m0;
3097 				m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
3098 					    sizeof(struct igmp_grouprec)) /
3099 				    sizeof(in_addr_t);
3100 				CTR1(KTR_IGMPV3,
3101 				    "%s: use previous packet", __func__);
3102 			} else {
3103 				m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
3104 				if (m)
3105 					m->m_data += IGMP_LEADINGSPACE;
3106 				if (m == NULL) {
3107 					m = m_gethdr(M_NOWAIT, MT_DATA);
3108 					if (m)
3109 						M_ALIGN(m, IGMP_LEADINGSPACE);
3110 				}
3111 				if (m == NULL) {
3112 					CTR1(KTR_IGMPV3,
3113 					    "%s: m_get*() failed", __func__);
3114 					return (-ENOMEM);
3115 				}
3116 				m->m_pkthdr.PH_vt.vt_nrecs = 0;
3117 				igmp_save_context(m, ifp);
3118 				m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
3119 				    sizeof(struct igmp_grouprec)) /
3120 				    sizeof(in_addr_t);
3121 				npbytes = 0;
3122 				CTR1(KTR_IGMPV3,
3123 				    "%s: allocated new packet", __func__);
3124 			}
3125 			/*
3126 			 * Append the IGMP group record header to the
3127 			 * current packet's data area.
3128 			 * Recalculate pointer to free space for next
3129 			 * group record, in case m_append() allocated
3130 			 * a new mbuf or cluster.
3131 			 */
3132 			memset(&ig, 0, sizeof(ig));
3133 			ig.ig_group = inm->inm_addr;
3134 			if (!m_append(m, sizeof(ig), (void *)&ig)) {
3135 				if (m != m0)
3136 					m_freem(m);
3137 				CTR1(KTR_IGMPV3,
3138 				    "%s: m_append() failed", __func__);
3139 				return (-ENOMEM);
3140 			}
3141 			npbytes += sizeof(struct igmp_grouprec);
3142 			if (m != m0) {
3143 				/* new packet; offset in c hain */
3144 				md = m_getptr(m, npbytes -
3145 				    sizeof(struct igmp_grouprec), &off);
3146 				pig = (struct igmp_grouprec *)(mtod(md,
3147 				    uint8_t *) + off);
3148 			} else {
3149 				/* current packet; offset from last append */
3150 				md = m_last(m);
3151 				pig = (struct igmp_grouprec *)(mtod(md,
3152 				    uint8_t *) + md->m_len -
3153 				    sizeof(struct igmp_grouprec));
3154 			}
3155 			/*
3156 			 * Begin walking the tree for this record type
3157 			 * pass, or continue from where we left off
3158 			 * previously if we had to allocate a new packet.
3159 			 * Only report deltas in-mode at t1.
3160 			 * We need not report included sources as allowed
3161 			 * if we are in inclusive mode on the group,
3162 			 * however the converse is not true.
3163 			 */
3164 			rsrcs = 0;
3165 			if (nims == NULL)
3166 				nims = RB_MIN(ip_msource_tree, &inm->inm_srcs);
3167 			RB_FOREACH_FROM(ims, ip_msource_tree, nims) {
3168 				CTR2(KTR_IGMPV3, "%s: visit node 0x%08x",
3169 				    __func__, ims->ims_haddr);
3170 				now = ims_get_mode(inm, ims, 1);
3171 				then = ims_get_mode(inm, ims, 0);
3172 				CTR3(KTR_IGMPV3, "%s: mode: t0 %d, t1 %d",
3173 				    __func__, then, now);
3174 				if (now == then) {
3175 					CTR1(KTR_IGMPV3,
3176 					    "%s: skip unchanged", __func__);
3177 					continue;
3178 				}
3179 				if (mode == MCAST_EXCLUDE &&
3180 				    now == MCAST_INCLUDE) {
3181 					CTR1(KTR_IGMPV3,
3182 					    "%s: skip IN src on EX group",
3183 					    __func__);
3184 					continue;
3185 				}
3186 				nrt = (rectype_t)now;
3187 				if (nrt == REC_NONE)
3188 					nrt = (rectype_t)(~mode & REC_FULL);
3189 				if (schanged++ == 0) {
3190 					crt = nrt;
3191 				} else if (crt != nrt)
3192 					continue;
3193 				naddr = htonl(ims->ims_haddr);
3194 				if (!m_append(m, sizeof(in_addr_t),
3195 				    (void *)&naddr)) {
3196 					if (m != m0)
3197 						m_freem(m);
3198 					CTR1(KTR_IGMPV3,
3199 					    "%s: m_append() failed", __func__);
3200 					return (-ENOMEM);
3201 				}
3202 				nallow += !!(crt == REC_ALLOW);
3203 				nblock += !!(crt == REC_BLOCK);
3204 				if (++rsrcs == m0srcs)
3205 					break;
3206 			}
3207 			/*
3208 			 * If we did not append any tree nodes on this
3209 			 * pass, back out of allocations.
3210 			 */
3211 			if (rsrcs == 0) {
3212 				npbytes -= sizeof(struct igmp_grouprec);
3213 				if (m != m0) {
3214 					CTR1(KTR_IGMPV3,
3215 					    "%s: m_free(m)", __func__);
3216 					m_freem(m);
3217 				} else {
3218 					CTR1(KTR_IGMPV3,
3219 					    "%s: m_adj(m, -ig)", __func__);
3220 					m_adj(m, -((int)sizeof(
3221 					    struct igmp_grouprec)));
3222 				}
3223 				continue;
3224 			}
3225 			npbytes += (rsrcs * sizeof(in_addr_t));
3226 			if (crt == REC_ALLOW)
3227 				pig->ig_type = IGMP_ALLOW_NEW_SOURCES;
3228 			else if (crt == REC_BLOCK)
3229 				pig->ig_type = IGMP_BLOCK_OLD_SOURCES;
3230 			pig->ig_numsrc = htons(rsrcs);
3231 			/*
3232 			 * Count the new group record, and enqueue this
3233 			 * packet if it wasn't already queued.
3234 			 */
3235 			m->m_pkthdr.PH_vt.vt_nrecs++;
3236 			if (m != m0)
3237 				mbufq_enqueue(mq, m);
3238 			nbytes += npbytes;
3239 		} while (nims != NULL);
3240 		drt |= crt;
3241 		crt = (~crt & REC_FULL);
3242 	}
3243 
3244 	CTR3(KTR_IGMPV3, "%s: queued %d ALLOW_NEW, %d BLOCK_OLD", __func__,
3245 	    nallow, nblock);
3246 
3247 	return (nbytes);
3248 }
3249 
3250 static int
3251 igmp_v3_merge_state_changes(struct in_multi *inm, struct mbufq *scq)
3252 {
3253 	struct mbufq	*gq;
3254 	struct mbuf	*m;		/* pending state-change */
3255 	struct mbuf	*m0;		/* copy of pending state-change */
3256 	struct mbuf	*mt;		/* last state-change in packet */
3257 	int		 docopy, domerge;
3258 	u_int		 recslen;
3259 
3260 	docopy = 0;
3261 	domerge = 0;
3262 	recslen = 0;
3263 
3264 	IN_MULTI_LIST_LOCK_ASSERT();
3265 	IGMP_LOCK_ASSERT();
3266 
3267 	/*
3268 	 * If there are further pending retransmissions, make a writable
3269 	 * copy of each queued state-change message before merging.
3270 	 */
3271 	if (inm->inm_scrv > 0)
3272 		docopy = 1;
3273 
3274 	gq = &inm->inm_scq;
3275 #ifdef KTR
3276 	if (mbufq_first(gq) == NULL) {
3277 		CTR2(KTR_IGMPV3, "%s: WARNING: queue for inm %p is empty",
3278 		    __func__, inm);
3279 	}
3280 #endif
3281 
3282 	m = mbufq_first(gq);
3283 	while (m != NULL) {
3284 		/*
3285 		 * Only merge the report into the current packet if
3286 		 * there is sufficient space to do so; an IGMPv3 report
3287 		 * packet may only contain 65,535 group records.
3288 		 * Always use a simple mbuf chain concatentation to do this,
3289 		 * as large state changes for single groups may have
3290 		 * allocated clusters.
3291 		 */
3292 		domerge = 0;
3293 		mt = mbufq_last(scq);
3294 		if (mt != NULL) {
3295 			recslen = m_length(m, NULL);
3296 
3297 			if ((mt->m_pkthdr.PH_vt.vt_nrecs +
3298 			    m->m_pkthdr.PH_vt.vt_nrecs <=
3299 			    IGMP_V3_REPORT_MAXRECS) &&
3300 			    (mt->m_pkthdr.len + recslen <=
3301 			    (inm->inm_ifp->if_mtu - IGMP_LEADINGSPACE)))
3302 				domerge = 1;
3303 		}
3304 
3305 		if (!domerge && mbufq_full(gq)) {
3306 			CTR2(KTR_IGMPV3,
3307 			    "%s: outbound queue full, skipping whole packet %p",
3308 			    __func__, m);
3309 			mt = m->m_nextpkt;
3310 			if (!docopy)
3311 				m_freem(m);
3312 			m = mt;
3313 			continue;
3314 		}
3315 
3316 		if (!docopy) {
3317 			CTR2(KTR_IGMPV3, "%s: dequeueing %p", __func__, m);
3318 			m0 = mbufq_dequeue(gq);
3319 			m = m0->m_nextpkt;
3320 		} else {
3321 			CTR2(KTR_IGMPV3, "%s: copying %p", __func__, m);
3322 			m0 = m_dup(m, M_NOWAIT);
3323 			if (m0 == NULL)
3324 				return (ENOMEM);
3325 			m0->m_nextpkt = NULL;
3326 			m = m->m_nextpkt;
3327 		}
3328 
3329 		if (!domerge) {
3330 			CTR3(KTR_IGMPV3, "%s: queueing %p to scq %p)",
3331 			    __func__, m0, scq);
3332 			mbufq_enqueue(scq, m0);
3333 		} else {
3334 			struct mbuf *mtl;	/* last mbuf of packet mt */
3335 
3336 			CTR3(KTR_IGMPV3, "%s: merging %p with scq tail %p)",
3337 			    __func__, m0, mt);
3338 
3339 			mtl = m_last(mt);
3340 			m0->m_flags &= ~M_PKTHDR;
3341 			mt->m_pkthdr.len += recslen;
3342 			mt->m_pkthdr.PH_vt.vt_nrecs +=
3343 			    m0->m_pkthdr.PH_vt.vt_nrecs;
3344 
3345 			mtl->m_next = m0;
3346 		}
3347 	}
3348 
3349 	return (0);
3350 }
3351 
3352 /*
3353  * Respond to a pending IGMPv3 General Query.
3354  */
3355 static void
3356 igmp_v3_dispatch_general_query(struct igmp_ifsoftc *igi)
3357 {
3358 	struct ifmultiaddr	*ifma;
3359 	struct ifnet		*ifp;
3360 	struct in_multi		*inm;
3361 	int			 retval __unused, loop;
3362 
3363 	IN_MULTI_LIST_LOCK_ASSERT();
3364 	IGMP_LOCK_ASSERT();
3365 	NET_EPOCH_ASSERT();
3366 
3367 	KASSERT(igi->igi_version == IGMP_VERSION_3,
3368 	    ("%s: called when version %d", __func__, igi->igi_version));
3369 
3370 	/*
3371 	 * Check that there are some packets queued. If so, send them first.
3372 	 * For large number of groups the reply to general query can take
3373 	 * many packets, we should finish sending them before starting of
3374 	 * queuing the new reply.
3375 	 */
3376 	if (mbufq_len(&igi->igi_gq) != 0)
3377 		goto send;
3378 
3379 	ifp = igi->igi_ifp;
3380 
3381 	CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3382 		if (ifma->ifma_addr->sa_family != AF_INET ||
3383 		    ifma->ifma_protospec == NULL)
3384 			continue;
3385 
3386 		inm = (struct in_multi *)ifma->ifma_protospec;
3387 		KASSERT(ifp == inm->inm_ifp,
3388 		    ("%s: inconsistent ifp", __func__));
3389 
3390 		switch (inm->inm_state) {
3391 		case IGMP_NOT_MEMBER:
3392 		case IGMP_SILENT_MEMBER:
3393 			break;
3394 		case IGMP_REPORTING_MEMBER:
3395 		case IGMP_IDLE_MEMBER:
3396 		case IGMP_LAZY_MEMBER:
3397 		case IGMP_SLEEPING_MEMBER:
3398 		case IGMP_AWAKENING_MEMBER:
3399 			inm->inm_state = IGMP_REPORTING_MEMBER;
3400 			retval = igmp_v3_enqueue_group_record(&igi->igi_gq,
3401 			    inm, 0, 0, 0);
3402 			CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
3403 			    __func__, retval);
3404 			break;
3405 		case IGMP_G_QUERY_PENDING_MEMBER:
3406 		case IGMP_SG_QUERY_PENDING_MEMBER:
3407 		case IGMP_LEAVING_MEMBER:
3408 			break;
3409 		}
3410 	}
3411 
3412 send:
3413 	loop = (igi->igi_flags & IGIF_LOOPBACK) ? 1 : 0;
3414 	igmp_dispatch_queue(&igi->igi_gq, IGMP_MAX_RESPONSE_BURST, loop);
3415 
3416 	/*
3417 	 * Slew transmission of bursts over 500ms intervals.
3418 	 */
3419 	if (mbufq_first(&igi->igi_gq) != NULL) {
3420 		igi->igi_v3_timer = 1 + IGMP_RANDOM_DELAY(
3421 		    IGMP_RESPONSE_BURST_INTERVAL);
3422 		V_interface_timers_running = 1;
3423 	}
3424 }
3425 
3426 /*
3427  * Transmit the next pending IGMP message in the output queue.
3428  *
3429  * We get called from netisr_processqueue(). A mutex private to igmpoq
3430  * will be acquired and released around this routine.
3431  *
3432  * VIMAGE: Needs to store/restore vnet pointer on a per-mbuf-chain basis.
3433  * MRT: Nothing needs to be done, as IGMP traffic is always local to
3434  * a link and uses a link-scope multicast address.
3435  */
3436 static void
3437 igmp_intr(struct mbuf *m)
3438 {
3439 	struct ip_moptions	 imo;
3440 	struct ifnet		*ifp;
3441 	struct mbuf		*ipopts, *m0;
3442 	int			 error;
3443 	uint32_t		 ifindex;
3444 
3445 	CTR2(KTR_IGMPV3, "%s: transmit %p", __func__, m);
3446 
3447 	/*
3448 	 * Set VNET image pointer from enqueued mbuf chain
3449 	 * before doing anything else. Whilst we use interface
3450 	 * indexes to guard against interface detach, they are
3451 	 * unique to each VIMAGE and must be retrieved.
3452 	 */
3453 	CURVNET_SET((struct vnet *)(m->m_pkthdr.PH_loc.ptr));
3454 	ifindex = igmp_restore_context(m);
3455 
3456 	/*
3457 	 * Check if the ifnet still exists. This limits the scope of
3458 	 * any race in the absence of a global ifp lock for low cost
3459 	 * (an array lookup).
3460 	 */
3461 	ifp = ifnet_byindex(ifindex);
3462 	if (ifp == NULL) {
3463 		CTR3(KTR_IGMPV3, "%s: dropped %p as ifindex %u went away.",
3464 		    __func__, m, ifindex);
3465 		m_freem(m);
3466 		IPSTAT_INC(ips_noroute);
3467 		goto out;
3468 	}
3469 
3470 	ipopts = V_igmp_sendra ? m_raopt : NULL;
3471 
3472 	imo.imo_multicast_ttl  = 1;
3473 	imo.imo_multicast_vif  = -1;
3474 	imo.imo_multicast_loop = (V_ip_mrouter != NULL);
3475 
3476 	/*
3477 	 * If the user requested that IGMP traffic be explicitly
3478 	 * redirected to the loopback interface (e.g. they are running a
3479 	 * MANET interface and the routing protocol needs to see the
3480 	 * updates), handle this now.
3481 	 */
3482 	if (m->m_flags & M_IGMP_LOOP)
3483 		imo.imo_multicast_ifp = V_loif;
3484 	else
3485 		imo.imo_multicast_ifp = ifp;
3486 
3487 	if (m->m_flags & M_IGMPV2) {
3488 		m0 = m;
3489 	} else {
3490 		m0 = igmp_v3_encap_report(ifp, m);
3491 		if (m0 == NULL) {
3492 			CTR2(KTR_IGMPV3, "%s: dropped %p", __func__, m);
3493 			m_freem(m);
3494 			IPSTAT_INC(ips_odropped);
3495 			goto out;
3496 		}
3497 	}
3498 
3499 	igmp_scrub_context(m0);
3500 	m_clrprotoflags(m);
3501 	m0->m_pkthdr.rcvif = V_loif;
3502 #ifdef MAC
3503 	mac_netinet_igmp_send(ifp, m0);
3504 #endif
3505 	error = ip_output(m0, ipopts, NULL, 0, &imo, NULL);
3506 	if (error) {
3507 		CTR3(KTR_IGMPV3, "%s: ip_output(%p) = %d", __func__, m0, error);
3508 		goto out;
3509 	}
3510 
3511 	IGMPSTAT_INC(igps_snd_reports);
3512 
3513 out:
3514 	/*
3515 	 * We must restore the existing vnet pointer before
3516 	 * continuing as we are run from netisr context.
3517 	 */
3518 	CURVNET_RESTORE();
3519 }
3520 
3521 /*
3522  * Encapsulate an IGMPv3 report.
3523  *
3524  * The internal mbuf flag M_IGMPV3_HDR is used to indicate that the mbuf
3525  * chain has already had its IP/IGMPv3 header prepended. In this case
3526  * the function will not attempt to prepend; the lengths and checksums
3527  * will however be re-computed.
3528  *
3529  * Returns a pointer to the new mbuf chain head, or NULL if the
3530  * allocation failed.
3531  */
3532 static struct mbuf *
3533 igmp_v3_encap_report(struct ifnet *ifp, struct mbuf *m)
3534 {
3535 	struct igmp_report	*igmp;
3536 	struct ip		*ip;
3537 	int			 hdrlen, igmpreclen;
3538 
3539 	KASSERT((m->m_flags & M_PKTHDR),
3540 	    ("%s: mbuf chain %p is !M_PKTHDR", __func__, m));
3541 
3542 	igmpreclen = m_length(m, NULL);
3543 	hdrlen = sizeof(struct ip) + sizeof(struct igmp_report);
3544 
3545 	if (m->m_flags & M_IGMPV3_HDR) {
3546 		igmpreclen -= hdrlen;
3547 	} else {
3548 		M_PREPEND(m, hdrlen, M_NOWAIT);
3549 		if (m == NULL)
3550 			return (NULL);
3551 		m->m_flags |= M_IGMPV3_HDR;
3552 	}
3553 
3554 	CTR2(KTR_IGMPV3, "%s: igmpreclen is %d", __func__, igmpreclen);
3555 
3556 	m->m_data += sizeof(struct ip);
3557 	m->m_len -= sizeof(struct ip);
3558 
3559 	igmp = mtod(m, struct igmp_report *);
3560 	igmp->ir_type = IGMP_v3_HOST_MEMBERSHIP_REPORT;
3561 	igmp->ir_rsv1 = 0;
3562 	igmp->ir_rsv2 = 0;
3563 	igmp->ir_numgrps = htons(m->m_pkthdr.PH_vt.vt_nrecs);
3564 	igmp->ir_cksum = 0;
3565 	igmp->ir_cksum = in_cksum(m, sizeof(struct igmp_report) + igmpreclen);
3566 	m->m_pkthdr.PH_vt.vt_nrecs = 0;
3567 
3568 	m->m_data -= sizeof(struct ip);
3569 	m->m_len += sizeof(struct ip);
3570 
3571 	ip = mtod(m, struct ip *);
3572 	ip->ip_tos = IPTOS_PREC_INTERNETCONTROL;
3573 	ip->ip_len = htons(hdrlen + igmpreclen);
3574 	ip->ip_off = htons(IP_DF);
3575 	ip->ip_p = IPPROTO_IGMP;
3576 	ip->ip_sum = 0;
3577 
3578 	ip->ip_src.s_addr = INADDR_ANY;
3579 
3580 	if (m->m_flags & M_IGMP_LOOP) {
3581 		struct in_ifaddr *ia;
3582 
3583 		IFP_TO_IA(ifp, ia);
3584 		if (ia != NULL)
3585 			ip->ip_src = ia->ia_addr.sin_addr;
3586 	}
3587 
3588 	ip->ip_dst.s_addr = htonl(INADDR_ALLRPTS_GROUP);
3589 
3590 	return (m);
3591 }
3592 
3593 #ifdef KTR
3594 static char *
3595 igmp_rec_type_to_str(const int type)
3596 {
3597 
3598 	switch (type) {
3599 		case IGMP_CHANGE_TO_EXCLUDE_MODE:
3600 			return "TO_EX";
3601 			break;
3602 		case IGMP_CHANGE_TO_INCLUDE_MODE:
3603 			return "TO_IN";
3604 			break;
3605 		case IGMP_MODE_IS_EXCLUDE:
3606 			return "MODE_EX";
3607 			break;
3608 		case IGMP_MODE_IS_INCLUDE:
3609 			return "MODE_IN";
3610 			break;
3611 		case IGMP_ALLOW_NEW_SOURCES:
3612 			return "ALLOW_NEW";
3613 			break;
3614 		case IGMP_BLOCK_OLD_SOURCES:
3615 			return "BLOCK_OLD";
3616 			break;
3617 		default:
3618 			break;
3619 	}
3620 	return "unknown";
3621 }
3622 #endif
3623 
3624 #ifdef VIMAGE
3625 static void
3626 vnet_igmp_init(const void *unused __unused)
3627 {
3628 
3629 	netisr_register_vnet(&igmp_nh);
3630 }
3631 VNET_SYSINIT(vnet_igmp_init, SI_SUB_PROTO_MC, SI_ORDER_ANY,
3632     vnet_igmp_init, NULL);
3633 
3634 static void
3635 vnet_igmp_uninit(const void *unused __unused)
3636 {
3637 
3638 	/* This can happen when we shutdown the entire network stack. */
3639 	CTR1(KTR_IGMPV3, "%s: tearing down", __func__);
3640 
3641 	netisr_unregister_vnet(&igmp_nh);
3642 }
3643 VNET_SYSUNINIT(vnet_igmp_uninit, SI_SUB_PROTO_MC, SI_ORDER_ANY,
3644     vnet_igmp_uninit, NULL);
3645 #endif
3646 
3647 #ifdef DDB
3648 DB_SHOW_COMMAND(igi_list, db_show_igi_list)
3649 {
3650 	struct igmp_ifsoftc *igi, *tigi;
3651 	LIST_HEAD(_igi_list, igmp_ifsoftc) *igi_head;
3652 
3653 	if (!have_addr) {
3654 		db_printf("usage: show igi_list <addr>\n");
3655 		return;
3656 	}
3657 	igi_head = (struct _igi_list *)addr;
3658 
3659 	LIST_FOREACH_SAFE(igi, igi_head, igi_link, tigi) {
3660 		db_printf("igmp_ifsoftc %p:\n", igi);
3661 		db_printf("    ifp %p\n", igi->igi_ifp);
3662 		db_printf("    version %u\n", igi->igi_version);
3663 		db_printf("    v1_timer %u\n", igi->igi_v1_timer);
3664 		db_printf("    v2_timer %u\n", igi->igi_v2_timer);
3665 		db_printf("    v3_timer %u\n", igi->igi_v3_timer);
3666 		db_printf("    flags %#x\n", igi->igi_flags);
3667 		db_printf("    rv %u\n", igi->igi_rv);
3668 		db_printf("    qi %u\n", igi->igi_qi);
3669 		db_printf("    qri %u\n", igi->igi_qri);
3670 		db_printf("    uri %u\n", igi->igi_uri);
3671 		/* struct mbufq    igi_gq; */
3672 		db_printf("\n");
3673 	}
3674 }
3675 #endif
3676 
3677 static int
3678 igmp_modevent(module_t mod, int type, void *unused __unused)
3679 {
3680 
3681 	switch (type) {
3682 	case MOD_LOAD:
3683 		CTR1(KTR_IGMPV3, "%s: initializing", __func__);
3684 		IGMP_LOCK_INIT();
3685 		m_raopt = igmp_ra_alloc();
3686 		netisr_register(&igmp_nh);
3687 		break;
3688 	case MOD_UNLOAD:
3689 		CTR1(KTR_IGMPV3, "%s: tearing down", __func__);
3690 		netisr_unregister(&igmp_nh);
3691 		m_free(m_raopt);
3692 		m_raopt = NULL;
3693 		IGMP_LOCK_DESTROY();
3694 		break;
3695 	default:
3696 		return (EOPNOTSUPP);
3697 	}
3698 	return (0);
3699 }
3700 
3701 static moduledata_t igmp_mod = {
3702     "igmp",
3703     igmp_modevent,
3704     0
3705 };
3706 DECLARE_MODULE(igmp, igmp_mod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);
3707