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