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