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