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