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