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