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