xref: /freebsd/sys/netinet/igmp.c (revision 031beb4e239bfce798af17f5fe8dba8bcaf13d99)
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 (igi->igi_version != IGMP_VERSION_3) {
2128 			CTR5(KTR_IGMPV3,
2129 			    "%s: transition from v%d -> v%d on %p(%s)",
2130 			    __func__, igi->igi_version, IGMP_VERSION_3,
2131 			    igi->igi_ifp, igi->igi_ifp->if_xname);
2132 			igi->igi_version = IGMP_VERSION_3;
2133 		}
2134 	} else if (igi->igi_v1_timer == 0 && igi->igi_v2_timer > 0) {
2135 		/*
2136 		 * IGMPv1 Querier Present timer expired,
2137 		 * IGMPv2 Querier Present timer running.
2138 		 * If IGMPv2 was disabled since last timeout,
2139 		 * revert to IGMPv3.
2140 		 * If IGMPv2 is enabled, revert to IGMPv2.
2141 		 */
2142 		if (!V_igmp_v2enable) {
2143 			CTR5(KTR_IGMPV3,
2144 			    "%s: transition from v%d -> v%d on %p(%s)",
2145 			    __func__, igi->igi_version, IGMP_VERSION_3,
2146 			    igi->igi_ifp, igi->igi_ifp->if_xname);
2147 			igi->igi_v2_timer = 0;
2148 			igi->igi_version = IGMP_VERSION_3;
2149 		} else {
2150 			--igi->igi_v2_timer;
2151 			if (igi->igi_version != IGMP_VERSION_2) {
2152 				CTR5(KTR_IGMPV3,
2153 				    "%s: transition from v%d -> v%d on %p(%s)",
2154 				    __func__, igi->igi_version, IGMP_VERSION_2,
2155 				    igi->igi_ifp, igi->igi_ifp->if_xname);
2156 				igi->igi_version = IGMP_VERSION_2;
2157 				igmp_v3_cancel_link_timers(igi);
2158 			}
2159 		}
2160 	} else if (igi->igi_v1_timer > 0) {
2161 		/*
2162 		 * IGMPv1 Querier Present timer running.
2163 		 * Stop IGMPv2 timer if running.
2164 		 *
2165 		 * If IGMPv1 was disabled since last timeout,
2166 		 * revert to IGMPv3.
2167 		 * If IGMPv1 is enabled, reset IGMPv2 timer if running.
2168 		 */
2169 		if (!V_igmp_v1enable) {
2170 			CTR5(KTR_IGMPV3,
2171 			    "%s: transition from v%d -> v%d on %p(%s)",
2172 			    __func__, igi->igi_version, IGMP_VERSION_3,
2173 			    igi->igi_ifp, igi->igi_ifp->if_xname);
2174 			igi->igi_v1_timer = 0;
2175 			igi->igi_version = IGMP_VERSION_3;
2176 		} else {
2177 			--igi->igi_v1_timer;
2178 		}
2179 		if (igi->igi_v2_timer > 0) {
2180 			CTR3(KTR_IGMPV3,
2181 			    "%s: cancel v2 timer on %p(%s)",
2182 			    __func__, igi->igi_ifp, igi->igi_ifp->if_xname);
2183 			igi->igi_v2_timer = 0;
2184 		}
2185 	}
2186 }
2187 
2188 /*
2189  * Global slowtimo handler.
2190  * VIMAGE: Timeout handlers are expected to service all vimages.
2191  */
2192 static struct callout igmpslow_callout;
2193 static void
2194 igmp_slowtimo(void *arg __unused)
2195 {
2196 	struct epoch_tracker et;
2197 	VNET_ITERATOR_DECL(vnet_iter);
2198 
2199 	NET_EPOCH_ENTER(et);
2200 	VNET_LIST_RLOCK_NOSLEEP();
2201 	VNET_FOREACH(vnet_iter) {
2202 		CURVNET_SET(vnet_iter);
2203 		igmp_slowtimo_vnet();
2204 		CURVNET_RESTORE();
2205 	}
2206 	VNET_LIST_RUNLOCK_NOSLEEP();
2207 	NET_EPOCH_EXIT(et);
2208 
2209 	callout_reset(&igmpslow_callout, hz / IGMP_SLOWHZ, igmp_slowtimo, NULL);
2210 }
2211 
2212 /*
2213  * Per-vnet slowtimo handler.
2214  */
2215 static void
2216 igmp_slowtimo_vnet(void)
2217 {
2218 	struct igmp_ifsoftc *igi;
2219 
2220 	IGMP_LOCK();
2221 
2222 	LIST_FOREACH(igi, &V_igi_head, igi_link) {
2223 		igmp_v1v2_process_querier_timers(igi);
2224 	}
2225 
2226 	IGMP_UNLOCK();
2227 }
2228 
2229 /*
2230  * Dispatch an IGMPv1/v2 host report or leave message.
2231  * These are always small enough to fit inside a single mbuf.
2232  */
2233 static int
2234 igmp_v1v2_queue_report(struct in_multi *inm, const int type)
2235 {
2236 	struct epoch_tracker 	et;
2237 	struct ifnet		*ifp;
2238 	struct igmp		*igmp;
2239 	struct ip		*ip;
2240 	struct mbuf		*m;
2241 
2242 	IN_MULTI_LIST_LOCK_ASSERT();
2243 	IGMP_LOCK_ASSERT();
2244 
2245 	ifp = inm->inm_ifp;
2246 
2247 	m = m_gethdr(M_NOWAIT, MT_DATA);
2248 	if (m == NULL)
2249 		return (ENOMEM);
2250 	M_ALIGN(m, sizeof(struct ip) + sizeof(struct igmp));
2251 
2252 	m->m_pkthdr.len = sizeof(struct ip) + sizeof(struct igmp);
2253 
2254 	m->m_data += sizeof(struct ip);
2255 	m->m_len = sizeof(struct igmp);
2256 
2257 	igmp = mtod(m, struct igmp *);
2258 	igmp->igmp_type = type;
2259 	igmp->igmp_code = 0;
2260 	igmp->igmp_group = inm->inm_addr;
2261 	igmp->igmp_cksum = 0;
2262 	igmp->igmp_cksum = in_cksum(m, sizeof(struct igmp));
2263 
2264 	m->m_data -= sizeof(struct ip);
2265 	m->m_len += sizeof(struct ip);
2266 
2267 	ip = mtod(m, struct ip *);
2268 	ip->ip_tos = 0;
2269 	ip->ip_len = htons(sizeof(struct ip) + sizeof(struct igmp));
2270 	ip->ip_off = 0;
2271 	ip->ip_p = IPPROTO_IGMP;
2272 	ip->ip_src.s_addr = INADDR_ANY;
2273 
2274 	if (type == IGMP_HOST_LEAVE_MESSAGE)
2275 		ip->ip_dst.s_addr = htonl(INADDR_ALLRTRS_GROUP);
2276 	else
2277 		ip->ip_dst = inm->inm_addr;
2278 
2279 	igmp_save_context(m, ifp);
2280 
2281 	m->m_flags |= M_IGMPV2;
2282 	if (inm->inm_igi->igi_flags & IGIF_LOOPBACK)
2283 		m->m_flags |= M_IGMP_LOOP;
2284 
2285 	CTR2(KTR_IGMPV3, "%s: netisr_dispatch(NETISR_IGMP, %p)", __func__, m);
2286 	NET_EPOCH_ENTER(et);
2287 	netisr_dispatch(NETISR_IGMP, m);
2288 	NET_EPOCH_EXIT(et);
2289 
2290 	return (0);
2291 }
2292 
2293 /*
2294  * Process a state change from the upper layer for the given IPv4 group.
2295  *
2296  * Each socket holds a reference on the in_multi in its own ip_moptions.
2297  * The socket layer will have made the necessary updates to.the group
2298  * state, it is now up to IGMP to issue a state change report if there
2299  * has been any change between T0 (when the last state-change was issued)
2300  * and T1 (now).
2301  *
2302  * We use the IGMPv3 state machine at group level. The IGMP module
2303  * however makes the decision as to which IGMP protocol version to speak.
2304  * A state change *from* INCLUDE {} always means an initial join.
2305  * A state change *to* INCLUDE {} always means a final leave.
2306  *
2307  * FUTURE: If IGIF_V3LITE is enabled for this interface, then we can
2308  * save ourselves a bunch of work; any exclusive mode groups need not
2309  * compute source filter lists.
2310  *
2311  * VIMAGE: curvnet should have been set by caller, as this routine
2312  * is called from the socket option handlers.
2313  */
2314 int
2315 igmp_change_state(struct in_multi *inm)
2316 {
2317 	struct igmp_ifsoftc *igi;
2318 	struct ifnet *ifp;
2319 	int error;
2320 
2321 	error = 0;
2322 	IN_MULTI_LOCK_ASSERT();
2323 	/*
2324 	 * Try to detect if the upper layer just asked us to change state
2325 	 * for an interface which has now gone away.
2326 	 */
2327 	KASSERT(inm->inm_ifma != NULL, ("%s: no ifma", __func__));
2328 	ifp = inm->inm_ifma->ifma_ifp;
2329 	if (ifp == NULL)
2330 		return (0);
2331 	/*
2332 	 * Sanity check that netinet's notion of ifp is the
2333 	 * same as net's.
2334 	 */
2335 	KASSERT(inm->inm_ifp == ifp, ("%s: bad ifp", __func__));
2336 
2337 	IGMP_LOCK();
2338 
2339 	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
2340 	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
2341 
2342 	/*
2343 	 * If we detect a state transition to or from MCAST_UNDEFINED
2344 	 * for this group, then we are starting or finishing an IGMP
2345 	 * life cycle for this group.
2346 	 */
2347 	if (inm->inm_st[1].iss_fmode != inm->inm_st[0].iss_fmode) {
2348 		CTR3(KTR_IGMPV3, "%s: inm transition %d -> %d", __func__,
2349 		    inm->inm_st[0].iss_fmode, inm->inm_st[1].iss_fmode);
2350 		if (inm->inm_st[0].iss_fmode == MCAST_UNDEFINED) {
2351 			CTR1(KTR_IGMPV3, "%s: initial join", __func__);
2352 			error = igmp_initial_join(inm, igi);
2353 			goto out_locked;
2354 		} else if (inm->inm_st[1].iss_fmode == MCAST_UNDEFINED) {
2355 			CTR1(KTR_IGMPV3, "%s: final leave", __func__);
2356 			igmp_final_leave(inm, igi);
2357 			goto out_locked;
2358 		}
2359 	} else {
2360 		CTR1(KTR_IGMPV3, "%s: filter set change", __func__);
2361 	}
2362 
2363 	error = igmp_handle_state_change(inm, igi);
2364 
2365 out_locked:
2366 	IGMP_UNLOCK();
2367 	return (error);
2368 }
2369 
2370 /*
2371  * Perform the initial join for an IGMP group.
2372  *
2373  * When joining a group:
2374  *  If the group should have its IGMP traffic suppressed, do nothing.
2375  *  IGMPv1 starts sending IGMPv1 host membership reports.
2376  *  IGMPv2 starts sending IGMPv2 host membership reports.
2377  *  IGMPv3 will schedule an IGMPv3 state-change report containing the
2378  *  initial state of the membership.
2379  */
2380 static int
2381 igmp_initial_join(struct in_multi *inm, struct igmp_ifsoftc *igi)
2382 {
2383 	struct ifnet		*ifp;
2384 	struct mbufq		*mq;
2385 	int			 error, retval, syncstates;
2386 
2387 	CTR4(KTR_IGMPV3, "%s: initial join 0x%08x on ifp %p(%s)", __func__,
2388 	    ntohl(inm->inm_addr.s_addr), inm->inm_ifp, inm->inm_ifp->if_xname);
2389 
2390 	error = 0;
2391 	syncstates = 1;
2392 
2393 	ifp = inm->inm_ifp;
2394 
2395 	IN_MULTI_LOCK_ASSERT();
2396 	IGMP_LOCK_ASSERT();
2397 
2398 	KASSERT(igi && igi->igi_ifp == ifp, ("%s: inconsistent ifp", __func__));
2399 
2400 	/*
2401 	 * Groups joined on loopback or marked as 'not reported',
2402 	 * e.g. 224.0.0.1, enter the IGMP_SILENT_MEMBER state and
2403 	 * are never reported in any IGMP protocol exchanges.
2404 	 * All other groups enter the appropriate IGMP state machine
2405 	 * for the version in use on this link.
2406 	 * A link marked as IGIF_SILENT causes IGMP to be completely
2407 	 * disabled for the link.
2408 	 */
2409 	if ((ifp->if_flags & IFF_LOOPBACK) ||
2410 	    (igi->igi_flags & IGIF_SILENT) ||
2411 	    !igmp_isgroupreported(inm->inm_addr)) {
2412 		CTR1(KTR_IGMPV3,
2413 "%s: not kicking state machine for silent group", __func__);
2414 		inm->inm_state = IGMP_SILENT_MEMBER;
2415 		inm->inm_timer = 0;
2416 	} else {
2417 		/*
2418 		 * Deal with overlapping in_multi lifecycle.
2419 		 * If this group was LEAVING, then make sure
2420 		 * we drop the reference we picked up to keep the
2421 		 * group around for the final INCLUDE {} enqueue.
2422 		 */
2423 		if (igi->igi_version == IGMP_VERSION_3 &&
2424 		    inm->inm_state == IGMP_LEAVING_MEMBER) {
2425 			MPASS(inm->inm_refcount > 1);
2426 			inm_rele_locked(NULL, inm);
2427 		}
2428 		inm->inm_state = IGMP_REPORTING_MEMBER;
2429 
2430 		switch (igi->igi_version) {
2431 		case IGMP_VERSION_1:
2432 		case IGMP_VERSION_2:
2433 			inm->inm_state = IGMP_IDLE_MEMBER;
2434 			error = igmp_v1v2_queue_report(inm,
2435 			    (igi->igi_version == IGMP_VERSION_2) ?
2436 			     IGMP_v2_HOST_MEMBERSHIP_REPORT :
2437 			     IGMP_v1_HOST_MEMBERSHIP_REPORT);
2438 			if (error == 0) {
2439 				inm->inm_timer = IGMP_RANDOM_DELAY(
2440 				    IGMP_V1V2_MAX_RI * IGMP_FASTHZ);
2441 				V_current_state_timers_running = 1;
2442 			}
2443 			break;
2444 
2445 		case IGMP_VERSION_3:
2446 			/*
2447 			 * Defer update of T0 to T1, until the first copy
2448 			 * of the state change has been transmitted.
2449 			 */
2450 			syncstates = 0;
2451 
2452 			/*
2453 			 * Immediately enqueue a State-Change Report for
2454 			 * this interface, freeing any previous reports.
2455 			 * Don't kick the timers if there is nothing to do,
2456 			 * or if an error occurred.
2457 			 */
2458 			mq = &inm->inm_scq;
2459 			mbufq_drain(mq);
2460 			retval = igmp_v3_enqueue_group_record(mq, inm, 1,
2461 			    0, 0);
2462 			CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
2463 			    __func__, retval);
2464 			if (retval <= 0) {
2465 				error = retval * -1;
2466 				break;
2467 			}
2468 
2469 			/*
2470 			 * Schedule transmission of pending state-change
2471 			 * report up to RV times for this link. The timer
2472 			 * will fire at the next igmp_fasttimo (~200ms),
2473 			 * giving us an opportunity to merge the reports.
2474 			 */
2475 			if (igi->igi_flags & IGIF_LOOPBACK) {
2476 				inm->inm_scrv = 1;
2477 			} else {
2478 				KASSERT(igi->igi_rv > 1,
2479 				   ("%s: invalid robustness %d", __func__,
2480 				    igi->igi_rv));
2481 				inm->inm_scrv = igi->igi_rv;
2482 			}
2483 			inm->inm_sctimer = 1;
2484 			V_state_change_timers_running = 1;
2485 
2486 			error = 0;
2487 			break;
2488 		}
2489 	}
2490 
2491 	/*
2492 	 * Only update the T0 state if state change is atomic,
2493 	 * i.e. we don't need to wait for a timer to fire before we
2494 	 * can consider the state change to have been communicated.
2495 	 */
2496 	if (syncstates) {
2497 		inm_commit(inm);
2498 		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2499 		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2500 	}
2501 
2502 	return (error);
2503 }
2504 
2505 /*
2506  * Issue an intermediate state change during the IGMP life-cycle.
2507  */
2508 static int
2509 igmp_handle_state_change(struct in_multi *inm, struct igmp_ifsoftc *igi)
2510 {
2511 	struct ifnet		*ifp;
2512 	int			 retval;
2513 
2514 	CTR4(KTR_IGMPV3, "%s: state change for 0x%08x on ifp %p(%s)", __func__,
2515 	    ntohl(inm->inm_addr.s_addr), inm->inm_ifp, inm->inm_ifp->if_xname);
2516 
2517 	ifp = inm->inm_ifp;
2518 
2519 	IN_MULTI_LIST_LOCK_ASSERT();
2520 	IGMP_LOCK_ASSERT();
2521 
2522 	KASSERT(igi && igi->igi_ifp == ifp, ("%s: inconsistent ifp", __func__));
2523 
2524 	if ((ifp->if_flags & IFF_LOOPBACK) ||
2525 	    (igi->igi_flags & IGIF_SILENT) ||
2526 	    !igmp_isgroupreported(inm->inm_addr) ||
2527 	    (igi->igi_version != IGMP_VERSION_3)) {
2528 		if (!igmp_isgroupreported(inm->inm_addr)) {
2529 			CTR1(KTR_IGMPV3,
2530 "%s: not kicking state machine for silent group", __func__);
2531 		}
2532 		CTR1(KTR_IGMPV3, "%s: nothing to do", __func__);
2533 		inm_commit(inm);
2534 		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2535 		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2536 		return (0);
2537 	}
2538 
2539 	mbufq_drain(&inm->inm_scq);
2540 
2541 	retval = igmp_v3_enqueue_group_record(&inm->inm_scq, inm, 1, 0, 0);
2542 	CTR2(KTR_IGMPV3, "%s: enqueue record = %d", __func__, retval);
2543 	if (retval <= 0)
2544 		return (-retval);
2545 
2546 	/*
2547 	 * If record(s) were enqueued, start the state-change
2548 	 * report timer for this group.
2549 	 */
2550 	inm->inm_scrv = ((igi->igi_flags & IGIF_LOOPBACK) ? 1 : igi->igi_rv);
2551 	inm->inm_sctimer = 1;
2552 	V_state_change_timers_running = 1;
2553 
2554 	return (0);
2555 }
2556 
2557 /*
2558  * Perform the final leave for an IGMP group.
2559  *
2560  * When leaving a group:
2561  *  IGMPv1 does nothing.
2562  *  IGMPv2 sends a host leave message, if and only if we are the reporter.
2563  *  IGMPv3 enqueues a state-change report containing a transition
2564  *  to INCLUDE {} for immediate transmission.
2565  */
2566 static void
2567 igmp_final_leave(struct in_multi *inm, struct igmp_ifsoftc *igi)
2568 {
2569 	int syncstates;
2570 
2571 	syncstates = 1;
2572 
2573 	CTR4(KTR_IGMPV3, "%s: final leave 0x%08x on ifp %p(%s)",
2574 	    __func__, ntohl(inm->inm_addr.s_addr), inm->inm_ifp,
2575 	    inm->inm_ifp->if_xname);
2576 
2577 	IN_MULTI_LIST_LOCK_ASSERT();
2578 	IGMP_LOCK_ASSERT();
2579 
2580 	switch (inm->inm_state) {
2581 	case IGMP_NOT_MEMBER:
2582 	case IGMP_SILENT_MEMBER:
2583 	case IGMP_LEAVING_MEMBER:
2584 		/* Already leaving or left; do nothing. */
2585 		CTR1(KTR_IGMPV3,
2586 "%s: not kicking state machine for silent group", __func__);
2587 		break;
2588 	case IGMP_REPORTING_MEMBER:
2589 	case IGMP_IDLE_MEMBER:
2590 	case IGMP_G_QUERY_PENDING_MEMBER:
2591 	case IGMP_SG_QUERY_PENDING_MEMBER:
2592 		if (igi->igi_version == IGMP_VERSION_2) {
2593 #ifdef INVARIANTS
2594 			if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER ||
2595 			    inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER)
2596 			panic("%s: IGMPv3 state reached, not IGMPv3 mode",
2597 			     __func__);
2598 #endif
2599 			igmp_v1v2_queue_report(inm, IGMP_HOST_LEAVE_MESSAGE);
2600 			inm->inm_state = IGMP_NOT_MEMBER;
2601 		} else if (igi->igi_version == IGMP_VERSION_3) {
2602 			/*
2603 			 * Stop group timer and all pending reports.
2604 			 * Immediately enqueue a state-change report
2605 			 * TO_IN {} to be sent on the next fast timeout,
2606 			 * giving us an opportunity to merge reports.
2607 			 */
2608 			mbufq_drain(&inm->inm_scq);
2609 			inm->inm_timer = 0;
2610 			if (igi->igi_flags & IGIF_LOOPBACK) {
2611 				inm->inm_scrv = 1;
2612 			} else {
2613 				inm->inm_scrv = igi->igi_rv;
2614 			}
2615 			CTR4(KTR_IGMPV3, "%s: Leaving 0x%08x/%s with %d "
2616 			    "pending retransmissions.", __func__,
2617 			    ntohl(inm->inm_addr.s_addr),
2618 			    inm->inm_ifp->if_xname, inm->inm_scrv);
2619 			if (inm->inm_scrv == 0) {
2620 				inm->inm_state = IGMP_NOT_MEMBER;
2621 				inm->inm_sctimer = 0;
2622 			} else {
2623 				int retval __unused;
2624 
2625 				inm_acquire_locked(inm);
2626 
2627 				retval = igmp_v3_enqueue_group_record(
2628 				    &inm->inm_scq, inm, 1, 0, 0);
2629 				KASSERT(retval != 0,
2630 				    ("%s: enqueue record = %d", __func__,
2631 				     retval));
2632 
2633 				inm->inm_state = IGMP_LEAVING_MEMBER;
2634 				inm->inm_sctimer = 1;
2635 				V_state_change_timers_running = 1;
2636 				syncstates = 0;
2637 			}
2638 			break;
2639 		}
2640 		break;
2641 	case IGMP_LAZY_MEMBER:
2642 	case IGMP_SLEEPING_MEMBER:
2643 	case IGMP_AWAKENING_MEMBER:
2644 		/* Our reports are suppressed; do nothing. */
2645 		break;
2646 	}
2647 
2648 	if (syncstates) {
2649 		inm_commit(inm);
2650 		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2651 		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2652 		inm->inm_st[1].iss_fmode = MCAST_UNDEFINED;
2653 		CTR3(KTR_IGMPV3, "%s: T1 now MCAST_UNDEFINED for 0x%08x/%s",
2654 		    __func__, ntohl(inm->inm_addr.s_addr),
2655 		    inm->inm_ifp->if_xname);
2656 	}
2657 }
2658 
2659 /*
2660  * Enqueue an IGMPv3 group record to the given output queue.
2661  *
2662  * XXX This function could do with having the allocation code
2663  * split out, and the multiple-tree-walks coalesced into a single
2664  * routine as has been done in igmp_v3_enqueue_filter_change().
2665  *
2666  * If is_state_change is zero, a current-state record is appended.
2667  * If is_state_change is non-zero, a state-change report is appended.
2668  *
2669  * If is_group_query is non-zero, an mbuf packet chain is allocated.
2670  * If is_group_query is zero, and if there is a packet with free space
2671  * at the tail of the queue, it will be appended to providing there
2672  * is enough free space.
2673  * Otherwise a new mbuf packet chain is allocated.
2674  *
2675  * If is_source_query is non-zero, each source is checked to see if
2676  * it was recorded for a Group-Source query, and will be omitted if
2677  * it is not both in-mode and recorded.
2678  *
2679  * The function will attempt to allocate leading space in the packet
2680  * for the IP/IGMP header to be prepended without fragmenting the chain.
2681  *
2682  * If successful the size of all data appended to the queue is returned,
2683  * otherwise an error code less than zero is returned, or zero if
2684  * no record(s) were appended.
2685  */
2686 static int
2687 igmp_v3_enqueue_group_record(struct mbufq *mq, struct in_multi *inm,
2688     const int is_state_change, const int is_group_query,
2689     const int is_source_query)
2690 {
2691 	struct igmp_grouprec	 ig;
2692 	struct igmp_grouprec	*pig;
2693 	struct ifnet		*ifp;
2694 	struct ip_msource	*ims, *nims;
2695 	struct mbuf		*m0, *m, *md;
2696 	int			 is_filter_list_change;
2697 	int			 minrec0len, m0srcs, msrcs, nbytes, off;
2698 	int			 record_has_sources;
2699 	int			 now;
2700 	int			 type;
2701 	in_addr_t		 naddr;
2702 	uint8_t			 mode;
2703 
2704 	IN_MULTI_LIST_LOCK_ASSERT();
2705 
2706 	ifp = inm->inm_ifp;
2707 	is_filter_list_change = 0;
2708 	m = NULL;
2709 	m0 = NULL;
2710 	m0srcs = 0;
2711 	msrcs = 0;
2712 	nbytes = 0;
2713 	nims = NULL;
2714 	record_has_sources = 1;
2715 	pig = NULL;
2716 	type = IGMP_DO_NOTHING;
2717 	mode = inm->inm_st[1].iss_fmode;
2718 
2719 	/*
2720 	 * If we did not transition out of ASM mode during t0->t1,
2721 	 * and there are no source nodes to process, we can skip
2722 	 * the generation of source records.
2723 	 */
2724 	if (inm->inm_st[0].iss_asm > 0 && inm->inm_st[1].iss_asm > 0 &&
2725 	    inm->inm_nsrc == 0)
2726 		record_has_sources = 0;
2727 
2728 	if (is_state_change) {
2729 		/*
2730 		 * Queue a state change record.
2731 		 * If the mode did not change, and there are non-ASM
2732 		 * listeners or source filters present,
2733 		 * we potentially need to issue two records for the group.
2734 		 * If we are transitioning to MCAST_UNDEFINED, we need
2735 		 * not send any sources.
2736 		 * If there are ASM listeners, and there was no filter
2737 		 * mode transition of any kind, do nothing.
2738 		 */
2739 		if (mode != inm->inm_st[0].iss_fmode) {
2740 			if (mode == MCAST_EXCLUDE) {
2741 				CTR1(KTR_IGMPV3, "%s: change to EXCLUDE",
2742 				    __func__);
2743 				type = IGMP_CHANGE_TO_EXCLUDE_MODE;
2744 			} else {
2745 				CTR1(KTR_IGMPV3, "%s: change to INCLUDE",
2746 				    __func__);
2747 				type = IGMP_CHANGE_TO_INCLUDE_MODE;
2748 				if (mode == MCAST_UNDEFINED)
2749 					record_has_sources = 0;
2750 			}
2751 		} else {
2752 			if (record_has_sources) {
2753 				is_filter_list_change = 1;
2754 			} else {
2755 				type = IGMP_DO_NOTHING;
2756 			}
2757 		}
2758 	} else {
2759 		/*
2760 		 * Queue a current state record.
2761 		 */
2762 		if (mode == MCAST_EXCLUDE) {
2763 			type = IGMP_MODE_IS_EXCLUDE;
2764 		} else if (mode == MCAST_INCLUDE) {
2765 			type = IGMP_MODE_IS_INCLUDE;
2766 			KASSERT(inm->inm_st[1].iss_asm == 0,
2767 			    ("%s: inm %p is INCLUDE but ASM count is %d",
2768 			     __func__, inm, inm->inm_st[1].iss_asm));
2769 		}
2770 	}
2771 
2772 	/*
2773 	 * Generate the filter list changes using a separate function.
2774 	 */
2775 	if (is_filter_list_change)
2776 		return (igmp_v3_enqueue_filter_change(mq, inm));
2777 
2778 	if (type == IGMP_DO_NOTHING) {
2779 		CTR3(KTR_IGMPV3, "%s: nothing to do for 0x%08x/%s", __func__,
2780 		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2781 		return (0);
2782 	}
2783 
2784 	/*
2785 	 * If any sources are present, we must be able to fit at least
2786 	 * one in the trailing space of the tail packet's mbuf,
2787 	 * ideally more.
2788 	 */
2789 	minrec0len = sizeof(struct igmp_grouprec);
2790 	if (record_has_sources)
2791 		minrec0len += sizeof(in_addr_t);
2792 
2793 	CTR4(KTR_IGMPV3, "%s: queueing %s for 0x%08x/%s", __func__,
2794 	    igmp_rec_type_to_str(type), ntohl(inm->inm_addr.s_addr),
2795 	    inm->inm_ifp->if_xname);
2796 
2797 	/*
2798 	 * Check if we have a packet in the tail of the queue for this
2799 	 * group into which the first group record for this group will fit.
2800 	 * Otherwise allocate a new packet.
2801 	 * Always allocate leading space for IP+RA_OPT+IGMP+REPORT.
2802 	 * Note: Group records for G/GSR query responses MUST be sent
2803 	 * in their own packet.
2804 	 */
2805 	m0 = mbufq_last(mq);
2806 	if (!is_group_query &&
2807 	    m0 != NULL &&
2808 	    (m0->m_pkthdr.vt_nrecs + 1 <= IGMP_V3_REPORT_MAXRECS) &&
2809 	    (m0->m_pkthdr.len + minrec0len) <
2810 	     (ifp->if_mtu - IGMP_LEADINGSPACE)) {
2811 		m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
2812 			    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2813 		m = m0;
2814 		CTR1(KTR_IGMPV3, "%s: use existing packet", __func__);
2815 	} else {
2816 		if (mbufq_full(mq)) {
2817 			CTR1(KTR_IGMPV3, "%s: outbound queue full", __func__);
2818 			return (-ENOMEM);
2819 		}
2820 		m = NULL;
2821 		m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
2822 		    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2823 		if (!is_state_change && !is_group_query) {
2824 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2825 			if (m)
2826 				m->m_data += IGMP_LEADINGSPACE;
2827 		}
2828 		if (m == NULL) {
2829 			m = m_gethdr(M_NOWAIT, MT_DATA);
2830 			if (m)
2831 				M_ALIGN(m, IGMP_LEADINGSPACE);
2832 		}
2833 		if (m == NULL)
2834 			return (-ENOMEM);
2835 
2836 		igmp_save_context(m, ifp);
2837 
2838 		CTR1(KTR_IGMPV3, "%s: allocated first packet", __func__);
2839 	}
2840 
2841 	/*
2842 	 * Append group record.
2843 	 * If we have sources, we don't know how many yet.
2844 	 */
2845 	ig.ig_type = type;
2846 	ig.ig_datalen = 0;
2847 	ig.ig_numsrc = 0;
2848 	ig.ig_group = inm->inm_addr;
2849 	if (!m_append(m, sizeof(struct igmp_grouprec), (void *)&ig)) {
2850 		if (m != m0)
2851 			m_freem(m);
2852 		CTR1(KTR_IGMPV3, "%s: m_append() failed.", __func__);
2853 		return (-ENOMEM);
2854 	}
2855 	nbytes += sizeof(struct igmp_grouprec);
2856 
2857 	/*
2858 	 * Append as many sources as will fit in the first packet.
2859 	 * If we are appending to a new packet, the chain allocation
2860 	 * may potentially use clusters; use m_getptr() in this case.
2861 	 * If we are appending to an existing packet, we need to obtain
2862 	 * a pointer to the group record after m_append(), in case a new
2863 	 * mbuf was allocated.
2864 	 * Only append sources which are in-mode at t1. If we are
2865 	 * transitioning to MCAST_UNDEFINED state on the group, do not
2866 	 * include source entries.
2867 	 * Only report recorded sources in our filter set when responding
2868 	 * to a group-source query.
2869 	 */
2870 	if (record_has_sources) {
2871 		if (m == m0) {
2872 			md = m_last(m);
2873 			pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) +
2874 			    md->m_len - nbytes);
2875 		} else {
2876 			md = m_getptr(m, 0, &off);
2877 			pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) +
2878 			    off);
2879 		}
2880 		msrcs = 0;
2881 		RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, nims) {
2882 			CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2883 			    ims->ims_haddr);
2884 			now = ims_get_mode(inm, ims, 1);
2885 			CTR2(KTR_IGMPV3, "%s: node is %d", __func__, now);
2886 			if ((now != mode) ||
2887 			    (now == mode && mode == MCAST_UNDEFINED)) {
2888 				CTR1(KTR_IGMPV3, "%s: skip node", __func__);
2889 				continue;
2890 			}
2891 			if (is_source_query && ims->ims_stp == 0) {
2892 				CTR1(KTR_IGMPV3, "%s: skip unrecorded node",
2893 				    __func__);
2894 				continue;
2895 			}
2896 			CTR1(KTR_IGMPV3, "%s: append node", __func__);
2897 			naddr = htonl(ims->ims_haddr);
2898 			if (!m_append(m, sizeof(in_addr_t), (void *)&naddr)) {
2899 				if (m != m0)
2900 					m_freem(m);
2901 				CTR1(KTR_IGMPV3, "%s: m_append() failed.",
2902 				    __func__);
2903 				return (-ENOMEM);
2904 			}
2905 			nbytes += sizeof(in_addr_t);
2906 			++msrcs;
2907 			if (msrcs == m0srcs)
2908 				break;
2909 		}
2910 		CTR2(KTR_IGMPV3, "%s: msrcs is %d this packet", __func__,
2911 		    msrcs);
2912 		pig->ig_numsrc = htons(msrcs);
2913 		nbytes += (msrcs * sizeof(in_addr_t));
2914 	}
2915 
2916 	if (is_source_query && msrcs == 0) {
2917 		CTR1(KTR_IGMPV3, "%s: no recorded sources to report", __func__);
2918 		if (m != m0)
2919 			m_freem(m);
2920 		return (0);
2921 	}
2922 
2923 	/*
2924 	 * We are good to go with first packet.
2925 	 */
2926 	if (m != m0) {
2927 		CTR1(KTR_IGMPV3, "%s: enqueueing first packet", __func__);
2928 		m->m_pkthdr.vt_nrecs = 1;
2929 		mbufq_enqueue(mq, m);
2930 	} else
2931 		m->m_pkthdr.vt_nrecs++;
2932 
2933 	/*
2934 	 * No further work needed if no source list in packet(s).
2935 	 */
2936 	if (!record_has_sources)
2937 		return (nbytes);
2938 
2939 	/*
2940 	 * Whilst sources remain to be announced, we need to allocate
2941 	 * a new packet and fill out as many sources as will fit.
2942 	 * Always try for a cluster first.
2943 	 */
2944 	while (nims != NULL) {
2945 		if (mbufq_full(mq)) {
2946 			CTR1(KTR_IGMPV3, "%s: outbound queue full", __func__);
2947 			return (-ENOMEM);
2948 		}
2949 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2950 		if (m)
2951 			m->m_data += IGMP_LEADINGSPACE;
2952 		if (m == NULL) {
2953 			m = m_gethdr(M_NOWAIT, MT_DATA);
2954 			if (m)
2955 				M_ALIGN(m, IGMP_LEADINGSPACE);
2956 		}
2957 		if (m == NULL)
2958 			return (-ENOMEM);
2959 		igmp_save_context(m, ifp);
2960 		md = m_getptr(m, 0, &off);
2961 		pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) + off);
2962 		CTR1(KTR_IGMPV3, "%s: allocated next packet", __func__);
2963 
2964 		if (!m_append(m, sizeof(struct igmp_grouprec), (void *)&ig)) {
2965 			if (m != m0)
2966 				m_freem(m);
2967 			CTR1(KTR_IGMPV3, "%s: m_append() failed.", __func__);
2968 			return (-ENOMEM);
2969 		}
2970 		m->m_pkthdr.vt_nrecs = 1;
2971 		nbytes += sizeof(struct igmp_grouprec);
2972 
2973 		m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
2974 		    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2975 
2976 		msrcs = 0;
2977 		RB_FOREACH_FROM(ims, ip_msource_tree, nims) {
2978 			CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2979 			    ims->ims_haddr);
2980 			now = ims_get_mode(inm, ims, 1);
2981 			if ((now != mode) ||
2982 			    (now == mode && mode == MCAST_UNDEFINED)) {
2983 				CTR1(KTR_IGMPV3, "%s: skip node", __func__);
2984 				continue;
2985 			}
2986 			if (is_source_query && ims->ims_stp == 0) {
2987 				CTR1(KTR_IGMPV3, "%s: skip unrecorded node",
2988 				    __func__);
2989 				continue;
2990 			}
2991 			CTR1(KTR_IGMPV3, "%s: append node", __func__);
2992 			naddr = htonl(ims->ims_haddr);
2993 			if (!m_append(m, sizeof(in_addr_t), (void *)&naddr)) {
2994 				if (m != m0)
2995 					m_freem(m);
2996 				CTR1(KTR_IGMPV3, "%s: m_append() failed.",
2997 				    __func__);
2998 				return (-ENOMEM);
2999 			}
3000 			++msrcs;
3001 			if (msrcs == m0srcs)
3002 				break;
3003 		}
3004 		pig->ig_numsrc = htons(msrcs);
3005 		nbytes += (msrcs * sizeof(in_addr_t));
3006 
3007 		CTR1(KTR_IGMPV3, "%s: enqueueing next packet", __func__);
3008 		mbufq_enqueue(mq, m);
3009 	}
3010 
3011 	return (nbytes);
3012 }
3013 
3014 /*
3015  * Type used to mark record pass completion.
3016  * We exploit the fact we can cast to this easily from the
3017  * current filter modes on each ip_msource node.
3018  */
3019 typedef enum {
3020 	REC_NONE = 0x00,	/* MCAST_UNDEFINED */
3021 	REC_ALLOW = 0x01,	/* MCAST_INCLUDE */
3022 	REC_BLOCK = 0x02,	/* MCAST_EXCLUDE */
3023 	REC_FULL = REC_ALLOW | REC_BLOCK
3024 } rectype_t;
3025 
3026 /*
3027  * Enqueue an IGMPv3 filter list change to the given output queue.
3028  *
3029  * Source list filter state is held in an RB-tree. When the filter list
3030  * for a group is changed without changing its mode, we need to compute
3031  * the deltas between T0 and T1 for each source in the filter set,
3032  * and enqueue the appropriate ALLOW_NEW/BLOCK_OLD records.
3033  *
3034  * As we may potentially queue two record types, and the entire R-B tree
3035  * needs to be walked at once, we break this out into its own function
3036  * so we can generate a tightly packed queue of packets.
3037  *
3038  * XXX This could be written to only use one tree walk, although that makes
3039  * serializing into the mbuf chains a bit harder. For now we do two walks
3040  * which makes things easier on us, and it may or may not be harder on
3041  * the L2 cache.
3042  *
3043  * If successful the size of all data appended to the queue is returned,
3044  * otherwise an error code less than zero is returned, or zero if
3045  * no record(s) were appended.
3046  */
3047 static int
3048 igmp_v3_enqueue_filter_change(struct mbufq *mq, struct in_multi *inm)
3049 {
3050 	static const int MINRECLEN =
3051 	    sizeof(struct igmp_grouprec) + sizeof(in_addr_t);
3052 	struct ifnet		*ifp;
3053 	struct igmp_grouprec	 ig;
3054 	struct igmp_grouprec	*pig;
3055 	struct ip_msource	*ims, *nims;
3056 	struct mbuf		*m, *m0, *md;
3057 	in_addr_t		 naddr;
3058 	int			 m0srcs, nbytes, npbytes, off, rsrcs, schanged;
3059 #ifdef KTR
3060 	int			 nallow, nblock;
3061 #endif
3062 	uint8_t			 mode, now, then;
3063 	rectype_t		 crt, drt, nrt;
3064 
3065 	IN_MULTI_LIST_LOCK_ASSERT();
3066 
3067 	if (inm->inm_nsrc == 0 ||
3068 	    (inm->inm_st[0].iss_asm > 0 && inm->inm_st[1].iss_asm > 0))
3069 		return (0);
3070 
3071 	ifp = inm->inm_ifp;			/* interface */
3072 	mode = inm->inm_st[1].iss_fmode;	/* filter mode at t1 */
3073 	crt = REC_NONE;	/* current group record type */
3074 	drt = REC_NONE;	/* mask of completed group record types */
3075 	nrt = REC_NONE;	/* record type for current node */
3076 	m0srcs = 0;	/* # source which will fit in current mbuf chain */
3077 	nbytes = 0;	/* # of bytes appended to group's state-change queue */
3078 	npbytes = 0;	/* # of bytes appended this packet */
3079 	rsrcs = 0;	/* # sources encoded in current record */
3080 	schanged = 0;	/* # nodes encoded in overall filter change */
3081 #ifdef KTR
3082 	nallow = 0;	/* # of source entries in ALLOW_NEW */
3083 	nblock = 0;	/* # of source entries in BLOCK_OLD */
3084 #endif
3085 	nims = NULL;	/* next tree node pointer */
3086 
3087 	/*
3088 	 * For each possible filter record mode.
3089 	 * The first kind of source we encounter tells us which
3090 	 * is the first kind of record we start appending.
3091 	 * If a node transitioned to UNDEFINED at t1, its mode is treated
3092 	 * as the inverse of the group's filter mode.
3093 	 */
3094 	while (drt != REC_FULL) {
3095 		do {
3096 			m0 = mbufq_last(mq);
3097 			if (m0 != NULL &&
3098 			    (m0->m_pkthdr.vt_nrecs + 1 <=
3099 			     IGMP_V3_REPORT_MAXRECS) &&
3100 			    (m0->m_pkthdr.len + MINRECLEN) <
3101 			     (ifp->if_mtu - IGMP_LEADINGSPACE)) {
3102 				m = m0;
3103 				m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
3104 					    sizeof(struct igmp_grouprec)) /
3105 				    sizeof(in_addr_t);
3106 				CTR1(KTR_IGMPV3,
3107 				    "%s: use previous packet", __func__);
3108 			} else {
3109 				m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
3110 				if (m)
3111 					m->m_data += IGMP_LEADINGSPACE;
3112 				if (m == NULL) {
3113 					m = m_gethdr(M_NOWAIT, MT_DATA);
3114 					if (m)
3115 						M_ALIGN(m, IGMP_LEADINGSPACE);
3116 				}
3117 				if (m == NULL) {
3118 					CTR1(KTR_IGMPV3,
3119 					    "%s: m_get*() failed", __func__);
3120 					return (-ENOMEM);
3121 				}
3122 				m->m_pkthdr.vt_nrecs = 0;
3123 				igmp_save_context(m, ifp);
3124 				m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
3125 				    sizeof(struct igmp_grouprec)) /
3126 				    sizeof(in_addr_t);
3127 				npbytes = 0;
3128 				CTR1(KTR_IGMPV3,
3129 				    "%s: allocated new packet", __func__);
3130 			}
3131 			/*
3132 			 * Append the IGMP group record header to the
3133 			 * current packet's data area.
3134 			 * Recalculate pointer to free space for next
3135 			 * group record, in case m_append() allocated
3136 			 * a new mbuf or cluster.
3137 			 */
3138 			memset(&ig, 0, sizeof(ig));
3139 			ig.ig_group = inm->inm_addr;
3140 			if (!m_append(m, sizeof(ig), (void *)&ig)) {
3141 				if (m != m0)
3142 					m_freem(m);
3143 				CTR1(KTR_IGMPV3,
3144 				    "%s: m_append() failed", __func__);
3145 				return (-ENOMEM);
3146 			}
3147 			npbytes += sizeof(struct igmp_grouprec);
3148 			if (m != m0) {
3149 				/* new packet; offset in c hain */
3150 				md = m_getptr(m, npbytes -
3151 				    sizeof(struct igmp_grouprec), &off);
3152 				pig = (struct igmp_grouprec *)(mtod(md,
3153 				    uint8_t *) + off);
3154 			} else {
3155 				/* current packet; offset from last append */
3156 				md = m_last(m);
3157 				pig = (struct igmp_grouprec *)(mtod(md,
3158 				    uint8_t *) + md->m_len -
3159 				    sizeof(struct igmp_grouprec));
3160 			}
3161 			/*
3162 			 * Begin walking the tree for this record type
3163 			 * pass, or continue from where we left off
3164 			 * previously if we had to allocate a new packet.
3165 			 * Only report deltas in-mode at t1.
3166 			 * We need not report included sources as allowed
3167 			 * if we are in inclusive mode on the group,
3168 			 * however the converse is not true.
3169 			 */
3170 			rsrcs = 0;
3171 			if (nims == NULL)
3172 				nims = RB_MIN(ip_msource_tree, &inm->inm_srcs);
3173 			RB_FOREACH_FROM(ims, ip_msource_tree, nims) {
3174 				CTR2(KTR_IGMPV3, "%s: visit node 0x%08x",
3175 				    __func__, ims->ims_haddr);
3176 				now = ims_get_mode(inm, ims, 1);
3177 				then = ims_get_mode(inm, ims, 0);
3178 				CTR3(KTR_IGMPV3, "%s: mode: t0 %d, t1 %d",
3179 				    __func__, then, now);
3180 				if (now == then) {
3181 					CTR1(KTR_IGMPV3,
3182 					    "%s: skip unchanged", __func__);
3183 					continue;
3184 				}
3185 				if (mode == MCAST_EXCLUDE &&
3186 				    now == MCAST_INCLUDE) {
3187 					CTR1(KTR_IGMPV3,
3188 					    "%s: skip IN src on EX group",
3189 					    __func__);
3190 					continue;
3191 				}
3192 				nrt = (rectype_t)now;
3193 				if (nrt == REC_NONE)
3194 					nrt = (rectype_t)(~mode & REC_FULL);
3195 				if (schanged++ == 0) {
3196 					crt = nrt;
3197 				} else if (crt != nrt)
3198 					continue;
3199 				naddr = htonl(ims->ims_haddr);
3200 				if (!m_append(m, sizeof(in_addr_t),
3201 				    (void *)&naddr)) {
3202 					if (m != m0)
3203 						m_freem(m);
3204 					CTR1(KTR_IGMPV3,
3205 					    "%s: m_append() failed", __func__);
3206 					return (-ENOMEM);
3207 				}
3208 #ifdef KTR
3209 				nallow += !!(crt == REC_ALLOW);
3210 				nblock += !!(crt == REC_BLOCK);
3211 #endif
3212 				if (++rsrcs == m0srcs)
3213 					break;
3214 			}
3215 			/*
3216 			 * If we did not append any tree nodes on this
3217 			 * pass, back out of allocations.
3218 			 */
3219 			if (rsrcs == 0) {
3220 				npbytes -= sizeof(struct igmp_grouprec);
3221 				if (m != m0) {
3222 					CTR1(KTR_IGMPV3,
3223 					    "%s: m_free(m)", __func__);
3224 					m_freem(m);
3225 				} else {
3226 					CTR1(KTR_IGMPV3,
3227 					    "%s: m_adj(m, -ig)", __func__);
3228 					m_adj(m, -((int)sizeof(
3229 					    struct igmp_grouprec)));
3230 				}
3231 				continue;
3232 			}
3233 			npbytes += (rsrcs * sizeof(in_addr_t));
3234 			if (crt == REC_ALLOW)
3235 				pig->ig_type = IGMP_ALLOW_NEW_SOURCES;
3236 			else if (crt == REC_BLOCK)
3237 				pig->ig_type = IGMP_BLOCK_OLD_SOURCES;
3238 			pig->ig_numsrc = htons(rsrcs);
3239 			/*
3240 			 * Count the new group record, and enqueue this
3241 			 * packet if it wasn't already queued.
3242 			 */
3243 			m->m_pkthdr.vt_nrecs++;
3244 			if (m != m0)
3245 				mbufq_enqueue(mq, m);
3246 			nbytes += npbytes;
3247 		} while (nims != NULL);
3248 		drt |= crt;
3249 		crt = (~crt & REC_FULL);
3250 	}
3251 
3252 	CTR3(KTR_IGMPV3, "%s: queued %d ALLOW_NEW, %d BLOCK_OLD", __func__,
3253 	    nallow, nblock);
3254 
3255 	return (nbytes);
3256 }
3257 
3258 static int
3259 igmp_v3_merge_state_changes(struct in_multi *inm, struct mbufq *scq)
3260 {
3261 	struct mbufq	*gq;
3262 	struct mbuf	*m;		/* pending state-change */
3263 	struct mbuf	*m0;		/* copy of pending state-change */
3264 	struct mbuf	*mt;		/* last state-change in packet */
3265 	int		 docopy, domerge;
3266 	u_int		 recslen;
3267 
3268 	docopy = 0;
3269 	domerge = 0;
3270 	recslen = 0;
3271 
3272 	IN_MULTI_LIST_LOCK_ASSERT();
3273 	IGMP_LOCK_ASSERT();
3274 
3275 	/*
3276 	 * If there are further pending retransmissions, make a writable
3277 	 * copy of each queued state-change message before merging.
3278 	 */
3279 	if (inm->inm_scrv > 0)
3280 		docopy = 1;
3281 
3282 	gq = &inm->inm_scq;
3283 #ifdef KTR
3284 	if (mbufq_first(gq) == NULL) {
3285 		CTR2(KTR_IGMPV3, "%s: WARNING: queue for inm %p is empty",
3286 		    __func__, inm);
3287 	}
3288 #endif
3289 
3290 	m = mbufq_first(gq);
3291 	while (m != NULL) {
3292 		/*
3293 		 * Only merge the report into the current packet if
3294 		 * there is sufficient space to do so; an IGMPv3 report
3295 		 * packet may only contain 65,535 group records.
3296 		 * Always use a simple mbuf chain concatentation to do this,
3297 		 * as large state changes for single groups may have
3298 		 * allocated clusters.
3299 		 */
3300 		domerge = 0;
3301 		mt = mbufq_last(scq);
3302 		if (mt != NULL) {
3303 			recslen = m_length(m, NULL);
3304 
3305 			if ((mt->m_pkthdr.vt_nrecs +
3306 			    m->m_pkthdr.vt_nrecs <=
3307 			    IGMP_V3_REPORT_MAXRECS) &&
3308 			    (mt->m_pkthdr.len + recslen <=
3309 			    (inm->inm_ifp->if_mtu - IGMP_LEADINGSPACE)))
3310 				domerge = 1;
3311 		}
3312 
3313 		if (!domerge && mbufq_full(gq)) {
3314 			CTR2(KTR_IGMPV3,
3315 			    "%s: outbound queue full, skipping whole packet %p",
3316 			    __func__, m);
3317 			mt = m->m_nextpkt;
3318 			if (!docopy)
3319 				m_freem(m);
3320 			m = mt;
3321 			continue;
3322 		}
3323 
3324 		if (!docopy) {
3325 			CTR2(KTR_IGMPV3, "%s: dequeueing %p", __func__, m);
3326 			m0 = mbufq_dequeue(gq);
3327 			m = m0->m_nextpkt;
3328 		} else {
3329 			CTR2(KTR_IGMPV3, "%s: copying %p", __func__, m);
3330 			m0 = m_dup(m, M_NOWAIT);
3331 			if (m0 == NULL)
3332 				return (ENOMEM);
3333 			m0->m_nextpkt = NULL;
3334 			m = m->m_nextpkt;
3335 		}
3336 
3337 		if (!domerge) {
3338 			CTR3(KTR_IGMPV3, "%s: queueing %p to scq %p)",
3339 			    __func__, m0, scq);
3340 			mbufq_enqueue(scq, m0);
3341 		} else {
3342 			struct mbuf *mtl;	/* last mbuf of packet mt */
3343 
3344 			CTR3(KTR_IGMPV3, "%s: merging %p with scq tail %p)",
3345 			    __func__, m0, mt);
3346 
3347 			mtl = m_last(mt);
3348 			m0->m_flags &= ~M_PKTHDR;
3349 			mt->m_pkthdr.len += recslen;
3350 			mt->m_pkthdr.vt_nrecs +=
3351 			    m0->m_pkthdr.vt_nrecs;
3352 
3353 			mtl->m_next = m0;
3354 		}
3355 	}
3356 
3357 	return (0);
3358 }
3359 
3360 /*
3361  * Respond to a pending IGMPv3 General Query.
3362  */
3363 static void
3364 igmp_v3_dispatch_general_query(struct igmp_ifsoftc *igi)
3365 {
3366 	struct ifmultiaddr	*ifma;
3367 	struct ifnet		*ifp;
3368 	struct in_multi		*inm;
3369 	int			 retval __unused, loop;
3370 
3371 	IN_MULTI_LIST_LOCK_ASSERT();
3372 	IGMP_LOCK_ASSERT();
3373 	NET_EPOCH_ASSERT();
3374 
3375 	KASSERT(igi->igi_version == IGMP_VERSION_3,
3376 	    ("%s: called when version %d", __func__, igi->igi_version));
3377 
3378 	/*
3379 	 * Check that there are some packets queued. If so, send them first.
3380 	 * For large number of groups the reply to general query can take
3381 	 * many packets, we should finish sending them before starting of
3382 	 * queuing the new reply.
3383 	 */
3384 	if (mbufq_len(&igi->igi_gq) != 0)
3385 		goto send;
3386 
3387 	ifp = igi->igi_ifp;
3388 
3389 	CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3390 		inm = inm_ifmultiaddr_get_inm(ifma);
3391 		if (inm == NULL)
3392 			continue;
3393 		KASSERT(ifp == inm->inm_ifp,
3394 		    ("%s: inconsistent ifp", __func__));
3395 
3396 		switch (inm->inm_state) {
3397 		case IGMP_NOT_MEMBER:
3398 		case IGMP_SILENT_MEMBER:
3399 			break;
3400 		case IGMP_REPORTING_MEMBER:
3401 		case IGMP_IDLE_MEMBER:
3402 		case IGMP_LAZY_MEMBER:
3403 		case IGMP_SLEEPING_MEMBER:
3404 		case IGMP_AWAKENING_MEMBER:
3405 			inm->inm_state = IGMP_REPORTING_MEMBER;
3406 			retval = igmp_v3_enqueue_group_record(&igi->igi_gq,
3407 			    inm, 0, 0, 0);
3408 			CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
3409 			    __func__, retval);
3410 			break;
3411 		case IGMP_G_QUERY_PENDING_MEMBER:
3412 		case IGMP_SG_QUERY_PENDING_MEMBER:
3413 		case IGMP_LEAVING_MEMBER:
3414 			break;
3415 		}
3416 	}
3417 
3418 send:
3419 	loop = (igi->igi_flags & IGIF_LOOPBACK) ? 1 : 0;
3420 	igmp_dispatch_queue(&igi->igi_gq, IGMP_MAX_RESPONSE_BURST, loop);
3421 
3422 	/*
3423 	 * Slew transmission of bursts over 500ms intervals.
3424 	 */
3425 	if (mbufq_first(&igi->igi_gq) != NULL) {
3426 		igi->igi_v3_timer = 1 + IGMP_RANDOM_DELAY(
3427 		    IGMP_RESPONSE_BURST_INTERVAL);
3428 		V_interface_timers_running = 1;
3429 	}
3430 }
3431 
3432 /*
3433  * Transmit the next pending IGMP message in the output queue.
3434  *
3435  * We get called from netisr_processqueue(). A mutex private to igmpoq
3436  * will be acquired and released around this routine.
3437  *
3438  * VIMAGE: Needs to store/restore vnet pointer on a per-mbuf-chain basis.
3439  * MRT: Nothing needs to be done, as IGMP traffic is always local to
3440  * a link and uses a link-scope multicast address.
3441  */
3442 static void
3443 igmp_intr(struct mbuf *m)
3444 {
3445 	struct ip_moptions	 imo;
3446 	struct ifnet		*ifp;
3447 	struct mbuf		*ipopts, *m0;
3448 	int			 error;
3449 	uint32_t		 ifindex;
3450 
3451 	CTR2(KTR_IGMPV3, "%s: transmit %p", __func__, m);
3452 
3453 	/*
3454 	 * Set VNET image pointer from enqueued mbuf chain
3455 	 * before doing anything else. Whilst we use interface
3456 	 * indexes to guard against interface detach, they are
3457 	 * unique to each VIMAGE and must be retrieved.
3458 	 */
3459 	CURVNET_SET((struct vnet *)(m->m_pkthdr.PH_loc.ptr));
3460 	ifindex = igmp_restore_context(m);
3461 
3462 	/*
3463 	 * Check if the ifnet still exists. This limits the scope of
3464 	 * any race in the absence of a global ifp lock for low cost
3465 	 * (an array lookup).
3466 	 */
3467 	ifp = ifnet_byindex(ifindex);
3468 	if (ifp == NULL) {
3469 		CTR3(KTR_IGMPV3, "%s: dropped %p as ifindex %u went away.",
3470 		    __func__, m, ifindex);
3471 		m_freem(m);
3472 		IPSTAT_INC(ips_noroute);
3473 		goto out;
3474 	}
3475 
3476 	ipopts = V_igmp_sendra ? m_raopt : NULL;
3477 
3478 	imo.imo_multicast_ttl  = 1;
3479 	imo.imo_multicast_vif  = -1;
3480 	imo.imo_multicast_loop = (V_ip_mrouter != NULL);
3481 
3482 	/*
3483 	 * If the user requested that IGMP traffic be explicitly
3484 	 * redirected to the loopback interface (e.g. they are running a
3485 	 * MANET interface and the routing protocol needs to see the
3486 	 * updates), handle this now.
3487 	 */
3488 	if (m->m_flags & M_IGMP_LOOP)
3489 		imo.imo_multicast_ifp = V_loif;
3490 	else
3491 		imo.imo_multicast_ifp = ifp;
3492 
3493 	if (m->m_flags & M_IGMPV2) {
3494 		m0 = m;
3495 	} else {
3496 		m0 = igmp_v3_encap_report(ifp, m);
3497 		if (m0 == NULL) {
3498 			CTR2(KTR_IGMPV3, "%s: dropped %p", __func__, m);
3499 			m_freem(m);
3500 			IPSTAT_INC(ips_odropped);
3501 			goto out;
3502 		}
3503 	}
3504 
3505 	igmp_scrub_context(m0);
3506 	m_clrprotoflags(m);
3507 	m0->m_pkthdr.rcvif = V_loif;
3508 #ifdef MAC
3509 	mac_netinet_igmp_send(ifp, m0);
3510 #endif
3511 	error = ip_output(m0, ipopts, NULL, 0, &imo, NULL);
3512 	if (error) {
3513 		CTR3(KTR_IGMPV3, "%s: ip_output(%p) = %d", __func__, m0, error);
3514 		goto out;
3515 	}
3516 
3517 	IGMPSTAT_INC(igps_snd_reports);
3518 
3519 out:
3520 	/*
3521 	 * We must restore the existing vnet pointer before
3522 	 * continuing as we are run from netisr context.
3523 	 */
3524 	CURVNET_RESTORE();
3525 }
3526 
3527 /*
3528  * Encapsulate an IGMPv3 report.
3529  *
3530  * The internal mbuf flag M_IGMPV3_HDR is used to indicate that the mbuf
3531  * chain has already had its IP/IGMPv3 header prepended. In this case
3532  * the function will not attempt to prepend; the lengths and checksums
3533  * will however be re-computed.
3534  *
3535  * Returns a pointer to the new mbuf chain head, or NULL if the
3536  * allocation failed.
3537  */
3538 static struct mbuf *
3539 igmp_v3_encap_report(struct ifnet *ifp, struct mbuf *m)
3540 {
3541 	struct igmp_report	*igmp;
3542 	struct ip		*ip;
3543 	int			 hdrlen, igmpreclen;
3544 
3545 	KASSERT((m->m_flags & M_PKTHDR),
3546 	    ("%s: mbuf chain %p is !M_PKTHDR", __func__, m));
3547 
3548 	igmpreclen = m_length(m, NULL);
3549 	hdrlen = sizeof(struct ip) + sizeof(struct igmp_report);
3550 
3551 	if (m->m_flags & M_IGMPV3_HDR) {
3552 		igmpreclen -= hdrlen;
3553 	} else {
3554 		M_PREPEND(m, hdrlen, M_NOWAIT);
3555 		if (m == NULL)
3556 			return (NULL);
3557 		m->m_flags |= M_IGMPV3_HDR;
3558 	}
3559 
3560 	CTR2(KTR_IGMPV3, "%s: igmpreclen is %d", __func__, igmpreclen);
3561 
3562 	m->m_data += sizeof(struct ip);
3563 	m->m_len -= sizeof(struct ip);
3564 
3565 	igmp = mtod(m, struct igmp_report *);
3566 	igmp->ir_type = IGMP_v3_HOST_MEMBERSHIP_REPORT;
3567 	igmp->ir_rsv1 = 0;
3568 	igmp->ir_rsv2 = 0;
3569 	igmp->ir_numgrps = htons(m->m_pkthdr.vt_nrecs);
3570 	igmp->ir_cksum = 0;
3571 	igmp->ir_cksum = in_cksum(m, sizeof(struct igmp_report) + igmpreclen);
3572 	m->m_pkthdr.vt_nrecs = 0;
3573 
3574 	m->m_data -= sizeof(struct ip);
3575 	m->m_len += sizeof(struct ip);
3576 
3577 	ip = mtod(m, struct ip *);
3578 	ip->ip_tos = IPTOS_PREC_INTERNETCONTROL;
3579 	ip->ip_len = htons(hdrlen + igmpreclen);
3580 	ip->ip_off = htons(IP_DF);
3581 	ip->ip_p = IPPROTO_IGMP;
3582 	ip->ip_sum = 0;
3583 
3584 	ip->ip_src.s_addr = INADDR_ANY;
3585 
3586 	if (m->m_flags & M_IGMP_LOOP) {
3587 		struct in_ifaddr *ia;
3588 
3589 		IFP_TO_IA(ifp, ia);
3590 		if (ia != NULL)
3591 			ip->ip_src = ia->ia_addr.sin_addr;
3592 	}
3593 
3594 	ip->ip_dst.s_addr = htonl(INADDR_ALLRPTS_GROUP);
3595 
3596 	return (m);
3597 }
3598 
3599 #ifdef KTR
3600 static char *
3601 igmp_rec_type_to_str(const int type)
3602 {
3603 
3604 	switch (type) {
3605 		case IGMP_CHANGE_TO_EXCLUDE_MODE:
3606 			return "TO_EX";
3607 			break;
3608 		case IGMP_CHANGE_TO_INCLUDE_MODE:
3609 			return "TO_IN";
3610 			break;
3611 		case IGMP_MODE_IS_EXCLUDE:
3612 			return "MODE_EX";
3613 			break;
3614 		case IGMP_MODE_IS_INCLUDE:
3615 			return "MODE_IN";
3616 			break;
3617 		case IGMP_ALLOW_NEW_SOURCES:
3618 			return "ALLOW_NEW";
3619 			break;
3620 		case IGMP_BLOCK_OLD_SOURCES:
3621 			return "BLOCK_OLD";
3622 			break;
3623 		default:
3624 			break;
3625 	}
3626 	return "unknown";
3627 }
3628 #endif
3629 
3630 #ifdef VIMAGE
3631 static void
3632 vnet_igmp_init(const void *unused __unused)
3633 {
3634 
3635 	netisr_register_vnet(&igmp_nh);
3636 }
3637 VNET_SYSINIT(vnet_igmp_init, SI_SUB_PROTO_MC, SI_ORDER_ANY,
3638     vnet_igmp_init, NULL);
3639 
3640 static void
3641 vnet_igmp_uninit(const void *unused __unused)
3642 {
3643 
3644 	/* This can happen when we shutdown the entire network stack. */
3645 	CTR1(KTR_IGMPV3, "%s: tearing down", __func__);
3646 
3647 	netisr_unregister_vnet(&igmp_nh);
3648 }
3649 VNET_SYSUNINIT(vnet_igmp_uninit, SI_SUB_PROTO_MC, SI_ORDER_ANY,
3650     vnet_igmp_uninit, NULL);
3651 #endif
3652 
3653 #ifdef DDB
3654 DB_SHOW_COMMAND(igi_list, db_show_igi_list)
3655 {
3656 	struct igmp_ifsoftc *igi, *tigi;
3657 	LIST_HEAD(_igi_list, igmp_ifsoftc) *igi_head;
3658 
3659 	if (!have_addr) {
3660 		db_printf("usage: show igi_list <addr>\n");
3661 		return;
3662 	}
3663 	igi_head = (struct _igi_list *)addr;
3664 
3665 	LIST_FOREACH_SAFE(igi, igi_head, igi_link, tigi) {
3666 		db_printf("igmp_ifsoftc %p:\n", igi);
3667 		db_printf("    ifp %p\n", igi->igi_ifp);
3668 		db_printf("    version %u\n", igi->igi_version);
3669 		db_printf("    v1_timer %u\n", igi->igi_v1_timer);
3670 		db_printf("    v2_timer %u\n", igi->igi_v2_timer);
3671 		db_printf("    v3_timer %u\n", igi->igi_v3_timer);
3672 		db_printf("    flags %#x\n", igi->igi_flags);
3673 		db_printf("    rv %u\n", igi->igi_rv);
3674 		db_printf("    qi %u\n", igi->igi_qi);
3675 		db_printf("    qri %u\n", igi->igi_qri);
3676 		db_printf("    uri %u\n", igi->igi_uri);
3677 		/* struct mbufq    igi_gq; */
3678 		db_printf("\n");
3679 	}
3680 }
3681 #endif
3682 
3683 static int
3684 igmp_modevent(module_t mod, int type, void *unused __unused)
3685 {
3686 
3687 	switch (type) {
3688 	case MOD_LOAD:
3689 		CTR1(KTR_IGMPV3, "%s: initializing", __func__);
3690 		IGMP_LOCK_INIT();
3691 		m_raopt = igmp_ra_alloc();
3692 		netisr_register(&igmp_nh);
3693 		callout_init(&igmpslow_callout, 1);
3694 		callout_reset(&igmpslow_callout, hz / IGMP_SLOWHZ,
3695 		    igmp_slowtimo, NULL);
3696 		callout_init(&igmpfast_callout, 1);
3697 		callout_reset(&igmpfast_callout, hz / IGMP_FASTHZ,
3698 		    igmp_fasttimo, NULL);
3699 		break;
3700 	case MOD_UNLOAD:
3701 		CTR1(KTR_IGMPV3, "%s: tearing down", __func__);
3702 		netisr_unregister(&igmp_nh);
3703 		m_free(m_raopt);
3704 		m_raopt = NULL;
3705 		IGMP_LOCK_DESTROY();
3706 		break;
3707 	default:
3708 		return (EOPNOTSUPP);
3709 	}
3710 	return (0);
3711 }
3712 
3713 static moduledata_t igmp_mod = {
3714     "igmp",
3715     igmp_modevent,
3716     0
3717 };
3718 DECLARE_MODULE(igmp, igmp_mod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);
3719