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