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