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