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