igmp.c revision 358274
1118611Snjl/*-
2118611Snjl * Copyright (c) 2007-2009 Bruce Simpson.
3118611Snjl * Copyright (c) 1988 Stephen Deering.
4118611Snjl * Copyright (c) 1992, 1993
5118611Snjl *	The Regents of the University of California.  All rights reserved.
6118611Snjl *
7217365Sjkim * This code is derived from software contributed to Berkeley by
8245582Sjkim * Stephen Deering of Stanford University.
9118611Snjl *
10118611Snjl * Redistribution and use in source and binary forms, with or without
11217365Sjkim * modification, are permitted provided that the following conditions
12217365Sjkim * are met:
13217365Sjkim * 1. Redistributions of source code must retain the above copyright
14217365Sjkim *    notice, this list of conditions and the following disclaimer.
15217365Sjkim * 2. Redistributions in binary form must reproduce the above copyright
16217365Sjkim *    notice, this list of conditions and the following disclaimer in the
17217365Sjkim *    documentation and/or other materials provided with the distribution.
18217365Sjkim * 4. Neither the name of the University nor the names of its contributors
19217365Sjkim *    may be used to endorse or promote products derived from this software
20217365Sjkim *    without specific prior written permission.
21217365Sjkim *
22217365Sjkim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23217365Sjkim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24217365Sjkim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25118611Snjl * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26217365Sjkim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27217365Sjkim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28217365Sjkim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29118611Snjl * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30217365Sjkim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31217365Sjkim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32217365Sjkim * SUCH DAMAGE.
33217365Sjkim *
34217365Sjkim *	@(#)igmp.c	8.1 (Berkeley) 7/19/93
35217365Sjkim */
36217365Sjkim
37217365Sjkim/*
38217365Sjkim * Internet Group Management Protocol (IGMP) routines.
39217365Sjkim * [RFC1112, RFC2236, RFC3376]
40217365Sjkim *
41217365Sjkim * Written by Steve Deering, Stanford, May 1988.
42217365Sjkim * Modified by Rosen Sharma, Stanford, Aug 1994.
43118611Snjl * Modified by Bill Fenner, Xerox PARC, Feb 1995.
44118611Snjl * Modified to fully comply to IGMPv2 by Bill Fenner, Oct 1995.
45151937Sjkim * Significantly rewritten for IGMPv3, VIMAGE, and SMP by Bruce Simpson.
46118611Snjl *
47118611Snjl * MULTICAST Revision: 3.5.1.4
48118611Snjl */
49118611Snjl
50151937Sjkim#include <sys/cdefs.h>
51118611Snjl__FBSDID("$FreeBSD: stable/11/sys/netinet/igmp.c 358274 2020-02-24 09:58:57Z hselasky $");
52151937Sjkim
53151937Sjkim#include "opt_ddb.h"
54151937Sjkim
55151937Sjkim#include <sys/param.h>
56151937Sjkim#include <sys/systm.h>
57233250Sjkim#include <sys/module.h>
58233250Sjkim#include <sys/malloc.h>
59233250Sjkim#include <sys/mbuf.h>
60233250Sjkim#include <sys/socket.h>
61233250Sjkim#include <sys/protosw.h>
62233250Sjkim#include <sys/kernel.h>
63233250Sjkim#include <sys/lock.h>
64233250Sjkim#include <sys/rmlock.h>
65233250Sjkim#include <sys/sysctl.h>
66233250Sjkim#include <sys/ktr.h>
67233250Sjkim#include <sys/condvar.h>
68233250Sjkim
69193529Sjkim#ifdef DDB
70193529Sjkim#include <ddb/ddb.h>
71193529Sjkim#endif
72193529Sjkim
73193529Sjkim#include <net/if.h>
74193529Sjkim#include <net/if_var.h>
75193529Sjkim#include <net/netisr.h>
76193529Sjkim#include <net/vnet.h>
77193529Sjkim
78193529Sjkim#include <netinet/in.h>
79193529Sjkim#include <netinet/in_var.h>
80193529Sjkim#include <netinet/in_systm.h>
81193529Sjkim#include <netinet/ip.h>
82193529Sjkim#include <netinet/ip_var.h>
83193529Sjkim#include <netinet/ip_options.h>
84193529Sjkim#include <netinet/igmp.h>
85193529Sjkim#include <netinet/igmp_var.h>
86193529Sjkim
87193529Sjkim#include <machine/in_cksum.h>
88193529Sjkim
89118611Snjl#include <security/mac/mac_framework.h>
90118611Snjl
91118611Snjl#ifndef KTR_IGMPV3
92118611Snjl#define KTR_IGMPV3 KTR_INET
93118611Snjl#endif
94118611Snjl
95118611Snjlstatic struct igmp_ifsoftc *
96118611Snjl		igi_alloc_locked(struct ifnet *);
97241973Sjkimstatic void	igi_delete_locked(const struct ifnet *);
98118611Snjlstatic void	igmp_dispatch_queue(struct mbufq *, int, const int);
99118611Snjlstatic void	igmp_fasttimo_vnet(void);
100118611Snjlstatic void	igmp_final_leave(struct in_multi *, struct igmp_ifsoftc *);
101118611Snjlstatic int	igmp_handle_state_change(struct in_multi *,
102118611Snjl		    struct igmp_ifsoftc *);
103151937Sjkimstatic int	igmp_initial_join(struct in_multi *, struct igmp_ifsoftc *);
104118611Snjlstatic int	igmp_input_v1_query(struct ifnet *, const struct ip *,
105118611Snjl		    const struct igmp *);
106118611Snjlstatic int	igmp_input_v2_query(struct ifnet *, const struct ip *,
107118611Snjl		    const struct igmp *);
108118611Snjlstatic int	igmp_input_v3_query(struct ifnet *, const struct ip *,
109118611Snjl		    /*const*/ struct igmpv3 *);
110118611Snjlstatic int	igmp_input_v3_group_query(struct in_multi *,
111202771Sjkim		    struct igmp_ifsoftc *, int, /*const*/ struct igmpv3 *);
112118611Snjlstatic int	igmp_input_v1_report(struct ifnet *, /*const*/ struct ip *,
113118611Snjl		    /*const*/ struct igmp *);
114118611Snjlstatic int	igmp_input_v2_report(struct ifnet *, /*const*/ struct ip *,
115118611Snjl		    /*const*/ struct igmp *);
116118611Snjlstatic void	igmp_intr(struct mbuf *);
117118611Snjlstatic int	igmp_isgroupreported(const struct in_addr);
118118611Snjlstatic struct mbuf *
119202771Sjkim		igmp_ra_alloc(void);
120202771Sjkim#ifdef KTR
121202771Sjkimstatic char *	igmp_rec_type_to_str(const int);
122202771Sjkim#endif
123118611Snjlstatic void	igmp_set_version(struct igmp_ifsoftc *, const int);
124118611Snjlstatic void	igmp_slowtimo_vnet(void);
125118611Snjlstatic int	igmp_v1v2_queue_report(struct in_multi *, const int);
126118611Snjlstatic void	igmp_v1v2_process_group_timer(struct in_multi *, const int);
127118611Snjlstatic void	igmp_v1v2_process_querier_timers(struct igmp_ifsoftc *);
128118611Snjlstatic void	igmp_v2_update_group(struct in_multi *, const int);
129118611Snjlstatic void	igmp_v3_cancel_link_timers(struct igmp_ifsoftc *);
130118611Snjlstatic void	igmp_v3_dispatch_general_query(struct igmp_ifsoftc *);
131118611Snjlstatic struct mbuf *
132118611Snjl		igmp_v3_encap_report(struct ifnet *, struct mbuf *);
133118611Snjlstatic int	igmp_v3_enqueue_group_record(struct mbufq *,
134118611Snjl		    struct in_multi *, const int, const int, const int);
135118611Snjlstatic int	igmp_v3_enqueue_filter_change(struct mbufq *,
136118611Snjl		    struct in_multi *);
137118611Snjlstatic void	igmp_v3_process_group_timers(struct igmp_ifsoftc *,
138118611Snjl		    struct mbufq *, struct mbufq *, struct in_multi *,
139118611Snjl		    const int);
140118611Snjlstatic int	igmp_v3_merge_state_changes(struct in_multi *,
141118611Snjl		    struct mbufq *);
142118611Snjlstatic void	igmp_v3_suppress_group_record(struct in_multi *);
143118611Snjlstatic int	sysctl_igmp_default_version(SYSCTL_HANDLER_ARGS);
144118611Snjlstatic int	sysctl_igmp_gsr(SYSCTL_HANDLER_ARGS);
145118611Snjlstatic int	sysctl_igmp_ifinfo(SYSCTL_HANDLER_ARGS);
146118611Snjl
147118611Snjlstatic const struct netisr_handler igmp_nh = {
148118611Snjl	.nh_name = "igmp",
149118611Snjl	.nh_handler = igmp_intr,
150118611Snjl	.nh_proto = NETISR_IGMP,
151118611Snjl	.nh_policy = NETISR_POLICY_SOURCE,
152151937Sjkim};
153118611Snjl
154118611Snjl/*
155118611Snjl * System-wide globals.
156118611Snjl *
157118611Snjl * Unlocked access to these is OK, except for the global IGMP output
158118611Snjl * queue. The IGMP subsystem lock ends up being system-wide for the moment,
159118611Snjl * because all VIMAGEs have to share a global output queue, as netisrs
160118611Snjl * themselves are not virtualized.
161118611Snjl *
162118611Snjl * Locking:
163118611Snjl *  * The permitted lock order is: IN_MULTI_LOCK, IGMP_LOCK, IF_ADDR_LOCK.
164118611Snjl *    Any may be taken independently; if any are held at the same
165118611Snjl *    time, the above lock order must be followed.
166118611Snjl *  * All output is delegated to the netisr.
167118611Snjl *    Now that Giant has been eliminated, the netisr may be inlined.
168118611Snjl *  * IN_MULTI_LOCK covers in_multi.
169118611Snjl *  * IGMP_LOCK covers igmp_ifsoftc and any global variables in this file,
170118611Snjl *    including the output queue.
171118611Snjl *  * IF_ADDR_LOCK covers if_multiaddrs, which is used for a variety of
172118611Snjl *    per-link state iterators.
173118611Snjl *  * igmp_ifsoftc is valid as long as PF_INET is attached to the interface,
174151937Sjkim *    therefore it is not refcounted.
175151937Sjkim *    We allow unlocked reads of igmp_ifsoftc when accessed via in_multi.
176118611Snjl *
177118611Snjl * Reference counting
178118611Snjl *  * IGMP acquires its own reference every time an in_multi is passed to
179118611Snjl *    it and the group is being joined for the first time.
180118611Snjl *  * IGMP releases its reference(s) on in_multi in a deferred way,
181118611Snjl *    because the operations which process the release run as part of
182233250Sjkim *    a loop whose control variables are directly affected by the release
183216471Sjkim *    (that, and not recursing on the IF_ADDR_LOCK).
184216471Sjkim *
185240716Sjkim * VIMAGE: Each in_multi corresponds to an ifp, and each ifp corresponds
186118611Snjl * to a vnet in ifp->if_vnet.
187118611Snjl *
188193529Sjkim * SMPng: XXX We may potentially race operations on ifma_protospec.
189193529Sjkim * The problem is that we currently lack a clean way of taking the
190193529Sjkim * IF_ADDR_LOCK() between the ifnet and in layers w/o recursing,
191193529Sjkim * as anything which modifies ifma needs to be covered by that lock.
192193529Sjkim * So check for ifma_protospec being NULL before proceeding.
193151937Sjkim */
194151937Sjkimstruct mtx		 igmp_mtx;
195151937Sjkim
196151937Sjkimstruct mbuf		*m_raopt;		 /* Router Alert option */
197118611Snjlstatic MALLOC_DEFINE(M_IGMP, "igmp", "igmp state");
198118611Snjl
199118611Snjl/*
200118611Snjl * VIMAGE-wide globals.
201118611Snjl *
202118611Snjl * The IGMPv3 timers themselves need to run per-image, however,
203118611Snjl * protosw timers run globally (see tcp).
204250838Sjkim * An ifnet can only be in one vimage at a time, and the loopback
205118611Snjl * ifnet, loif, is itself virtualized.
206118611Snjl * It would otherwise be possible to seriously hose IGMP state,
207118611Snjl * and create inconsistencies in upstream multicast routing, if you have
208118611Snjl * multiple VIMAGEs running on the same link joining different multicast
209118611Snjl * groups, UNLESS the "primary IP address" is different. This is because
210118611Snjl * IGMP for IPv4 does not force link-local addresses to be used for each
211118611Snjl * node, unlike MLD for IPv6.
212250838Sjkim * Obviously the IGMPv3 per-interface state has per-vimage granularity
213118611Snjl * also as a result.
214118611Snjl *
215118611Snjl * FUTURE: Stop using IFP_TO_IA/INADDR_ANY, and use source address selection
216118611Snjl * policy to control the address used by IGMP on the link.
217118611Snjl */
218118611Snjlstatic VNET_DEFINE(int, interface_timers_running);	/* IGMPv3 general
219118611Snjl							 * query response */
220250838Sjkimstatic VNET_DEFINE(int, state_change_timers_running);	/* IGMPv3 state-change
221118611Snjl							 * retransmit */
222118611Snjlstatic VNET_DEFINE(int, current_state_timers_running);	/* IGMPv1/v2 host
223118611Snjl							 * report; IGMPv3 g/sg
224118611Snjl							 * query response */
225118611Snjl
226118611Snjl#define	V_interface_timers_running	VNET(interface_timers_running)
227118611Snjl#define	V_state_change_timers_running	VNET(state_change_timers_running)
228209746Sjkim#define	V_current_state_timers_running	VNET(current_state_timers_running)
229209746Sjkim
230233250Sjkimstatic VNET_DEFINE(LIST_HEAD(, igmp_ifsoftc), igi_head) =
231209746Sjkim    LIST_HEAD_INITIALIZER(igi_head);
232233250Sjkimstatic VNET_DEFINE(struct igmpstat, igmpstat) = {
233118611Snjl	.igps_version = IGPS_VERSION_3,
234233250Sjkim	.igps_len = sizeof(struct igmpstat),
235233250Sjkim};
236233250Sjkimstatic VNET_DEFINE(struct timeval, igmp_gsrdelay) = {10, 0};
237233250Sjkim
238233250Sjkim#define	V_igi_head			VNET(igi_head)
239216471Sjkim#define	V_igmpstat			VNET(igmpstat)
240233250Sjkim#define	V_igmp_gsrdelay			VNET(igmp_gsrdelay)
241233250Sjkim
242233250Sjkimstatic VNET_DEFINE(int, igmp_recvifkludge) = 1;
243216471Sjkimstatic VNET_DEFINE(int, igmp_sendra) = 1;
244233250Sjkimstatic VNET_DEFINE(int, igmp_sendlocal) = 1;
245233250Sjkimstatic VNET_DEFINE(int, igmp_v1enable) = 1;
246233250Sjkimstatic VNET_DEFINE(int, igmp_v2enable) = 1;
247233250Sjkimstatic VNET_DEFINE(int, igmp_legacysupp);
248233250Sjkimstatic VNET_DEFINE(int, igmp_default_version) = IGMP_VERSION_3;
249233250Sjkim
250233250Sjkim#define	V_igmp_recvifkludge		VNET(igmp_recvifkludge)
251216471Sjkim#define	V_igmp_sendra			VNET(igmp_sendra)
252216471Sjkim#define	V_igmp_sendlocal		VNET(igmp_sendlocal)
253216471Sjkim#define	V_igmp_v1enable			VNET(igmp_v1enable)
254118611Snjl#define	V_igmp_v2enable			VNET(igmp_v2enable)
255118611Snjl#define	V_igmp_legacysupp		VNET(igmp_legacysupp)
256118611Snjl#define	V_igmp_default_version		VNET(igmp_default_version)
257118611Snjl
258118611Snjl/*
259118611Snjl * Virtualized sysctls.
260118611Snjl */
261118611SnjlSYSCTL_STRUCT(_net_inet_igmp, IGMPCTL_STATS, stats, CTLFLAG_VNET | CTLFLAG_RW,
262118611Snjl    &VNET_NAME(igmpstat), igmpstat, "");
263118611SnjlSYSCTL_INT(_net_inet_igmp, OID_AUTO, recvifkludge, CTLFLAG_VNET | CTLFLAG_RW,
264118611Snjl    &VNET_NAME(igmp_recvifkludge), 0,
265234623Sjkim    "Rewrite IGMPv1/v2 reports from 0.0.0.0 to contain subnet address");
266118611SnjlSYSCTL_INT(_net_inet_igmp, OID_AUTO, sendra, CTLFLAG_VNET | CTLFLAG_RW,
267118611Snjl    &VNET_NAME(igmp_sendra), 0,
268118611Snjl    "Send IP Router Alert option in IGMPv2/v3 messages");
269233250SjkimSYSCTL_INT(_net_inet_igmp, OID_AUTO, sendlocal, CTLFLAG_VNET | CTLFLAG_RW,
270233250Sjkim    &VNET_NAME(igmp_sendlocal), 0,
271233250Sjkim    "Send IGMP membership reports for 224.0.0.0/24 groups");
272233250SjkimSYSCTL_INT(_net_inet_igmp, OID_AUTO, v1enable, CTLFLAG_VNET | CTLFLAG_RW,
273233250Sjkim    &VNET_NAME(igmp_v1enable), 0,
274233250Sjkim    "Enable backwards compatibility with IGMPv1");
275233250SjkimSYSCTL_INT(_net_inet_igmp, OID_AUTO, v2enable, CTLFLAG_VNET | CTLFLAG_RW,
276234623Sjkim    &VNET_NAME(igmp_v2enable), 0,
277118611Snjl    "Enable backwards compatibility with IGMPv2");
278216471SjkimSYSCTL_INT(_net_inet_igmp, OID_AUTO, legacysupp, CTLFLAG_VNET | CTLFLAG_RW,
279233250Sjkim    &VNET_NAME(igmp_legacysupp), 0,
280233250Sjkim    "Allow v1/v2 reports to suppress v3 group responses");
281233250SjkimSYSCTL_PROC(_net_inet_igmp, OID_AUTO, default_version,
282216471Sjkim    CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
283233250Sjkim    &VNET_NAME(igmp_default_version), 0, sysctl_igmp_default_version, "I",
284118611Snjl    "Default version of IGMP to run on each interface");
285233250SjkimSYSCTL_PROC(_net_inet_igmp, OID_AUTO, gsrdelay,
286233250Sjkim    CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
287233250Sjkim    &VNET_NAME(igmp_gsrdelay.tv_sec), 0, sysctl_igmp_gsr, "I",
288233250Sjkim    "Rate limit for IGMPv3 Group-and-Source queries in seconds");
289233250Sjkim
290233250Sjkim/*
291233250Sjkim * Non-virtualized sysctls.
292216471Sjkim */
293216471Sjkimstatic SYSCTL_NODE(_net_inet_igmp, OID_AUTO, ifinfo,
294233250Sjkim    CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_igmp_ifinfo,
295216471Sjkim    "Per-interface IGMPv3 state");
296216471Sjkim
297233250Sjkimstatic __inline void
298216471Sjkimigmp_save_context(struct mbuf *m, struct ifnet *ifp)
299216471Sjkim{
300243347Sjkim
301233250Sjkim#ifdef VIMAGE
302233250Sjkim	m->m_pkthdr.PH_loc.ptr = ifp->if_vnet;
303233250Sjkim#endif /* VIMAGE */
304233250Sjkim	m->m_pkthdr.rcvif = ifp;
305233250Sjkim	m->m_pkthdr.flowid = ifp->if_index;
306240716Sjkim}
307240716Sjkim
308249112Sjkimstatic __inline void
309249112Sjkimigmp_scrub_context(struct mbuf *m)
310249112Sjkim{
311240716Sjkim
312249112Sjkim	m->m_pkthdr.PH_loc.ptr = NULL;
313243347Sjkim	m->m_pkthdr.flowid = 0;
314249112Sjkim}
315249112Sjkim
316249112Sjkim/*
317249112Sjkim * Restore context from a queued IGMP output chain.
318249112Sjkim * Return saved ifindex.
319249112Sjkim *
320249112Sjkim * VIMAGE: The assertion is there to make sure that we
321243347Sjkim * actually called CURVNET_SET() with what's in the mbuf chain.
322249112Sjkim */
323249112Sjkimstatic __inline uint32_t
324249112Sjkimigmp_restore_context(struct mbuf *m)
325249112Sjkim{
326249112Sjkim
327249112Sjkim#ifdef notyet
328243347Sjkim#if defined(VIMAGE) && defined(INVARIANTS)
329240716Sjkim	KASSERT(curvnet == (m->m_pkthdr.PH_loc.ptr),
330243347Sjkim	    ("%s: called when curvnet was not restored", __func__));
331243347Sjkim#endif
332243347Sjkim#endif
333243347Sjkim	return (m->m_pkthdr.flowid);
334243347Sjkim}
335243347Sjkim
336243347Sjkim/*
337240716Sjkim * Retrieve or set default IGMP version.
338240716Sjkim *
339233250Sjkim * VIMAGE: Assume curvnet set by caller.
340216471Sjkim * SMPng: NOTE: Serialized by IGMP lock.
341118611Snjl */
342233250Sjkimstatic int
343233250Sjkimsysctl_igmp_default_version(SYSCTL_HANDLER_ARGS)
344118611Snjl{
345118611Snjl	int	 error;
346118611Snjl	int	 new;
347118611Snjl
348118611Snjl	error = sysctl_wire_old_buffer(req, sizeof(int));
349235945Sjkim	if (error)
350235945Sjkim		return (error);
351235945Sjkim
352235945Sjkim	IGMP_LOCK();
353118611Snjl
354118611Snjl	new = V_igmp_default_version;
355118611Snjl
356118611Snjl	error = sysctl_handle_int(oidp, &new, 0, req);
357235945Sjkim	if (error || !req->newptr)
358235945Sjkim		goto out_locked;
359118611Snjl
360118611Snjl	if (new < IGMP_VERSION_1 || new > IGMP_VERSION_3) {
361118611Snjl		error = EINVAL;
362118611Snjl		goto out_locked;
363118611Snjl	}
364118611Snjl
365118611Snjl	CTR2(KTR_IGMPV3, "change igmp_default_version from %d to %d",
366118611Snjl	     V_igmp_default_version, new);
367118611Snjl
368118611Snjl	V_igmp_default_version = new;
369118611Snjl
370118611Snjlout_locked:
371118611Snjl	IGMP_UNLOCK();
372118611Snjl	return (error);
373235945Sjkim}
374235945Sjkim
375237412Sjkim/*
376235945Sjkim * Retrieve or set threshold between group-source queries in seconds.
377235945Sjkim *
378235945Sjkim * VIMAGE: Assume curvnet set by caller.
379235945Sjkim * SMPng: NOTE: Serialized by IGMP lock.
380235945Sjkim */
381235945Sjkimstatic int
382235945Sjkimsysctl_igmp_gsr(SYSCTL_HANDLER_ARGS)
383235945Sjkim{
384235945Sjkim	int error;
385118611Snjl	int i;
386118611Snjl
387118611Snjl	error = sysctl_wire_old_buffer(req, sizeof(int));
388118611Snjl	if (error)
389118611Snjl		return (error);
390118611Snjl
391228110Sjkim	IGMP_LOCK();
392228110Sjkim
393228110Sjkim	i = V_igmp_gsrdelay.tv_sec;
394228110Sjkim
395228110Sjkim	error = sysctl_handle_int(oidp, &i, 0, req);
396228110Sjkim	if (error || !req->newptr)
397228110Sjkim		goto out_locked;
398118611Snjl
399118611Snjl	if (i < -1 || i >= 60) {
400118611Snjl		error = EINVAL;
401228110Sjkim		goto out_locked;
402228110Sjkim	}
403118611Snjl
404228110Sjkim	CTR2(KTR_IGMPV3, "change igmp_gsrdelay from %d to %d",
405228110Sjkim	     V_igmp_gsrdelay.tv_sec, i);
406228110Sjkim	V_igmp_gsrdelay.tv_sec = i;
407228110Sjkim
408118611Snjlout_locked:
409118611Snjl	IGMP_UNLOCK();
410118611Snjl	return (error);
411118611Snjl}
412118611Snjl
413216471Sjkim/*
414118611Snjl * Expose struct igmp_ifsoftc to userland, keyed by ifindex.
415240716Sjkim * For use by ifmcstat(8).
416118611Snjl *
417240716Sjkim * SMPng: NOTE: Does an unlocked ifindex space read.
418240716Sjkim * VIMAGE: Assume curvnet set by caller. The node handler itself
419118611Snjl * is not directly virtualized.
420118611Snjl */
421118611Snjlstatic int
422240716Sjkimsysctl_igmp_ifinfo(SYSCTL_HANDLER_ARGS)
423240716Sjkim{
424240716Sjkim	int			*name;
425240716Sjkim	int			 error;
426240716Sjkim	u_int			 namelen;
427240716Sjkim	struct ifnet		*ifp;
428240716Sjkim	struct igmp_ifsoftc	*igi;
429240716Sjkim
430240716Sjkim	name = (int *)arg1;
431240716Sjkim	namelen = arg2;
432240716Sjkim
433240716Sjkim	if (req->newptr != NULL)
434240716Sjkim		return (EPERM);
435240716Sjkim
436240716Sjkim	if (namelen != 1)
437118611Snjl		return (EINVAL);
438118611Snjl
439118611Snjl	error = sysctl_wire_old_buffer(req, sizeof(struct igmp_ifinfo));
440118611Snjl	if (error)
441118611Snjl		return (error);
442118611Snjl
443118611Snjl	IN_MULTI_LOCK();
444118611Snjl	IGMP_LOCK();
445118611Snjl
446118611Snjl	if (name[0] <= 0 || name[0] > V_if_index) {
447118611Snjl		error = ENOENT;
448118611Snjl		goto out_locked;
449118611Snjl	}
450118611Snjl
451216471Sjkim	error = ENOENT;
452216471Sjkim
453216471Sjkim	ifp = ifnet_byindex(name[0]);
454216471Sjkim	if (ifp == NULL)
455216471Sjkim		goto out_locked;
456118611Snjl
457118611Snjl	LIST_FOREACH(igi, &V_igi_head, igi_link) {
458118611Snjl		if (ifp == igi->igi_ifp) {
459118611Snjl			struct igmp_ifinfo info;
460118611Snjl
461118611Snjl			info.igi_version = igi->igi_version;
462118611Snjl			info.igi_v1_timer = igi->igi_v1_timer;
463118611Snjl			info.igi_v2_timer = igi->igi_v2_timer;
464151937Sjkim			info.igi_v3_timer = igi->igi_v3_timer;
465118611Snjl			info.igi_flags = igi->igi_flags;
466118611Snjl			info.igi_rv = igi->igi_rv;
467118611Snjl			info.igi_qi = igi->igi_qi;
468118611Snjl			info.igi_qri = igi->igi_qri;
469118611Snjl			info.igi_uri = igi->igi_uri;
470118611Snjl			error = SYSCTL_OUT(req, &info, sizeof(info));
471118611Snjl			break;
472118611Snjl		}
473118611Snjl	}
474118611Snjl
475118611Snjlout_locked:
476118611Snjl	IGMP_UNLOCK();
477118611Snjl	IN_MULTI_UNLOCK();
478118611Snjl	return (error);
479118611Snjl}
480118611Snjl
481118611Snjl/*
482118611Snjl * Dispatch an entire queue of pending packet chains
483118611Snjl * using the netisr.
484118611Snjl * VIMAGE: Assumes the vnet pointer has been set.
485118611Snjl */
486118611Snjlstatic void
487118611Snjligmp_dispatch_queue(struct mbufq *mq, int limit, const int loop)
488118611Snjl{
489118611Snjl	struct mbuf *m;
490118611Snjl
491118611Snjl	while ((m = mbufq_dequeue(mq)) != NULL) {
492118611Snjl		CTR3(KTR_IGMPV3, "%s: dispatch %p from %p", __func__, mq, m);
493118611Snjl		if (loop)
494118611Snjl			m->m_flags |= M_IGMP_LOOP;
495118611Snjl		netisr_dispatch(NETISR_IGMP, m);
496118611Snjl		if (--limit == 0)
497118611Snjl			break;
498118611Snjl	}
499118611Snjl}
500118611Snjl
501233250Sjkim/*
502233250Sjkim * Filter outgoing IGMP report state by group.
503233250Sjkim *
504233250Sjkim * Reports are ALWAYS suppressed for ALL-HOSTS (224.0.0.1).
505233250Sjkim * If the net.inet.igmp.sendlocal sysctl is 0, then IGMP reports are
506233250Sjkim * disabled for all groups in the 224.0.0.0/24 link-local scope. However,
507233250Sjkim * this may break certain IGMP snooping switches which rely on the old
508233250Sjkim * report behaviour.
509233250Sjkim *
510233250Sjkim * Return zero if the given group is one for which IGMP reports
511233250Sjkim * should be suppressed, or non-zero if reports should be issued.
512233250Sjkim */
513233250Sjkimstatic __inline int
514233250Sjkimigmp_isgroupreported(const struct in_addr addr)
515233250Sjkim{
516233250Sjkim
517233250Sjkim	if (in_allhosts(addr) ||
518233250Sjkim	    ((!V_igmp_sendlocal && IN_LOCAL_GROUP(ntohl(addr.s_addr)))))
519233250Sjkim		return (0);
520233250Sjkim
521233250Sjkim	return (1);
522233250Sjkim}
523233250Sjkim
524233250Sjkim/*
525233250Sjkim * Construct a Router Alert option to use in outgoing packets.
526233250Sjkim */
527233250Sjkimstatic struct mbuf *
528233250Sjkimigmp_ra_alloc(void)
529233250Sjkim{
530233250Sjkim	struct mbuf	*m;
531233250Sjkim	struct ipoption	*p;
532233250Sjkim
533233250Sjkim	m = m_get(M_WAITOK, MT_DATA);
534233250Sjkim	p = mtod(m, struct ipoption *);
535233250Sjkim	p->ipopt_dst.s_addr = INADDR_ANY;
536233250Sjkim	p->ipopt_list[0] = (char)IPOPT_RA;	/* Router Alert Option */
537233250Sjkim	p->ipopt_list[1] = 0x04;		/* 4 bytes long */
538233250Sjkim	p->ipopt_list[2] = IPOPT_EOL;		/* End of IP option list */
539233250Sjkim	p->ipopt_list[3] = 0x00;		/* pad byte */
540233250Sjkim	m->m_len = sizeof(p->ipopt_dst) + p->ipopt_list[1];
541233250Sjkim
542233250Sjkim	return (m);
543233250Sjkim}
544233250Sjkim
545233250Sjkim/*
546233250Sjkim * Attach IGMP when PF_INET is attached to an interface.
547233250Sjkim */
548233250Sjkimstruct igmp_ifsoftc *
549233250Sjkimigmp_domifattach(struct ifnet *ifp)
550233250Sjkim{
551233250Sjkim	struct igmp_ifsoftc *igi;
552233250Sjkim
553233250Sjkim	CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)",
554233250Sjkim	    __func__, ifp, ifp->if_xname);
555233250Sjkim
556233250Sjkim	IGMP_LOCK();
557233250Sjkim
558233250Sjkim	igi = igi_alloc_locked(ifp);
559233250Sjkim	if (!(ifp->if_flags & IFF_MULTICAST))
560233250Sjkim		igi->igi_flags |= IGIF_SILENT;
561233250Sjkim
562233250Sjkim	IGMP_UNLOCK();
563233250Sjkim
564233250Sjkim	return (igi);
565233250Sjkim}
566233250Sjkim
567233250Sjkim/*
568233250Sjkim * VIMAGE: assume curvnet set by caller.
569233250Sjkim */
570233250Sjkimstatic struct igmp_ifsoftc *
571233250Sjkimigi_alloc_locked(/*const*/ struct ifnet *ifp)
572233250Sjkim{
573233250Sjkim	struct igmp_ifsoftc *igi;
574233250Sjkim
575233250Sjkim	IGMP_LOCK_ASSERT();
576233250Sjkim
577233250Sjkim	igi = malloc(sizeof(struct igmp_ifsoftc), M_IGMP, M_NOWAIT|M_ZERO);
578233250Sjkim	if (igi == NULL)
579233250Sjkim		goto out;
580233250Sjkim
581233250Sjkim	igi->igi_ifp = ifp;
582233250Sjkim	igi->igi_version = V_igmp_default_version;
583233250Sjkim	igi->igi_flags = 0;
584233250Sjkim	igi->igi_rv = IGMP_RV_INIT;
585233250Sjkim	igi->igi_qi = IGMP_QI_INIT;
586118611Snjl	igi->igi_qri = IGMP_QRI_INIT;
587118611Snjl	igi->igi_uri = IGMP_URI_INIT;
588118611Snjl	SLIST_INIT(&igi->igi_relinmhead);
589118611Snjl	mbufq_init(&igi->igi_gq, IGMP_MAX_RESPONSE_PACKETS);
590118611Snjl
591118611Snjl	LIST_INSERT_HEAD(&V_igi_head, igi, igi_link);
592118611Snjl
593118611Snjl	CTR2(KTR_IGMPV3, "allocate igmp_ifsoftc for ifp %p(%s)",
594118611Snjl	     ifp, ifp->if_xname);
595118611Snjl
596118611Snjlout:
597151937Sjkim	return (igi);
598118611Snjl}
599118611Snjl
600118611Snjl/*
601118611Snjl * Hook for ifdetach.
602118611Snjl *
603118611Snjl * NOTE: Some finalization tasks need to run before the protocol domain
604118611Snjl * is detached, but also before the link layer does its cleanup.
605118611Snjl *
606118611Snjl * SMPNG: igmp_ifdetach() needs to take IF_ADDR_LOCK().
607118611Snjl * XXX This is also bitten by unlocked ifma_protospec access.
608118611Snjl */
609118611Snjlvoid
610118611Snjligmp_ifdetach(struct ifnet *ifp)
611118611Snjl{
612118611Snjl	struct igmp_ifsoftc	*igi;
613118611Snjl	struct ifmultiaddr	*ifma;
614118611Snjl	struct in_multi		*inm, *tinm;
615118611Snjl
616118611Snjl	CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)", __func__, ifp,
617118611Snjl	    ifp->if_xname);
618118611Snjl
619118611Snjl	IGMP_LOCK();
620118611Snjl
621118611Snjl	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
622118611Snjl	if (igi->igi_version == IGMP_VERSION_3) {
623118611Snjl		IF_ADDR_RLOCK(ifp);
624118611Snjl		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
625118611Snjl			if (ifma->ifma_addr->sa_family != AF_INET ||
626118611Snjl			    ifma->ifma_protospec == NULL)
627118611Snjl				continue;
628118611Snjl#if 0
629118611Snjl			KASSERT(ifma->ifma_protospec != NULL,
630118611Snjl			    ("%s: ifma_protospec is NULL", __func__));
631118611Snjl#endif
632118611Snjl			inm = (struct in_multi *)ifma->ifma_protospec;
633118611Snjl			if (inm->inm_state == IGMP_LEAVING_MEMBER) {
634118611Snjl				SLIST_INSERT_HEAD(&igi->igi_relinmhead,
635118611Snjl				    inm, inm_nrele);
636118611Snjl			}
637118611Snjl			inm_clear_recorded(inm);
638118611Snjl		}
639118611Snjl		IF_ADDR_RUNLOCK(ifp);
640118611Snjl		/*
641118611Snjl		 * Free the in_multi reference(s) for this IGMP lifecycle.
642118611Snjl		 */
643118611Snjl		SLIST_FOREACH_SAFE(inm, &igi->igi_relinmhead, inm_nrele,
644118611Snjl		    tinm) {
645118611Snjl			SLIST_REMOVE_HEAD(&igi->igi_relinmhead, inm_nrele);
646118611Snjl			inm_release_locked(inm);
647118611Snjl		}
648118611Snjl	}
649118611Snjl
650118611Snjl	IGMP_UNLOCK();
651118611Snjl}
652233250Sjkim
653118611Snjl/*
654118611Snjl * Hook for domifdetach.
655118611Snjl */
656118611Snjlvoid
657118611Snjligmp_domifdetach(struct ifnet *ifp)
658118611Snjl{
659118611Snjl
660118611Snjl	CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)",
661118611Snjl	    __func__, ifp, ifp->if_xname);
662118611Snjl
663118611Snjl	IGMP_LOCK();
664118611Snjl	igi_delete_locked(ifp);
665118611Snjl	IGMP_UNLOCK();
666118611Snjl}
667118611Snjl
668209746Sjkimstatic void
669118611Snjligi_delete_locked(const struct ifnet *ifp)
670118611Snjl{
671118611Snjl	struct igmp_ifsoftc *igi, *tigi;
672118611Snjl
673199337Sjkim	CTR3(KTR_IGMPV3, "%s: freeing igmp_ifsoftc for ifp %p(%s)",
674118611Snjl	    __func__, ifp, ifp->if_xname);
675118611Snjl
676118611Snjl	IGMP_LOCK_ASSERT();
677118611Snjl
678118611Snjl	LIST_FOREACH_SAFE(igi, &V_igi_head, igi_link, tigi) {
679118611Snjl		if (igi->igi_ifp == ifp) {
680118611Snjl			/*
681118611Snjl			 * Free deferred General Query responses.
682250838Sjkim			 */
683250838Sjkim			mbufq_drain(&igi->igi_gq);
684250838Sjkim
685250838Sjkim			LIST_REMOVE(igi, igi_link);
686250838Sjkim
687250838Sjkim			KASSERT(SLIST_EMPTY(&igi->igi_relinmhead),
688250838Sjkim			    ("%s: there are dangling in_multi references",
689250838Sjkim			    __func__));
690250838Sjkim
691250838Sjkim			free(igi, M_IGMP);
692250838Sjkim			return;
693250838Sjkim		}
694250838Sjkim	}
695250838Sjkim}
696250838Sjkim
697250838Sjkim/*
698250838Sjkim * Process a received IGMPv1 query.
699250838Sjkim * Return non-zero if the message should be dropped.
700250838Sjkim *
701250838Sjkim * VIMAGE: The curvnet pointer is derived from the input ifp.
702250838Sjkim */
703250838Sjkimstatic int
704250838Sjkimigmp_input_v1_query(struct ifnet *ifp, const struct ip *ip,
705250838Sjkim    const struct igmp *igmp)
706250838Sjkim{
707250838Sjkim	struct ifmultiaddr	*ifma;
708250838Sjkim	struct igmp_ifsoftc	*igi;
709250838Sjkim	struct in_multi		*inm;
710250838Sjkim
711250838Sjkim	/*
712250838Sjkim	 * IGMPv1 Host Mmembership Queries SHOULD always be addressed to
713250838Sjkim	 * 224.0.0.1. They are always treated as General Queries.
714250838Sjkim	 * igmp_group is always ignored. Do not drop it as a userland
715250838Sjkim	 * daemon may wish to see it.
716250838Sjkim	 * XXX SMPng: unlocked increments in igmpstat assumed atomic.
717250838Sjkim	 */
718250838Sjkim	if (!in_allhosts(ip->ip_dst) || !in_nullhost(igmp->igmp_group)) {
719250838Sjkim		IGMPSTAT_INC(igps_rcv_badqueries);
720250838Sjkim		return (0);
721250838Sjkim	}
722250838Sjkim	IGMPSTAT_INC(igps_rcv_gen_queries);
723250838Sjkim
724250838Sjkim	IN_MULTI_LOCK();
725250838Sjkim	IGMP_LOCK();
726250838Sjkim
727250838Sjkim	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
728250838Sjkim	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
729250838Sjkim
730250838Sjkim	if (igi->igi_flags & IGIF_LOOPBACK) {
731250838Sjkim		CTR2(KTR_IGMPV3, "ignore v1 query on IGIF_LOOPBACK ifp %p(%s)",
732250838Sjkim		    ifp, ifp->if_xname);
733250838Sjkim		goto out_locked;
734250838Sjkim	}
735250838Sjkim
736250838Sjkim	/*
737250838Sjkim	 * Switch to IGMPv1 host compatibility mode.
738250838Sjkim	 */
739250838Sjkim	igmp_set_version(igi, IGMP_VERSION_1);
740250838Sjkim
741250838Sjkim	CTR2(KTR_IGMPV3, "process v1 query on ifp %p(%s)", ifp, ifp->if_xname);
742250838Sjkim
743250838Sjkim	/*
744250838Sjkim	 * Start the timers in all of our group records
745250838Sjkim	 * for the interface on which the query arrived,
746250838Sjkim	 * except those which are already running.
747250838Sjkim	 */
748250838Sjkim	IF_ADDR_RLOCK(ifp);
749250838Sjkim	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
750250838Sjkim		if (ifma->ifma_addr->sa_family != AF_INET ||
751250838Sjkim		    ifma->ifma_protospec == NULL)
752250838Sjkim			continue;
753250838Sjkim		inm = (struct in_multi *)ifma->ifma_protospec;
754250838Sjkim		if (inm->inm_timer != 0)
755250838Sjkim			continue;
756250838Sjkim		switch (inm->inm_state) {
757250838Sjkim		case IGMP_NOT_MEMBER:
758250838Sjkim		case IGMP_SILENT_MEMBER:
759250838Sjkim			break;
760250838Sjkim		case IGMP_G_QUERY_PENDING_MEMBER:
761250838Sjkim		case IGMP_SG_QUERY_PENDING_MEMBER:
762250838Sjkim		case IGMP_REPORTING_MEMBER:
763250838Sjkim		case IGMP_IDLE_MEMBER:
764250838Sjkim		case IGMP_LAZY_MEMBER:
765250838Sjkim		case IGMP_SLEEPING_MEMBER:
766250838Sjkim		case IGMP_AWAKENING_MEMBER:
767250838Sjkim			inm->inm_state = IGMP_REPORTING_MEMBER;
768250838Sjkim			inm->inm_timer = IGMP_RANDOM_DELAY(
769250838Sjkim			    IGMP_V1V2_MAX_RI * PR_FASTHZ);
770250838Sjkim			V_current_state_timers_running = 1;
771250838Sjkim			break;
772250838Sjkim		case IGMP_LEAVING_MEMBER:
773250838Sjkim			break;
774250838Sjkim		}
775250838Sjkim	}
776250838Sjkim	IF_ADDR_RUNLOCK(ifp);
777250838Sjkim
778250838Sjkimout_locked:
779250838Sjkim	IGMP_UNLOCK();
780250838Sjkim	IN_MULTI_UNLOCK();
781250838Sjkim
782250838Sjkim	return (0);
783250838Sjkim}
784250838Sjkim
785250838Sjkim/*
786250838Sjkim * Process a received IGMPv2 general or group-specific query.
787250838Sjkim */
788250838Sjkimstatic int
789118611Snjligmp_input_v2_query(struct ifnet *ifp, const struct ip *ip,
790118611Snjl    const struct igmp *igmp)
791118611Snjl{
792118611Snjl	struct ifmultiaddr	*ifma;
793118611Snjl	struct igmp_ifsoftc	*igi;
794118611Snjl	struct in_multi		*inm;
795118611Snjl	int			 is_general_query;
796118611Snjl	uint16_t		 timer;
797118611Snjl
798118611Snjl	is_general_query = 0;
799118611Snjl
800118611Snjl	/*
801118611Snjl	 * Validate address fields upfront.
802118611Snjl	 * XXX SMPng: unlocked increments in igmpstat assumed atomic.
803118611Snjl	 */
804118611Snjl	if (in_nullhost(igmp->igmp_group)) {
805118611Snjl		/*
806118611Snjl		 * IGMPv2 General Query.
807118611Snjl		 * If this was not sent to the all-hosts group, ignore it.
808118611Snjl		 */
809118611Snjl		if (!in_allhosts(ip->ip_dst))
810118611Snjl			return (0);
811250838Sjkim		IGMPSTAT_INC(igps_rcv_gen_queries);
812250838Sjkim		is_general_query = 1;
813250838Sjkim	} else {
814167802Sjkim		/* IGMPv2 Group-Specific Query. */
815250838Sjkim		IGMPSTAT_INC(igps_rcv_group_queries);
816167802Sjkim	}
817167802Sjkim
818118611Snjl	IN_MULTI_LOCK();
819118611Snjl	IGMP_LOCK();
820118611Snjl
821250838Sjkim	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
822250838Sjkim	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
823250838Sjkim
824250838Sjkim	if (igi->igi_flags & IGIF_LOOPBACK) {
825118611Snjl		CTR2(KTR_IGMPV3, "ignore v2 query on IGIF_LOOPBACK ifp %p(%s)",
826118611Snjl		    ifp, ifp->if_xname);
827118611Snjl		goto out_locked;
828118611Snjl	}
829250838Sjkim
830118611Snjl	/*
831118611Snjl	 * Ignore v2 query if in v1 Compatibility Mode.
832118611Snjl	 */
833118611Snjl	if (igi->igi_version == IGMP_VERSION_1)
834118611Snjl		goto out_locked;
835118611Snjl
836118611Snjl	igmp_set_version(igi, IGMP_VERSION_2);
837118611Snjl
838118611Snjl	timer = igmp->igmp_code * PR_FASTHZ / IGMP_TIMER_SCALE;
839118611Snjl	if (timer == 0)
840118611Snjl		timer = 1;
841118611Snjl
842118611Snjl	if (is_general_query) {
843118611Snjl		/*
844118611Snjl		 * For each reporting group joined on this
845118611Snjl		 * interface, kick the report timer.
846118611Snjl		 */
847118611Snjl		CTR2(KTR_IGMPV3, "process v2 general query on ifp %p(%s)",
848118611Snjl		    ifp, ifp->if_xname);
849118611Snjl		IF_ADDR_RLOCK(ifp);
850118611Snjl		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
851118611Snjl			if (ifma->ifma_addr->sa_family != AF_INET ||
852118611Snjl			    ifma->ifma_protospec == NULL)
853118611Snjl				continue;
854118611Snjl			inm = (struct in_multi *)ifma->ifma_protospec;
855118611Snjl			igmp_v2_update_group(inm, timer);
856118611Snjl		}
857118611Snjl		IF_ADDR_RUNLOCK(ifp);
858118611Snjl	} else {
859118611Snjl		/*
860118611Snjl		 * Group-specific IGMPv2 query, we need only
861118611Snjl		 * look up the single group to process it.
862118611Snjl		 */
863118611Snjl		inm = inm_lookup(ifp, igmp->igmp_group);
864118611Snjl		if (inm != NULL) {
865118611Snjl			CTR3(KTR_IGMPV3,
866118611Snjl			    "process v2 query 0x%08x on ifp %p(%s)",
867118611Snjl			    ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
868118611Snjl			igmp_v2_update_group(inm, timer);
869118611Snjl		}
870118611Snjl	}
871118611Snjl
872118611Snjlout_locked:
873118611Snjl	IGMP_UNLOCK();
874118611Snjl	IN_MULTI_UNLOCK();
875118611Snjl
876118611Snjl	return (0);
877118611Snjl}
878118611Snjl
879118611Snjl/*
880118611Snjl * Update the report timer on a group in response to an IGMPv2 query.
881118611Snjl *
882118611Snjl * If we are becoming the reporting member for this group, start the timer.
883118611Snjl * If we already are the reporting member for this group, and timer is
884118611Snjl * below the threshold, reset it.
885118611Snjl *
886118611Snjl * We may be updating the group for the first time since we switched
887151937Sjkim * to IGMPv3. If we are, then we must clear any recorded source lists,
888118611Snjl * and transition to REPORTING state; the group timer is overloaded
889118611Snjl * for group and group-source query responses.
890151937Sjkim *
891151937Sjkim * Unlike IGMPv3, the delay per group should be jittered
892118611Snjl * to avoid bursts of IGMPv2 reports.
893118611Snjl */
894118611Snjlstatic void
895118611Snjligmp_v2_update_group(struct in_multi *inm, const int timer)
896118611Snjl{
897228110Sjkim
898118611Snjl	CTR4(KTR_IGMPV3, "0x%08x: %s/%s timer=%d", __func__,
899118611Snjl	    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname, timer);
900118611Snjl
901228110Sjkim	IN_MULTI_LOCK_ASSERT();
902228110Sjkim
903228110Sjkim	switch (inm->inm_state) {
904118611Snjl	case IGMP_NOT_MEMBER:
905241973Sjkim	case IGMP_SILENT_MEMBER:
906118611Snjl		break;
907	case IGMP_REPORTING_MEMBER:
908		if (inm->inm_timer != 0 &&
909		    inm->inm_timer <= timer) {
910			CTR1(KTR_IGMPV3, "%s: REPORTING and timer running, "
911			    "skipping.", __func__);
912			break;
913		}
914		/* FALLTHROUGH */
915	case IGMP_SG_QUERY_PENDING_MEMBER:
916	case IGMP_G_QUERY_PENDING_MEMBER:
917	case IGMP_IDLE_MEMBER:
918	case IGMP_LAZY_MEMBER:
919	case IGMP_AWAKENING_MEMBER:
920		CTR1(KTR_IGMPV3, "%s: ->REPORTING", __func__);
921		inm->inm_state = IGMP_REPORTING_MEMBER;
922		inm->inm_timer = IGMP_RANDOM_DELAY(timer);
923		V_current_state_timers_running = 1;
924		break;
925	case IGMP_SLEEPING_MEMBER:
926		CTR1(KTR_IGMPV3, "%s: ->AWAKENING", __func__);
927		inm->inm_state = IGMP_AWAKENING_MEMBER;
928		break;
929	case IGMP_LEAVING_MEMBER:
930		break;
931	}
932}
933
934/*
935 * Process a received IGMPv3 general, group-specific or
936 * group-and-source-specific query.
937 * Assumes m has already been pulled up to the full IGMP message length.
938 * Return 0 if successful, otherwise an appropriate error code is returned.
939 */
940static int
941igmp_input_v3_query(struct ifnet *ifp, const struct ip *ip,
942    /*const*/ struct igmpv3 *igmpv3)
943{
944	struct igmp_ifsoftc	*igi;
945	struct in_multi		*inm;
946	int			 is_general_query;
947	uint32_t		 maxresp, nsrc, qqi;
948	uint16_t		 timer;
949	uint8_t			 qrv;
950
951	is_general_query = 0;
952
953	CTR2(KTR_IGMPV3, "process v3 query on ifp %p(%s)", ifp, ifp->if_xname);
954
955	maxresp = igmpv3->igmp_code;	/* in 1/10ths of a second */
956	if (maxresp >= 128) {
957		maxresp = IGMP_MANT(igmpv3->igmp_code) <<
958			  (IGMP_EXP(igmpv3->igmp_code) + 3);
959	}
960
961	/*
962	 * Robustness must never be less than 2 for on-wire IGMPv3.
963	 * FUTURE: Check if ifp has IGIF_LOOPBACK set, as we will make
964	 * an exception for interfaces whose IGMPv3 state changes
965	 * are redirected to loopback (e.g. MANET).
966	 */
967	qrv = IGMP_QRV(igmpv3->igmp_misc);
968	if (qrv < 2) {
969		CTR3(KTR_IGMPV3, "%s: clamping qrv %d to %d", __func__,
970		    qrv, IGMP_RV_INIT);
971		qrv = IGMP_RV_INIT;
972	}
973
974	qqi = igmpv3->igmp_qqi;
975	if (qqi >= 128) {
976		qqi = IGMP_MANT(igmpv3->igmp_qqi) <<
977		     (IGMP_EXP(igmpv3->igmp_qqi) + 3);
978	}
979
980	timer = maxresp * PR_FASTHZ / IGMP_TIMER_SCALE;
981	if (timer == 0)
982		timer = 1;
983
984	nsrc = ntohs(igmpv3->igmp_numsrc);
985
986	/*
987	 * Validate address fields and versions upfront before
988	 * accepting v3 query.
989	 * XXX SMPng: Unlocked access to igmpstat counters here.
990	 */
991	if (in_nullhost(igmpv3->igmp_group)) {
992		/*
993		 * IGMPv3 General Query.
994		 *
995		 * General Queries SHOULD be directed to 224.0.0.1.
996		 * A general query with a source list has undefined
997		 * behaviour; discard it.
998		 */
999		IGMPSTAT_INC(igps_rcv_gen_queries);
1000		if (!in_allhosts(ip->ip_dst) || nsrc > 0) {
1001			IGMPSTAT_INC(igps_rcv_badqueries);
1002			return (0);
1003		}
1004		is_general_query = 1;
1005	} else {
1006		/* Group or group-source specific query. */
1007		if (nsrc == 0)
1008			IGMPSTAT_INC(igps_rcv_group_queries);
1009		else
1010			IGMPSTAT_INC(igps_rcv_gsr_queries);
1011	}
1012
1013	IN_MULTI_LOCK();
1014	IGMP_LOCK();
1015
1016	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
1017	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
1018
1019	if (igi->igi_flags & IGIF_LOOPBACK) {
1020		CTR2(KTR_IGMPV3, "ignore v3 query on IGIF_LOOPBACK ifp %p(%s)",
1021		    ifp, ifp->if_xname);
1022		goto out_locked;
1023	}
1024
1025	/*
1026	 * Discard the v3 query if we're in Compatibility Mode.
1027	 * The RFC is not obviously worded that hosts need to stay in
1028	 * compatibility mode until the Old Version Querier Present
1029	 * timer expires.
1030	 */
1031	if (igi->igi_version != IGMP_VERSION_3) {
1032		CTR3(KTR_IGMPV3, "ignore v3 query in v%d mode on ifp %p(%s)",
1033		    igi->igi_version, ifp, ifp->if_xname);
1034		goto out_locked;
1035	}
1036
1037	igmp_set_version(igi, IGMP_VERSION_3);
1038	igi->igi_rv = qrv;
1039	igi->igi_qi = qqi;
1040	igi->igi_qri = maxresp;
1041
1042	CTR4(KTR_IGMPV3, "%s: qrv %d qi %d qri %d", __func__, qrv, qqi,
1043	    maxresp);
1044
1045	if (is_general_query) {
1046		/*
1047		 * Schedule a current-state report on this ifp for
1048		 * all groups, possibly containing source lists.
1049		 * If there is a pending General Query response
1050		 * scheduled earlier than the selected delay, do
1051		 * not schedule any other reports.
1052		 * Otherwise, reset the interface timer.
1053		 */
1054		CTR2(KTR_IGMPV3, "process v3 general query on ifp %p(%s)",
1055		    ifp, ifp->if_xname);
1056		if (igi->igi_v3_timer == 0 || igi->igi_v3_timer >= timer) {
1057			igi->igi_v3_timer = IGMP_RANDOM_DELAY(timer);
1058			V_interface_timers_running = 1;
1059		}
1060	} else {
1061		/*
1062		 * Group-source-specific queries are throttled on
1063		 * a per-group basis to defeat denial-of-service attempts.
1064		 * Queries for groups we are not a member of on this
1065		 * link are simply ignored.
1066		 */
1067		inm = inm_lookup(ifp, igmpv3->igmp_group);
1068		if (inm == NULL)
1069			goto out_locked;
1070		if (nsrc > 0) {
1071			if (!ratecheck(&inm->inm_lastgsrtv,
1072			    &V_igmp_gsrdelay)) {
1073				CTR1(KTR_IGMPV3, "%s: GS query throttled.",
1074				    __func__);
1075				IGMPSTAT_INC(igps_drop_gsr_queries);
1076				goto out_locked;
1077			}
1078		}
1079		CTR3(KTR_IGMPV3, "process v3 0x%08x query on ifp %p(%s)",
1080		     ntohl(igmpv3->igmp_group.s_addr), ifp, ifp->if_xname);
1081		/*
1082		 * If there is a pending General Query response
1083		 * scheduled sooner than the selected delay, no
1084		 * further report need be scheduled.
1085		 * Otherwise, prepare to respond to the
1086		 * group-specific or group-and-source query.
1087		 */
1088		if (igi->igi_v3_timer == 0 || igi->igi_v3_timer >= timer)
1089			igmp_input_v3_group_query(inm, igi, timer, igmpv3);
1090	}
1091
1092out_locked:
1093	IGMP_UNLOCK();
1094	IN_MULTI_UNLOCK();
1095
1096	return (0);
1097}
1098
1099/*
1100 * Process a received IGMPv3 group-specific or group-and-source-specific
1101 * query.
1102 * Return <0 if any error occurred. Currently this is ignored.
1103 */
1104static int
1105igmp_input_v3_group_query(struct in_multi *inm, struct igmp_ifsoftc *igi,
1106    int timer, /*const*/ struct igmpv3 *igmpv3)
1107{
1108	int			 retval;
1109	uint16_t		 nsrc;
1110
1111	IN_MULTI_LOCK_ASSERT();
1112	IGMP_LOCK_ASSERT();
1113
1114	retval = 0;
1115
1116	switch (inm->inm_state) {
1117	case IGMP_NOT_MEMBER:
1118	case IGMP_SILENT_MEMBER:
1119	case IGMP_SLEEPING_MEMBER:
1120	case IGMP_LAZY_MEMBER:
1121	case IGMP_AWAKENING_MEMBER:
1122	case IGMP_IDLE_MEMBER:
1123	case IGMP_LEAVING_MEMBER:
1124		return (retval);
1125		break;
1126	case IGMP_REPORTING_MEMBER:
1127	case IGMP_G_QUERY_PENDING_MEMBER:
1128	case IGMP_SG_QUERY_PENDING_MEMBER:
1129		break;
1130	}
1131
1132	nsrc = ntohs(igmpv3->igmp_numsrc);
1133
1134	/*
1135	 * Deal with group-specific queries upfront.
1136	 * If any group query is already pending, purge any recorded
1137	 * source-list state if it exists, and schedule a query response
1138	 * for this group-specific query.
1139	 */
1140	if (nsrc == 0) {
1141		if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER ||
1142		    inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER) {
1143			inm_clear_recorded(inm);
1144			timer = min(inm->inm_timer, timer);
1145		}
1146		inm->inm_state = IGMP_G_QUERY_PENDING_MEMBER;
1147		inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1148		V_current_state_timers_running = 1;
1149		return (retval);
1150	}
1151
1152	/*
1153	 * Deal with the case where a group-and-source-specific query has
1154	 * been received but a group-specific query is already pending.
1155	 */
1156	if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER) {
1157		timer = min(inm->inm_timer, timer);
1158		inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1159		V_current_state_timers_running = 1;
1160		return (retval);
1161	}
1162
1163	/*
1164	 * Finally, deal with the case where a group-and-source-specific
1165	 * query has been received, where a response to a previous g-s-r
1166	 * query exists, or none exists.
1167	 * In this case, we need to parse the source-list which the Querier
1168	 * has provided us with and check if we have any source list filter
1169	 * entries at T1 for these sources. If we do not, there is no need
1170	 * schedule a report and the query may be dropped.
1171	 * If we do, we must record them and schedule a current-state
1172	 * report for those sources.
1173	 * FIXME: Handling source lists larger than 1 mbuf requires that
1174	 * we pass the mbuf chain pointer down to this function, and use
1175	 * m_getptr() to walk the chain.
1176	 */
1177	if (inm->inm_nsrc > 0) {
1178		const struct in_addr	*ap;
1179		int			 i, nrecorded;
1180
1181		ap = (const struct in_addr *)(igmpv3 + 1);
1182		nrecorded = 0;
1183		for (i = 0; i < nsrc; i++, ap++) {
1184			retval = inm_record_source(inm, ap->s_addr);
1185			if (retval < 0)
1186				break;
1187			nrecorded += retval;
1188		}
1189		if (nrecorded > 0) {
1190			CTR1(KTR_IGMPV3,
1191			    "%s: schedule response to SG query", __func__);
1192			inm->inm_state = IGMP_SG_QUERY_PENDING_MEMBER;
1193			inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1194			V_current_state_timers_running = 1;
1195		}
1196	}
1197
1198	return (retval);
1199}
1200
1201/*
1202 * Process a received IGMPv1 host membership report.
1203 *
1204 * NOTE: 0.0.0.0 workaround breaks const correctness.
1205 */
1206static int
1207igmp_input_v1_report(struct ifnet *ifp, /*const*/ struct ip *ip,
1208    /*const*/ struct igmp *igmp)
1209{
1210	struct rm_priotracker in_ifa_tracker;
1211	struct in_ifaddr *ia;
1212	struct in_multi *inm;
1213
1214	IGMPSTAT_INC(igps_rcv_reports);
1215
1216	if (ifp->if_flags & IFF_LOOPBACK)
1217		return (0);
1218
1219	if (!IN_MULTICAST(ntohl(igmp->igmp_group.s_addr)) ||
1220	    !in_hosteq(igmp->igmp_group, ip->ip_dst)) {
1221		IGMPSTAT_INC(igps_rcv_badreports);
1222		return (EINVAL);
1223	}
1224
1225	/*
1226	 * RFC 3376, Section 4.2.13, 9.2, 9.3:
1227	 * Booting clients may use the source address 0.0.0.0. Some
1228	 * IGMP daemons may not know how to use IP_RECVIF to determine
1229	 * the interface upon which this message was received.
1230	 * Replace 0.0.0.0 with the subnet address if told to do so.
1231	 */
1232	if (V_igmp_recvifkludge && in_nullhost(ip->ip_src)) {
1233		IFP_TO_IA(ifp, ia, &in_ifa_tracker);
1234		if (ia != NULL) {
1235			ip->ip_src.s_addr = htonl(ia->ia_subnet);
1236			ifa_free(&ia->ia_ifa);
1237		}
1238	}
1239
1240	CTR3(KTR_IGMPV3, "process v1 report 0x%08x on ifp %p(%s)",
1241	     ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1242
1243	/*
1244	 * IGMPv1 report suppression.
1245	 * If we are a member of this group, and our membership should be
1246	 * reported, stop our group timer and transition to the 'lazy' state.
1247	 */
1248	IN_MULTI_LOCK();
1249	inm = inm_lookup(ifp, igmp->igmp_group);
1250	if (inm != NULL) {
1251		struct igmp_ifsoftc *igi;
1252
1253		igi = inm->inm_igi;
1254		if (igi == NULL) {
1255			KASSERT(igi != NULL,
1256			    ("%s: no igi for ifp %p", __func__, ifp));
1257			goto out_locked;
1258		}
1259
1260		IGMPSTAT_INC(igps_rcv_ourreports);
1261
1262		/*
1263		 * If we are in IGMPv3 host mode, do not allow the
1264		 * other host's IGMPv1 report to suppress our reports
1265		 * unless explicitly configured to do so.
1266		 */
1267		if (igi->igi_version == IGMP_VERSION_3) {
1268			if (V_igmp_legacysupp)
1269				igmp_v3_suppress_group_record(inm);
1270			goto out_locked;
1271		}
1272
1273		inm->inm_timer = 0;
1274
1275		switch (inm->inm_state) {
1276		case IGMP_NOT_MEMBER:
1277		case IGMP_SILENT_MEMBER:
1278			break;
1279		case IGMP_IDLE_MEMBER:
1280		case IGMP_LAZY_MEMBER:
1281		case IGMP_AWAKENING_MEMBER:
1282			CTR3(KTR_IGMPV3,
1283			    "report suppressed for 0x%08x on ifp %p(%s)",
1284			    ntohl(igmp->igmp_group.s_addr), ifp,
1285			    ifp->if_xname);
1286		case IGMP_SLEEPING_MEMBER:
1287			inm->inm_state = IGMP_SLEEPING_MEMBER;
1288			break;
1289		case IGMP_REPORTING_MEMBER:
1290			CTR3(KTR_IGMPV3,
1291			    "report suppressed for 0x%08x on ifp %p(%s)",
1292			    ntohl(igmp->igmp_group.s_addr), ifp,
1293			    ifp->if_xname);
1294			if (igi->igi_version == IGMP_VERSION_1)
1295				inm->inm_state = IGMP_LAZY_MEMBER;
1296			else if (igi->igi_version == IGMP_VERSION_2)
1297				inm->inm_state = IGMP_SLEEPING_MEMBER;
1298			break;
1299		case IGMP_G_QUERY_PENDING_MEMBER:
1300		case IGMP_SG_QUERY_PENDING_MEMBER:
1301		case IGMP_LEAVING_MEMBER:
1302			break;
1303		}
1304	}
1305
1306out_locked:
1307	IN_MULTI_UNLOCK();
1308
1309	return (0);
1310}
1311
1312/*
1313 * Process a received IGMPv2 host membership report.
1314 *
1315 * NOTE: 0.0.0.0 workaround breaks const correctness.
1316 */
1317static int
1318igmp_input_v2_report(struct ifnet *ifp, /*const*/ struct ip *ip,
1319    /*const*/ struct igmp *igmp)
1320{
1321	struct rm_priotracker in_ifa_tracker;
1322	struct in_ifaddr *ia;
1323	struct in_multi *inm;
1324
1325	/*
1326	 * Make sure we don't hear our own membership report.  Fast
1327	 * leave requires knowing that we are the only member of a
1328	 * group.
1329	 */
1330	IFP_TO_IA(ifp, ia, &in_ifa_tracker);
1331	if (ia != NULL && in_hosteq(ip->ip_src, IA_SIN(ia)->sin_addr)) {
1332		ifa_free(&ia->ia_ifa);
1333		return (0);
1334	}
1335
1336	IGMPSTAT_INC(igps_rcv_reports);
1337
1338	if (ifp->if_flags & IFF_LOOPBACK) {
1339		if (ia != NULL)
1340			ifa_free(&ia->ia_ifa);
1341		return (0);
1342	}
1343
1344	if (!IN_MULTICAST(ntohl(igmp->igmp_group.s_addr)) ||
1345	    !in_hosteq(igmp->igmp_group, ip->ip_dst)) {
1346		if (ia != NULL)
1347			ifa_free(&ia->ia_ifa);
1348		IGMPSTAT_INC(igps_rcv_badreports);
1349		return (EINVAL);
1350	}
1351
1352	/*
1353	 * RFC 3376, Section 4.2.13, 9.2, 9.3:
1354	 * Booting clients may use the source address 0.0.0.0. Some
1355	 * IGMP daemons may not know how to use IP_RECVIF to determine
1356	 * the interface upon which this message was received.
1357	 * Replace 0.0.0.0 with the subnet address if told to do so.
1358	 */
1359	if (V_igmp_recvifkludge && in_nullhost(ip->ip_src)) {
1360		if (ia != NULL)
1361			ip->ip_src.s_addr = htonl(ia->ia_subnet);
1362	}
1363	if (ia != NULL)
1364		ifa_free(&ia->ia_ifa);
1365
1366	CTR3(KTR_IGMPV3, "process v2 report 0x%08x on ifp %p(%s)",
1367	     ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1368
1369	/*
1370	 * IGMPv2 report suppression.
1371	 * If we are a member of this group, and our membership should be
1372	 * reported, and our group timer is pending or about to be reset,
1373	 * stop our group timer by transitioning to the 'lazy' state.
1374	 */
1375	IN_MULTI_LOCK();
1376	inm = inm_lookup(ifp, igmp->igmp_group);
1377	if (inm != NULL) {
1378		struct igmp_ifsoftc *igi;
1379
1380		igi = inm->inm_igi;
1381		KASSERT(igi != NULL, ("%s: no igi for ifp %p", __func__, ifp));
1382
1383		IGMPSTAT_INC(igps_rcv_ourreports);
1384
1385		/*
1386		 * If we are in IGMPv3 host mode, do not allow the
1387		 * other host's IGMPv1 report to suppress our reports
1388		 * unless explicitly configured to do so.
1389		 */
1390		if (igi->igi_version == IGMP_VERSION_3) {
1391			if (V_igmp_legacysupp)
1392				igmp_v3_suppress_group_record(inm);
1393			goto out_locked;
1394		}
1395
1396		inm->inm_timer = 0;
1397
1398		switch (inm->inm_state) {
1399		case IGMP_NOT_MEMBER:
1400		case IGMP_SILENT_MEMBER:
1401		case IGMP_SLEEPING_MEMBER:
1402			break;
1403		case IGMP_REPORTING_MEMBER:
1404		case IGMP_IDLE_MEMBER:
1405		case IGMP_AWAKENING_MEMBER:
1406			CTR3(KTR_IGMPV3,
1407			    "report suppressed for 0x%08x on ifp %p(%s)",
1408			    ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1409		case IGMP_LAZY_MEMBER:
1410			inm->inm_state = IGMP_LAZY_MEMBER;
1411			break;
1412		case IGMP_G_QUERY_PENDING_MEMBER:
1413		case IGMP_SG_QUERY_PENDING_MEMBER:
1414		case IGMP_LEAVING_MEMBER:
1415			break;
1416		}
1417	}
1418
1419out_locked:
1420	IN_MULTI_UNLOCK();
1421
1422	return (0);
1423}
1424
1425int
1426igmp_input(struct mbuf **mp, int *offp, int proto)
1427{
1428	int iphlen;
1429	struct ifnet *ifp;
1430	struct igmp *igmp;
1431	struct ip *ip;
1432	struct mbuf *m;
1433	int igmplen;
1434	int minlen;
1435	int queryver;
1436
1437	CTR3(KTR_IGMPV3, "%s: called w/mbuf (%p,%d)", __func__, *mp, *offp);
1438
1439	m = *mp;
1440	ifp = m->m_pkthdr.rcvif;
1441	*mp = NULL;
1442
1443	IGMPSTAT_INC(igps_rcv_total);
1444
1445	ip = mtod(m, struct ip *);
1446	iphlen = *offp;
1447	igmplen = ntohs(ip->ip_len) - iphlen;
1448
1449	/*
1450	 * Validate lengths.
1451	 */
1452	if (igmplen < IGMP_MINLEN) {
1453		IGMPSTAT_INC(igps_rcv_tooshort);
1454		m_freem(m);
1455		return (IPPROTO_DONE);
1456	}
1457
1458	/*
1459	 * Always pullup to the minimum size for v1/v2 or v3
1460	 * to amortize calls to m_pullup().
1461	 */
1462	minlen = iphlen;
1463	if (igmplen >= IGMP_V3_QUERY_MINLEN)
1464		minlen += IGMP_V3_QUERY_MINLEN;
1465	else
1466		minlen += IGMP_MINLEN;
1467	if ((!M_WRITABLE(m) || m->m_len < minlen) &&
1468	    (m = m_pullup(m, minlen)) == NULL) {
1469		IGMPSTAT_INC(igps_rcv_tooshort);
1470		return (IPPROTO_DONE);
1471	}
1472	ip = mtod(m, struct ip *);
1473
1474	/*
1475	 * Validate checksum.
1476	 */
1477	m->m_data += iphlen;
1478	m->m_len -= iphlen;
1479	igmp = mtod(m, struct igmp *);
1480	if (in_cksum(m, igmplen)) {
1481		IGMPSTAT_INC(igps_rcv_badsum);
1482		m_freem(m);
1483		return (IPPROTO_DONE);
1484	}
1485	m->m_data -= iphlen;
1486	m->m_len += iphlen;
1487
1488	/*
1489	 * IGMP control traffic is link-scope, and must have a TTL of 1.
1490	 * DVMRP traffic (e.g. mrinfo, mtrace) is an exception;
1491	 * probe packets may come from beyond the LAN.
1492	 */
1493	if (igmp->igmp_type != IGMP_DVMRP && ip->ip_ttl != 1) {
1494		IGMPSTAT_INC(igps_rcv_badttl);
1495		m_freem(m);
1496		return (IPPROTO_DONE);
1497	}
1498
1499	switch (igmp->igmp_type) {
1500	case IGMP_HOST_MEMBERSHIP_QUERY:
1501		if (igmplen == IGMP_MINLEN) {
1502			if (igmp->igmp_code == 0)
1503				queryver = IGMP_VERSION_1;
1504			else
1505				queryver = IGMP_VERSION_2;
1506		} else if (igmplen >= IGMP_V3_QUERY_MINLEN) {
1507			queryver = IGMP_VERSION_3;
1508		} else {
1509			IGMPSTAT_INC(igps_rcv_tooshort);
1510			m_freem(m);
1511			return (IPPROTO_DONE);
1512		}
1513
1514		switch (queryver) {
1515		case IGMP_VERSION_1:
1516			IGMPSTAT_INC(igps_rcv_v1v2_queries);
1517			if (!V_igmp_v1enable)
1518				break;
1519			if (igmp_input_v1_query(ifp, ip, igmp) != 0) {
1520				m_freem(m);
1521				return (IPPROTO_DONE);
1522			}
1523			break;
1524
1525		case IGMP_VERSION_2:
1526			IGMPSTAT_INC(igps_rcv_v1v2_queries);
1527			if (!V_igmp_v2enable)
1528				break;
1529			if (igmp_input_v2_query(ifp, ip, igmp) != 0) {
1530				m_freem(m);
1531				return (IPPROTO_DONE);
1532			}
1533			break;
1534
1535		case IGMP_VERSION_3: {
1536				struct igmpv3 *igmpv3;
1537				uint16_t igmpv3len;
1538				uint16_t nsrc;
1539
1540				IGMPSTAT_INC(igps_rcv_v3_queries);
1541				igmpv3 = (struct igmpv3 *)igmp;
1542				/*
1543				 * Validate length based on source count.
1544				 */
1545				nsrc = ntohs(igmpv3->igmp_numsrc);
1546				if (nsrc * sizeof(in_addr_t) >
1547				    UINT16_MAX - iphlen - IGMP_V3_QUERY_MINLEN) {
1548					IGMPSTAT_INC(igps_rcv_tooshort);
1549					return (IPPROTO_DONE);
1550				}
1551				/*
1552				 * m_pullup() may modify m, so pullup in
1553				 * this scope.
1554				 */
1555				igmpv3len = iphlen + IGMP_V3_QUERY_MINLEN +
1556				   sizeof(struct in_addr) * nsrc;
1557				if ((!M_WRITABLE(m) ||
1558				     m->m_len < igmpv3len) &&
1559				    (m = m_pullup(m, igmpv3len)) == NULL) {
1560					IGMPSTAT_INC(igps_rcv_tooshort);
1561					return (IPPROTO_DONE);
1562				}
1563				igmpv3 = (struct igmpv3 *)(mtod(m, uint8_t *)
1564				    + iphlen);
1565				if (igmp_input_v3_query(ifp, ip, igmpv3) != 0) {
1566					m_freem(m);
1567					return (IPPROTO_DONE);
1568				}
1569			}
1570			break;
1571		}
1572		break;
1573
1574	case IGMP_v1_HOST_MEMBERSHIP_REPORT:
1575		if (!V_igmp_v1enable)
1576			break;
1577		if (igmp_input_v1_report(ifp, ip, igmp) != 0) {
1578			m_freem(m);
1579			return (IPPROTO_DONE);
1580		}
1581		break;
1582
1583	case IGMP_v2_HOST_MEMBERSHIP_REPORT:
1584		if (!V_igmp_v2enable)
1585			break;
1586		if (!ip_checkrouteralert(m))
1587			IGMPSTAT_INC(igps_rcv_nora);
1588		if (igmp_input_v2_report(ifp, ip, igmp) != 0) {
1589			m_freem(m);
1590			return (IPPROTO_DONE);
1591		}
1592		break;
1593
1594	case IGMP_v3_HOST_MEMBERSHIP_REPORT:
1595		/*
1596		 * Hosts do not need to process IGMPv3 membership reports,
1597		 * as report suppression is no longer required.
1598		 */
1599		if (!ip_checkrouteralert(m))
1600			IGMPSTAT_INC(igps_rcv_nora);
1601		break;
1602
1603	default:
1604		break;
1605	}
1606
1607	/*
1608	 * Pass all valid IGMP packets up to any process(es) listening on a
1609	 * raw IGMP socket.
1610	 */
1611	*mp = m;
1612	return (rip_input(mp, offp, proto));
1613}
1614
1615
1616/*
1617 * Fast timeout handler (global).
1618 * VIMAGE: Timeout handlers are expected to service all vimages.
1619 */
1620void
1621igmp_fasttimo(void)
1622{
1623	VNET_ITERATOR_DECL(vnet_iter);
1624
1625	VNET_LIST_RLOCK_NOSLEEP();
1626	VNET_FOREACH(vnet_iter) {
1627		CURVNET_SET(vnet_iter);
1628		igmp_fasttimo_vnet();
1629		CURVNET_RESTORE();
1630	}
1631	VNET_LIST_RUNLOCK_NOSLEEP();
1632}
1633
1634/*
1635 * Fast timeout handler (per-vnet).
1636 * Sends are shuffled off to a netisr to deal with Giant.
1637 *
1638 * VIMAGE: Assume caller has set up our curvnet.
1639 */
1640static void
1641igmp_fasttimo_vnet(void)
1642{
1643	struct mbufq		 scq;	/* State-change packets */
1644	struct mbufq		 qrq;	/* Query response packets */
1645	struct ifnet		*ifp;
1646	struct igmp_ifsoftc	*igi;
1647	struct ifmultiaddr	*ifma;
1648	struct in_multi		*inm;
1649	int			 loop, uri_fasthz;
1650
1651	loop = 0;
1652	uri_fasthz = 0;
1653
1654	/*
1655	 * Quick check to see if any work needs to be done, in order to
1656	 * minimize the overhead of fasttimo processing.
1657	 * SMPng: XXX Unlocked reads.
1658	 */
1659	if (!V_current_state_timers_running &&
1660	    !V_interface_timers_running &&
1661	    !V_state_change_timers_running)
1662		return;
1663
1664	IN_MULTI_LOCK();
1665	IGMP_LOCK();
1666
1667	/*
1668	 * IGMPv3 General Query response timer processing.
1669	 */
1670	if (V_interface_timers_running) {
1671		CTR1(KTR_IGMPV3, "%s: interface timers running", __func__);
1672
1673		V_interface_timers_running = 0;
1674		LIST_FOREACH(igi, &V_igi_head, igi_link) {
1675			if (igi->igi_v3_timer == 0) {
1676				/* Do nothing. */
1677			} else if (--igi->igi_v3_timer == 0) {
1678				igmp_v3_dispatch_general_query(igi);
1679			} else {
1680				V_interface_timers_running = 1;
1681			}
1682		}
1683	}
1684
1685	if (!V_current_state_timers_running &&
1686	    !V_state_change_timers_running)
1687		goto out_locked;
1688
1689	V_current_state_timers_running = 0;
1690	V_state_change_timers_running = 0;
1691
1692	CTR1(KTR_IGMPV3, "%s: state change timers running", __func__);
1693
1694	/*
1695	 * IGMPv1/v2/v3 host report and state-change timer processing.
1696	 * Note: Processing a v3 group timer may remove a node.
1697	 */
1698	LIST_FOREACH(igi, &V_igi_head, igi_link) {
1699		ifp = igi->igi_ifp;
1700
1701		if (igi->igi_version == IGMP_VERSION_3) {
1702			loop = (igi->igi_flags & IGIF_LOOPBACK) ? 1 : 0;
1703			uri_fasthz = IGMP_RANDOM_DELAY(igi->igi_uri *
1704			    PR_FASTHZ);
1705			mbufq_init(&qrq, IGMP_MAX_G_GS_PACKETS);
1706			mbufq_init(&scq, IGMP_MAX_STATE_CHANGE_PACKETS);
1707		}
1708
1709		IF_ADDR_RLOCK(ifp);
1710		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1711			if (ifma->ifma_addr->sa_family != AF_INET ||
1712			    ifma->ifma_protospec == NULL)
1713				continue;
1714			inm = (struct in_multi *)ifma->ifma_protospec;
1715			switch (igi->igi_version) {
1716			case IGMP_VERSION_1:
1717			case IGMP_VERSION_2:
1718				igmp_v1v2_process_group_timer(inm,
1719				    igi->igi_version);
1720				break;
1721			case IGMP_VERSION_3:
1722				igmp_v3_process_group_timers(igi, &qrq,
1723				    &scq, inm, uri_fasthz);
1724				break;
1725			}
1726		}
1727		IF_ADDR_RUNLOCK(ifp);
1728
1729		if (igi->igi_version == IGMP_VERSION_3) {
1730			struct in_multi		*tinm;
1731
1732			igmp_dispatch_queue(&qrq, 0, loop);
1733			igmp_dispatch_queue(&scq, 0, loop);
1734
1735			/*
1736			 * Free the in_multi reference(s) for this
1737			 * IGMP lifecycle.
1738			 */
1739			SLIST_FOREACH_SAFE(inm, &igi->igi_relinmhead,
1740			    inm_nrele, tinm) {
1741				SLIST_REMOVE_HEAD(&igi->igi_relinmhead,
1742				    inm_nrele);
1743				inm_release_locked(inm);
1744			}
1745		}
1746	}
1747
1748out_locked:
1749	IGMP_UNLOCK();
1750	IN_MULTI_UNLOCK();
1751}
1752
1753/*
1754 * Update host report group timer for IGMPv1/v2.
1755 * Will update the global pending timer flags.
1756 */
1757static void
1758igmp_v1v2_process_group_timer(struct in_multi *inm, const int version)
1759{
1760	int report_timer_expired;
1761
1762	IN_MULTI_LOCK_ASSERT();
1763	IGMP_LOCK_ASSERT();
1764
1765	if (inm->inm_timer == 0) {
1766		report_timer_expired = 0;
1767	} else if (--inm->inm_timer == 0) {
1768		report_timer_expired = 1;
1769	} else {
1770		V_current_state_timers_running = 1;
1771		return;
1772	}
1773
1774	switch (inm->inm_state) {
1775	case IGMP_NOT_MEMBER:
1776	case IGMP_SILENT_MEMBER:
1777	case IGMP_IDLE_MEMBER:
1778	case IGMP_LAZY_MEMBER:
1779	case IGMP_SLEEPING_MEMBER:
1780	case IGMP_AWAKENING_MEMBER:
1781		break;
1782	case IGMP_REPORTING_MEMBER:
1783		if (report_timer_expired) {
1784			inm->inm_state = IGMP_IDLE_MEMBER;
1785			(void)igmp_v1v2_queue_report(inm,
1786			    (version == IGMP_VERSION_2) ?
1787			     IGMP_v2_HOST_MEMBERSHIP_REPORT :
1788			     IGMP_v1_HOST_MEMBERSHIP_REPORT);
1789		}
1790		break;
1791	case IGMP_G_QUERY_PENDING_MEMBER:
1792	case IGMP_SG_QUERY_PENDING_MEMBER:
1793	case IGMP_LEAVING_MEMBER:
1794		break;
1795	}
1796}
1797
1798/*
1799 * Update a group's timers for IGMPv3.
1800 * Will update the global pending timer flags.
1801 * Note: Unlocked read from igi.
1802 */
1803static void
1804igmp_v3_process_group_timers(struct igmp_ifsoftc *igi,
1805    struct mbufq *qrq, struct mbufq *scq,
1806    struct in_multi *inm, const int uri_fasthz)
1807{
1808	int query_response_timer_expired;
1809	int state_change_retransmit_timer_expired;
1810
1811	IN_MULTI_LOCK_ASSERT();
1812	IGMP_LOCK_ASSERT();
1813
1814	query_response_timer_expired = 0;
1815	state_change_retransmit_timer_expired = 0;
1816
1817	/*
1818	 * During a transition from v1/v2 compatibility mode back to v3,
1819	 * a group record in REPORTING state may still have its group
1820	 * timer active. This is a no-op in this function; it is easier
1821	 * to deal with it here than to complicate the slow-timeout path.
1822	 */
1823	if (inm->inm_timer == 0) {
1824		query_response_timer_expired = 0;
1825	} else if (--inm->inm_timer == 0) {
1826		query_response_timer_expired = 1;
1827	} else {
1828		V_current_state_timers_running = 1;
1829	}
1830
1831	if (inm->inm_sctimer == 0) {
1832		state_change_retransmit_timer_expired = 0;
1833	} else if (--inm->inm_sctimer == 0) {
1834		state_change_retransmit_timer_expired = 1;
1835	} else {
1836		V_state_change_timers_running = 1;
1837	}
1838
1839	/* We are in fasttimo, so be quick about it. */
1840	if (!state_change_retransmit_timer_expired &&
1841	    !query_response_timer_expired)
1842		return;
1843
1844	switch (inm->inm_state) {
1845	case IGMP_NOT_MEMBER:
1846	case IGMP_SILENT_MEMBER:
1847	case IGMP_SLEEPING_MEMBER:
1848	case IGMP_LAZY_MEMBER:
1849	case IGMP_AWAKENING_MEMBER:
1850	case IGMP_IDLE_MEMBER:
1851		break;
1852	case IGMP_G_QUERY_PENDING_MEMBER:
1853	case IGMP_SG_QUERY_PENDING_MEMBER:
1854		/*
1855		 * Respond to a previously pending Group-Specific
1856		 * or Group-and-Source-Specific query by enqueueing
1857		 * the appropriate Current-State report for
1858		 * immediate transmission.
1859		 */
1860		if (query_response_timer_expired) {
1861			int retval;
1862
1863			retval = igmp_v3_enqueue_group_record(qrq, inm, 0, 1,
1864			    (inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER));
1865			CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
1866			    __func__, retval);
1867			inm->inm_state = IGMP_REPORTING_MEMBER;
1868			/* XXX Clear recorded sources for next time. */
1869			inm_clear_recorded(inm);
1870		}
1871		/* FALLTHROUGH */
1872	case IGMP_REPORTING_MEMBER:
1873	case IGMP_LEAVING_MEMBER:
1874		if (state_change_retransmit_timer_expired) {
1875			/*
1876			 * State-change retransmission timer fired.
1877			 * If there are any further pending retransmissions,
1878			 * set the global pending state-change flag, and
1879			 * reset the timer.
1880			 */
1881			if (--inm->inm_scrv > 0) {
1882				inm->inm_sctimer = uri_fasthz;
1883				V_state_change_timers_running = 1;
1884			}
1885			/*
1886			 * Retransmit the previously computed state-change
1887			 * report. If there are no further pending
1888			 * retransmissions, the mbuf queue will be consumed.
1889			 * Update T0 state to T1 as we have now sent
1890			 * a state-change.
1891			 */
1892			(void)igmp_v3_merge_state_changes(inm, scq);
1893
1894			inm_commit(inm);
1895			CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
1896			    ntohl(inm->inm_addr.s_addr),
1897			    inm->inm_ifp->if_xname);
1898
1899			/*
1900			 * If we are leaving the group for good, make sure
1901			 * we release IGMP's reference to it.
1902			 * This release must be deferred using a SLIST,
1903			 * as we are called from a loop which traverses
1904			 * the in_ifmultiaddr TAILQ.
1905			 */
1906			if (inm->inm_state == IGMP_LEAVING_MEMBER &&
1907			    inm->inm_scrv == 0) {
1908				inm->inm_state = IGMP_NOT_MEMBER;
1909				SLIST_INSERT_HEAD(&igi->igi_relinmhead,
1910				    inm, inm_nrele);
1911			}
1912		}
1913		break;
1914	}
1915}
1916
1917
1918/*
1919 * Suppress a group's pending response to a group or source/group query.
1920 *
1921 * Do NOT suppress state changes. This leads to IGMPv3 inconsistency.
1922 * Do NOT update ST1/ST0 as this operation merely suppresses
1923 * the currently pending group record.
1924 * Do NOT suppress the response to a general query. It is possible but
1925 * it would require adding another state or flag.
1926 */
1927static void
1928igmp_v3_suppress_group_record(struct in_multi *inm)
1929{
1930
1931	IN_MULTI_LOCK_ASSERT();
1932
1933	KASSERT(inm->inm_igi->igi_version == IGMP_VERSION_3,
1934		("%s: not IGMPv3 mode on link", __func__));
1935
1936	if (inm->inm_state != IGMP_G_QUERY_PENDING_MEMBER ||
1937	    inm->inm_state != IGMP_SG_QUERY_PENDING_MEMBER)
1938		return;
1939
1940	if (inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER)
1941		inm_clear_recorded(inm);
1942
1943	inm->inm_timer = 0;
1944	inm->inm_state = IGMP_REPORTING_MEMBER;
1945}
1946
1947/*
1948 * Switch to a different IGMP version on the given interface,
1949 * as per Section 7.2.1.
1950 */
1951static void
1952igmp_set_version(struct igmp_ifsoftc *igi, const int version)
1953{
1954	int old_version_timer;
1955
1956	IGMP_LOCK_ASSERT();
1957
1958	CTR4(KTR_IGMPV3, "%s: switching to v%d on ifp %p(%s)", __func__,
1959	    version, igi->igi_ifp, igi->igi_ifp->if_xname);
1960
1961	if (version == IGMP_VERSION_1 || version == IGMP_VERSION_2) {
1962		/*
1963		 * Compute the "Older Version Querier Present" timer as per
1964		 * Section 8.12.
1965		 */
1966		old_version_timer = igi->igi_rv * igi->igi_qi + igi->igi_qri;
1967		old_version_timer *= PR_SLOWHZ;
1968
1969		if (version == IGMP_VERSION_1) {
1970			igi->igi_v1_timer = old_version_timer;
1971			igi->igi_v2_timer = 0;
1972		} else if (version == IGMP_VERSION_2) {
1973			igi->igi_v1_timer = 0;
1974			igi->igi_v2_timer = old_version_timer;
1975		}
1976	}
1977
1978	if (igi->igi_v1_timer == 0 && igi->igi_v2_timer > 0) {
1979		if (igi->igi_version != IGMP_VERSION_2) {
1980			igi->igi_version = IGMP_VERSION_2;
1981			igmp_v3_cancel_link_timers(igi);
1982		}
1983	} else if (igi->igi_v1_timer > 0) {
1984		if (igi->igi_version != IGMP_VERSION_1) {
1985			igi->igi_version = IGMP_VERSION_1;
1986			igmp_v3_cancel_link_timers(igi);
1987		}
1988	}
1989}
1990
1991/*
1992 * Cancel pending IGMPv3 timers for the given link and all groups
1993 * joined on it; state-change, general-query, and group-query timers.
1994 *
1995 * Only ever called on a transition from v3 to Compatibility mode. Kill
1996 * the timers stone dead (this may be expensive for large N groups), they
1997 * will be restarted if Compatibility Mode deems that they must be due to
1998 * query processing.
1999 */
2000static void
2001igmp_v3_cancel_link_timers(struct igmp_ifsoftc *igi)
2002{
2003	struct ifmultiaddr	*ifma;
2004	struct ifnet		*ifp;
2005	struct in_multi		*inm, *tinm;
2006
2007	CTR3(KTR_IGMPV3, "%s: cancel v3 timers on ifp %p(%s)", __func__,
2008	    igi->igi_ifp, igi->igi_ifp->if_xname);
2009
2010	IN_MULTI_LOCK_ASSERT();
2011	IGMP_LOCK_ASSERT();
2012
2013	/*
2014	 * Stop the v3 General Query Response on this link stone dead.
2015	 * If fasttimo is woken up due to V_interface_timers_running,
2016	 * the flag will be cleared if there are no pending link timers.
2017	 */
2018	igi->igi_v3_timer = 0;
2019
2020	/*
2021	 * Now clear the current-state and state-change report timers
2022	 * for all memberships scoped to this link.
2023	 */
2024	ifp = igi->igi_ifp;
2025	IF_ADDR_RLOCK(ifp);
2026	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2027		if (ifma->ifma_addr->sa_family != AF_INET ||
2028		    ifma->ifma_protospec == NULL)
2029			continue;
2030		inm = (struct in_multi *)ifma->ifma_protospec;
2031		switch (inm->inm_state) {
2032		case IGMP_NOT_MEMBER:
2033		case IGMP_SILENT_MEMBER:
2034		case IGMP_IDLE_MEMBER:
2035		case IGMP_LAZY_MEMBER:
2036		case IGMP_SLEEPING_MEMBER:
2037		case IGMP_AWAKENING_MEMBER:
2038			/*
2039			 * These states are either not relevant in v3 mode,
2040			 * or are unreported. Do nothing.
2041			 */
2042			break;
2043		case IGMP_LEAVING_MEMBER:
2044			/*
2045			 * If we are leaving the group and switching to
2046			 * compatibility mode, we need to release the final
2047			 * reference held for issuing the INCLUDE {}, and
2048			 * transition to REPORTING to ensure the host leave
2049			 * message is sent upstream to the old querier --
2050			 * transition to NOT would lose the leave and race.
2051			 */
2052			SLIST_INSERT_HEAD(&igi->igi_relinmhead, inm, inm_nrele);
2053			/* FALLTHROUGH */
2054		case IGMP_G_QUERY_PENDING_MEMBER:
2055		case IGMP_SG_QUERY_PENDING_MEMBER:
2056			inm_clear_recorded(inm);
2057			/* FALLTHROUGH */
2058		case IGMP_REPORTING_MEMBER:
2059			inm->inm_state = IGMP_REPORTING_MEMBER;
2060			break;
2061		}
2062		/*
2063		 * Always clear state-change and group report timers.
2064		 * Free any pending IGMPv3 state-change records.
2065		 */
2066		inm->inm_sctimer = 0;
2067		inm->inm_timer = 0;
2068		mbufq_drain(&inm->inm_scq);
2069	}
2070	IF_ADDR_RUNLOCK(ifp);
2071	SLIST_FOREACH_SAFE(inm, &igi->igi_relinmhead, inm_nrele, tinm) {
2072		SLIST_REMOVE_HEAD(&igi->igi_relinmhead, inm_nrele);
2073		inm_release_locked(inm);
2074	}
2075}
2076
2077/*
2078 * Update the Older Version Querier Present timers for a link.
2079 * See Section 7.2.1 of RFC 3376.
2080 */
2081static void
2082igmp_v1v2_process_querier_timers(struct igmp_ifsoftc *igi)
2083{
2084
2085	IGMP_LOCK_ASSERT();
2086
2087	if (igi->igi_v1_timer == 0 && igi->igi_v2_timer == 0) {
2088		/*
2089		 * IGMPv1 and IGMPv2 Querier Present timers expired.
2090		 *
2091		 * Revert to IGMPv3.
2092		 */
2093		if (igi->igi_version != IGMP_VERSION_3) {
2094			CTR5(KTR_IGMPV3,
2095			    "%s: transition from v%d -> v%d on %p(%s)",
2096			    __func__, igi->igi_version, IGMP_VERSION_3,
2097			    igi->igi_ifp, igi->igi_ifp->if_xname);
2098			igi->igi_version = IGMP_VERSION_3;
2099		}
2100	} else if (igi->igi_v1_timer == 0 && igi->igi_v2_timer > 0) {
2101		/*
2102		 * IGMPv1 Querier Present timer expired,
2103		 * IGMPv2 Querier Present timer running.
2104		 * If IGMPv2 was disabled since last timeout,
2105		 * revert to IGMPv3.
2106		 * If IGMPv2 is enabled, revert to IGMPv2.
2107		 */
2108		if (!V_igmp_v2enable) {
2109			CTR5(KTR_IGMPV3,
2110			    "%s: transition from v%d -> v%d on %p(%s)",
2111			    __func__, igi->igi_version, IGMP_VERSION_3,
2112			    igi->igi_ifp, igi->igi_ifp->if_xname);
2113			igi->igi_v2_timer = 0;
2114			igi->igi_version = IGMP_VERSION_3;
2115		} else {
2116			--igi->igi_v2_timer;
2117			if (igi->igi_version != IGMP_VERSION_2) {
2118				CTR5(KTR_IGMPV3,
2119				    "%s: transition from v%d -> v%d on %p(%s)",
2120				    __func__, igi->igi_version, IGMP_VERSION_2,
2121				    igi->igi_ifp, igi->igi_ifp->if_xname);
2122				igi->igi_version = IGMP_VERSION_2;
2123				igmp_v3_cancel_link_timers(igi);
2124			}
2125		}
2126	} else if (igi->igi_v1_timer > 0) {
2127		/*
2128		 * IGMPv1 Querier Present timer running.
2129		 * Stop IGMPv2 timer if running.
2130		 *
2131		 * If IGMPv1 was disabled since last timeout,
2132		 * revert to IGMPv3.
2133		 * If IGMPv1 is enabled, reset IGMPv2 timer if running.
2134		 */
2135		if (!V_igmp_v1enable) {
2136			CTR5(KTR_IGMPV3,
2137			    "%s: transition from v%d -> v%d on %p(%s)",
2138			    __func__, igi->igi_version, IGMP_VERSION_3,
2139			    igi->igi_ifp, igi->igi_ifp->if_xname);
2140			igi->igi_v1_timer = 0;
2141			igi->igi_version = IGMP_VERSION_3;
2142		} else {
2143			--igi->igi_v1_timer;
2144		}
2145		if (igi->igi_v2_timer > 0) {
2146			CTR3(KTR_IGMPV3,
2147			    "%s: cancel v2 timer on %p(%s)",
2148			    __func__, igi->igi_ifp, igi->igi_ifp->if_xname);
2149			igi->igi_v2_timer = 0;
2150		}
2151	}
2152}
2153
2154/*
2155 * Global slowtimo handler.
2156 * VIMAGE: Timeout handlers are expected to service all vimages.
2157 */
2158void
2159igmp_slowtimo(void)
2160{
2161	VNET_ITERATOR_DECL(vnet_iter);
2162
2163	VNET_LIST_RLOCK_NOSLEEP();
2164	VNET_FOREACH(vnet_iter) {
2165		CURVNET_SET(vnet_iter);
2166		igmp_slowtimo_vnet();
2167		CURVNET_RESTORE();
2168	}
2169	VNET_LIST_RUNLOCK_NOSLEEP();
2170}
2171
2172/*
2173 * Per-vnet slowtimo handler.
2174 */
2175static void
2176igmp_slowtimo_vnet(void)
2177{
2178	struct igmp_ifsoftc *igi;
2179
2180	IGMP_LOCK();
2181
2182	LIST_FOREACH(igi, &V_igi_head, igi_link) {
2183		igmp_v1v2_process_querier_timers(igi);
2184	}
2185
2186	IGMP_UNLOCK();
2187}
2188
2189/*
2190 * Dispatch an IGMPv1/v2 host report or leave message.
2191 * These are always small enough to fit inside a single mbuf.
2192 */
2193static int
2194igmp_v1v2_queue_report(struct in_multi *inm, const int type)
2195{
2196	struct ifnet		*ifp;
2197	struct igmp		*igmp;
2198	struct ip		*ip;
2199	struct mbuf		*m;
2200
2201	IN_MULTI_LOCK_ASSERT();
2202	IGMP_LOCK_ASSERT();
2203
2204	ifp = inm->inm_ifp;
2205
2206	m = m_gethdr(M_NOWAIT, MT_DATA);
2207	if (m == NULL)
2208		return (ENOMEM);
2209	M_ALIGN(m, sizeof(struct ip) + sizeof(struct igmp));
2210
2211	m->m_pkthdr.len = sizeof(struct ip) + sizeof(struct igmp);
2212
2213	m->m_data += sizeof(struct ip);
2214	m->m_len = sizeof(struct igmp);
2215
2216	igmp = mtod(m, struct igmp *);
2217	igmp->igmp_type = type;
2218	igmp->igmp_code = 0;
2219	igmp->igmp_group = inm->inm_addr;
2220	igmp->igmp_cksum = 0;
2221	igmp->igmp_cksum = in_cksum(m, sizeof(struct igmp));
2222
2223	m->m_data -= sizeof(struct ip);
2224	m->m_len += sizeof(struct ip);
2225
2226	ip = mtod(m, struct ip *);
2227	ip->ip_tos = 0;
2228	ip->ip_len = htons(sizeof(struct ip) + sizeof(struct igmp));
2229	ip->ip_off = 0;
2230	ip->ip_p = IPPROTO_IGMP;
2231	ip->ip_src.s_addr = INADDR_ANY;
2232
2233	if (type == IGMP_HOST_LEAVE_MESSAGE)
2234		ip->ip_dst.s_addr = htonl(INADDR_ALLRTRS_GROUP);
2235	else
2236		ip->ip_dst = inm->inm_addr;
2237
2238	igmp_save_context(m, ifp);
2239
2240	m->m_flags |= M_IGMPV2;
2241	if (inm->inm_igi->igi_flags & IGIF_LOOPBACK)
2242		m->m_flags |= M_IGMP_LOOP;
2243
2244	CTR2(KTR_IGMPV3, "%s: netisr_dispatch(NETISR_IGMP, %p)", __func__, m);
2245	netisr_dispatch(NETISR_IGMP, m);
2246
2247	return (0);
2248}
2249
2250/*
2251 * Process a state change from the upper layer for the given IPv4 group.
2252 *
2253 * Each socket holds a reference on the in_multi in its own ip_moptions.
2254 * The socket layer will have made the necessary updates to.the group
2255 * state, it is now up to IGMP to issue a state change report if there
2256 * has been any change between T0 (when the last state-change was issued)
2257 * and T1 (now).
2258 *
2259 * We use the IGMPv3 state machine at group level. The IGMP module
2260 * however makes the decision as to which IGMP protocol version to speak.
2261 * A state change *from* INCLUDE {} always means an initial join.
2262 * A state change *to* INCLUDE {} always means a final leave.
2263 *
2264 * FUTURE: If IGIF_V3LITE is enabled for this interface, then we can
2265 * save ourselves a bunch of work; any exclusive mode groups need not
2266 * compute source filter lists.
2267 *
2268 * VIMAGE: curvnet should have been set by caller, as this routine
2269 * is called from the socket option handlers.
2270 */
2271int
2272igmp_change_state(struct in_multi *inm)
2273{
2274	struct igmp_ifsoftc *igi;
2275	struct ifnet *ifp;
2276	int error;
2277
2278	IN_MULTI_LOCK_ASSERT();
2279
2280	error = 0;
2281
2282	/*
2283	 * Try to detect if the upper layer just asked us to change state
2284	 * for an interface which has now gone away.
2285	 */
2286	KASSERT(inm->inm_ifma != NULL, ("%s: no ifma", __func__));
2287	ifp = inm->inm_ifma->ifma_ifp;
2288	/*
2289	 * Sanity check that netinet's notion of ifp is the
2290	 * same as net's.
2291	 */
2292	KASSERT(inm->inm_ifp == ifp, ("%s: bad ifp", __func__));
2293
2294	IGMP_LOCK();
2295
2296	igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
2297	KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
2298
2299	/*
2300	 * If we detect a state transition to or from MCAST_UNDEFINED
2301	 * for this group, then we are starting or finishing an IGMP
2302	 * life cycle for this group.
2303	 */
2304	if (inm->inm_st[1].iss_fmode != inm->inm_st[0].iss_fmode) {
2305		CTR3(KTR_IGMPV3, "%s: inm transition %d -> %d", __func__,
2306		    inm->inm_st[0].iss_fmode, inm->inm_st[1].iss_fmode);
2307		if (inm->inm_st[0].iss_fmode == MCAST_UNDEFINED) {
2308			CTR1(KTR_IGMPV3, "%s: initial join", __func__);
2309			error = igmp_initial_join(inm, igi);
2310			goto out_locked;
2311		} else if (inm->inm_st[1].iss_fmode == MCAST_UNDEFINED) {
2312			CTR1(KTR_IGMPV3, "%s: final leave", __func__);
2313			igmp_final_leave(inm, igi);
2314			goto out_locked;
2315		}
2316	} else {
2317		CTR1(KTR_IGMPV3, "%s: filter set change", __func__);
2318	}
2319
2320	error = igmp_handle_state_change(inm, igi);
2321
2322out_locked:
2323	IGMP_UNLOCK();
2324	return (error);
2325}
2326
2327/*
2328 * Perform the initial join for an IGMP group.
2329 *
2330 * When joining a group:
2331 *  If the group should have its IGMP traffic suppressed, do nothing.
2332 *  IGMPv1 starts sending IGMPv1 host membership reports.
2333 *  IGMPv2 starts sending IGMPv2 host membership reports.
2334 *  IGMPv3 will schedule an IGMPv3 state-change report containing the
2335 *  initial state of the membership.
2336 */
2337static int
2338igmp_initial_join(struct in_multi *inm, struct igmp_ifsoftc *igi)
2339{
2340	struct ifnet		*ifp;
2341	struct mbufq		*mq;
2342	int			 error, retval, syncstates;
2343
2344	CTR4(KTR_IGMPV3, "%s: initial join 0x%08x on ifp %p(%s)", __func__,
2345	    ntohl(inm->inm_addr.s_addr), inm->inm_ifp, inm->inm_ifp->if_xname);
2346
2347	error = 0;
2348	syncstates = 1;
2349
2350	ifp = inm->inm_ifp;
2351
2352	IN_MULTI_LOCK_ASSERT();
2353	IGMP_LOCK_ASSERT();
2354
2355	KASSERT(igi && igi->igi_ifp == ifp, ("%s: inconsistent ifp", __func__));
2356
2357	/*
2358	 * Groups joined on loopback or marked as 'not reported',
2359	 * e.g. 224.0.0.1, enter the IGMP_SILENT_MEMBER state and
2360	 * are never reported in any IGMP protocol exchanges.
2361	 * All other groups enter the appropriate IGMP state machine
2362	 * for the version in use on this link.
2363	 * A link marked as IGIF_SILENT causes IGMP to be completely
2364	 * disabled for the link.
2365	 */
2366	if ((ifp->if_flags & IFF_LOOPBACK) ||
2367	    (igi->igi_flags & IGIF_SILENT) ||
2368	    !igmp_isgroupreported(inm->inm_addr)) {
2369		CTR1(KTR_IGMPV3,
2370"%s: not kicking state machine for silent group", __func__);
2371		inm->inm_state = IGMP_SILENT_MEMBER;
2372		inm->inm_timer = 0;
2373	} else {
2374		/*
2375		 * Deal with overlapping in_multi lifecycle.
2376		 * If this group was LEAVING, then make sure
2377		 * we drop the reference we picked up to keep the
2378		 * group around for the final INCLUDE {} enqueue.
2379		 */
2380		if (igi->igi_version == IGMP_VERSION_3 &&
2381		    inm->inm_state == IGMP_LEAVING_MEMBER)
2382			inm_release_locked(inm);
2383
2384		inm->inm_state = IGMP_REPORTING_MEMBER;
2385
2386		switch (igi->igi_version) {
2387		case IGMP_VERSION_1:
2388		case IGMP_VERSION_2:
2389			inm->inm_state = IGMP_IDLE_MEMBER;
2390			error = igmp_v1v2_queue_report(inm,
2391			    (igi->igi_version == IGMP_VERSION_2) ?
2392			     IGMP_v2_HOST_MEMBERSHIP_REPORT :
2393			     IGMP_v1_HOST_MEMBERSHIP_REPORT);
2394			if (error == 0) {
2395				inm->inm_timer = IGMP_RANDOM_DELAY(
2396				    IGMP_V1V2_MAX_RI * PR_FASTHZ);
2397				V_current_state_timers_running = 1;
2398			}
2399			break;
2400
2401		case IGMP_VERSION_3:
2402			/*
2403			 * Defer update of T0 to T1, until the first copy
2404			 * of the state change has been transmitted.
2405			 */
2406			syncstates = 0;
2407
2408			/*
2409			 * Immediately enqueue a State-Change Report for
2410			 * this interface, freeing any previous reports.
2411			 * Don't kick the timers if there is nothing to do,
2412			 * or if an error occurred.
2413			 */
2414			mq = &inm->inm_scq;
2415			mbufq_drain(mq);
2416			retval = igmp_v3_enqueue_group_record(mq, inm, 1,
2417			    0, 0);
2418			CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
2419			    __func__, retval);
2420			if (retval <= 0) {
2421				error = retval * -1;
2422				break;
2423			}
2424
2425			/*
2426			 * Schedule transmission of pending state-change
2427			 * report up to RV times for this link. The timer
2428			 * will fire at the next igmp_fasttimo (~200ms),
2429			 * giving us an opportunity to merge the reports.
2430			 */
2431			if (igi->igi_flags & IGIF_LOOPBACK) {
2432				inm->inm_scrv = 1;
2433			} else {
2434				KASSERT(igi->igi_rv > 1,
2435				   ("%s: invalid robustness %d", __func__,
2436				    igi->igi_rv));
2437				inm->inm_scrv = igi->igi_rv;
2438			}
2439			inm->inm_sctimer = 1;
2440			V_state_change_timers_running = 1;
2441
2442			error = 0;
2443			break;
2444		}
2445	}
2446
2447	/*
2448	 * Only update the T0 state if state change is atomic,
2449	 * i.e. we don't need to wait for a timer to fire before we
2450	 * can consider the state change to have been communicated.
2451	 */
2452	if (syncstates) {
2453		inm_commit(inm);
2454		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2455		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2456	}
2457
2458	return (error);
2459}
2460
2461/*
2462 * Issue an intermediate state change during the IGMP life-cycle.
2463 */
2464static int
2465igmp_handle_state_change(struct in_multi *inm, struct igmp_ifsoftc *igi)
2466{
2467	struct ifnet		*ifp;
2468	int			 retval;
2469
2470	CTR4(KTR_IGMPV3, "%s: state change for 0x%08x on ifp %p(%s)", __func__,
2471	    ntohl(inm->inm_addr.s_addr), inm->inm_ifp, inm->inm_ifp->if_xname);
2472
2473	ifp = inm->inm_ifp;
2474
2475	IN_MULTI_LOCK_ASSERT();
2476	IGMP_LOCK_ASSERT();
2477
2478	KASSERT(igi && igi->igi_ifp == ifp, ("%s: inconsistent ifp", __func__));
2479
2480	if ((ifp->if_flags & IFF_LOOPBACK) ||
2481	    (igi->igi_flags & IGIF_SILENT) ||
2482	    !igmp_isgroupreported(inm->inm_addr) ||
2483	    (igi->igi_version != IGMP_VERSION_3)) {
2484		if (!igmp_isgroupreported(inm->inm_addr)) {
2485			CTR1(KTR_IGMPV3,
2486"%s: not kicking state machine for silent group", __func__);
2487		}
2488		CTR1(KTR_IGMPV3, "%s: nothing to do", __func__);
2489		inm_commit(inm);
2490		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2491		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2492		return (0);
2493	}
2494
2495	mbufq_drain(&inm->inm_scq);
2496
2497	retval = igmp_v3_enqueue_group_record(&inm->inm_scq, inm, 1, 0, 0);
2498	CTR2(KTR_IGMPV3, "%s: enqueue record = %d", __func__, retval);
2499	if (retval <= 0)
2500		return (-retval);
2501
2502	/*
2503	 * If record(s) were enqueued, start the state-change
2504	 * report timer for this group.
2505	 */
2506	inm->inm_scrv = ((igi->igi_flags & IGIF_LOOPBACK) ? 1 : igi->igi_rv);
2507	inm->inm_sctimer = 1;
2508	V_state_change_timers_running = 1;
2509
2510	return (0);
2511}
2512
2513/*
2514 * Perform the final leave for an IGMP group.
2515 *
2516 * When leaving a group:
2517 *  IGMPv1 does nothing.
2518 *  IGMPv2 sends a host leave message, if and only if we are the reporter.
2519 *  IGMPv3 enqueues a state-change report containing a transition
2520 *  to INCLUDE {} for immediate transmission.
2521 */
2522static void
2523igmp_final_leave(struct in_multi *inm, struct igmp_ifsoftc *igi)
2524{
2525	int syncstates;
2526
2527	syncstates = 1;
2528
2529	CTR4(KTR_IGMPV3, "%s: final leave 0x%08x on ifp %p(%s)",
2530	    __func__, ntohl(inm->inm_addr.s_addr), inm->inm_ifp,
2531	    inm->inm_ifp->if_xname);
2532
2533	IN_MULTI_LOCK_ASSERT();
2534	IGMP_LOCK_ASSERT();
2535
2536	switch (inm->inm_state) {
2537	case IGMP_NOT_MEMBER:
2538	case IGMP_SILENT_MEMBER:
2539	case IGMP_LEAVING_MEMBER:
2540		/* Already leaving or left; do nothing. */
2541		CTR1(KTR_IGMPV3,
2542"%s: not kicking state machine for silent group", __func__);
2543		break;
2544	case IGMP_REPORTING_MEMBER:
2545	case IGMP_IDLE_MEMBER:
2546	case IGMP_G_QUERY_PENDING_MEMBER:
2547	case IGMP_SG_QUERY_PENDING_MEMBER:
2548		if (igi->igi_version == IGMP_VERSION_2) {
2549#ifdef INVARIANTS
2550			if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER ||
2551			    inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER)
2552			panic("%s: IGMPv3 state reached, not IGMPv3 mode",
2553			     __func__);
2554#endif
2555			igmp_v1v2_queue_report(inm, IGMP_HOST_LEAVE_MESSAGE);
2556			inm->inm_state = IGMP_NOT_MEMBER;
2557		} else if (igi->igi_version == IGMP_VERSION_3) {
2558			/*
2559			 * Stop group timer and all pending reports.
2560			 * Immediately enqueue a state-change report
2561			 * TO_IN {} to be sent on the next fast timeout,
2562			 * giving us an opportunity to merge reports.
2563			 */
2564			mbufq_drain(&inm->inm_scq);
2565			inm->inm_timer = 0;
2566			if (igi->igi_flags & IGIF_LOOPBACK) {
2567				inm->inm_scrv = 1;
2568			} else {
2569				inm->inm_scrv = igi->igi_rv;
2570			}
2571			CTR4(KTR_IGMPV3, "%s: Leaving 0x%08x/%s with %d "
2572			    "pending retransmissions.", __func__,
2573			    ntohl(inm->inm_addr.s_addr),
2574			    inm->inm_ifp->if_xname, inm->inm_scrv);
2575			if (inm->inm_scrv == 0) {
2576				inm->inm_state = IGMP_NOT_MEMBER;
2577				inm->inm_sctimer = 0;
2578			} else {
2579				int retval;
2580
2581				inm_acquire_locked(inm);
2582
2583				retval = igmp_v3_enqueue_group_record(
2584				    &inm->inm_scq, inm, 1, 0, 0);
2585				KASSERT(retval != 0,
2586				    ("%s: enqueue record = %d", __func__,
2587				     retval));
2588
2589				inm->inm_state = IGMP_LEAVING_MEMBER;
2590				inm->inm_sctimer = 1;
2591				V_state_change_timers_running = 1;
2592				syncstates = 0;
2593			}
2594			break;
2595		}
2596		break;
2597	case IGMP_LAZY_MEMBER:
2598	case IGMP_SLEEPING_MEMBER:
2599	case IGMP_AWAKENING_MEMBER:
2600		/* Our reports are suppressed; do nothing. */
2601		break;
2602	}
2603
2604	if (syncstates) {
2605		inm_commit(inm);
2606		CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2607		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2608		inm->inm_st[1].iss_fmode = MCAST_UNDEFINED;
2609		CTR3(KTR_IGMPV3, "%s: T1 now MCAST_UNDEFINED for 0x%08x/%s",
2610		    __func__, ntohl(inm->inm_addr.s_addr),
2611		    inm->inm_ifp->if_xname);
2612	}
2613}
2614
2615/*
2616 * Enqueue an IGMPv3 group record to the given output queue.
2617 *
2618 * XXX This function could do with having the allocation code
2619 * split out, and the multiple-tree-walks coalesced into a single
2620 * routine as has been done in igmp_v3_enqueue_filter_change().
2621 *
2622 * If is_state_change is zero, a current-state record is appended.
2623 * If is_state_change is non-zero, a state-change report is appended.
2624 *
2625 * If is_group_query is non-zero, an mbuf packet chain is allocated.
2626 * If is_group_query is zero, and if there is a packet with free space
2627 * at the tail of the queue, it will be appended to providing there
2628 * is enough free space.
2629 * Otherwise a new mbuf packet chain is allocated.
2630 *
2631 * If is_source_query is non-zero, each source is checked to see if
2632 * it was recorded for a Group-Source query, and will be omitted if
2633 * it is not both in-mode and recorded.
2634 *
2635 * The function will attempt to allocate leading space in the packet
2636 * for the IP/IGMP header to be prepended without fragmenting the chain.
2637 *
2638 * If successful the size of all data appended to the queue is returned,
2639 * otherwise an error code less than zero is returned, or zero if
2640 * no record(s) were appended.
2641 */
2642static int
2643igmp_v3_enqueue_group_record(struct mbufq *mq, struct in_multi *inm,
2644    const int is_state_change, const int is_group_query,
2645    const int is_source_query)
2646{
2647	struct igmp_grouprec	 ig;
2648	struct igmp_grouprec	*pig;
2649	struct ifnet		*ifp;
2650	struct ip_msource	*ims, *nims;
2651	struct mbuf		*m0, *m, *md;
2652	int			 error, is_filter_list_change;
2653	int			 minrec0len, m0srcs, msrcs, nbytes, off;
2654	int			 record_has_sources;
2655	int			 now;
2656	int			 type;
2657	in_addr_t		 naddr;
2658	uint8_t			 mode;
2659
2660	IN_MULTI_LOCK_ASSERT();
2661
2662	error = 0;
2663	ifp = inm->inm_ifp;
2664	is_filter_list_change = 0;
2665	m = NULL;
2666	m0 = NULL;
2667	m0srcs = 0;
2668	msrcs = 0;
2669	nbytes = 0;
2670	nims = NULL;
2671	record_has_sources = 1;
2672	pig = NULL;
2673	type = IGMP_DO_NOTHING;
2674	mode = inm->inm_st[1].iss_fmode;
2675
2676	/*
2677	 * If we did not transition out of ASM mode during t0->t1,
2678	 * and there are no source nodes to process, we can skip
2679	 * the generation of source records.
2680	 */
2681	if (inm->inm_st[0].iss_asm > 0 && inm->inm_st[1].iss_asm > 0 &&
2682	    inm->inm_nsrc == 0)
2683		record_has_sources = 0;
2684
2685	if (is_state_change) {
2686		/*
2687		 * Queue a state change record.
2688		 * If the mode did not change, and there are non-ASM
2689		 * listeners or source filters present,
2690		 * we potentially need to issue two records for the group.
2691		 * If we are transitioning to MCAST_UNDEFINED, we need
2692		 * not send any sources.
2693		 * If there are ASM listeners, and there was no filter
2694		 * mode transition of any kind, do nothing.
2695		 */
2696		if (mode != inm->inm_st[0].iss_fmode) {
2697			if (mode == MCAST_EXCLUDE) {
2698				CTR1(KTR_IGMPV3, "%s: change to EXCLUDE",
2699				    __func__);
2700				type = IGMP_CHANGE_TO_EXCLUDE_MODE;
2701			} else {
2702				CTR1(KTR_IGMPV3, "%s: change to INCLUDE",
2703				    __func__);
2704				type = IGMP_CHANGE_TO_INCLUDE_MODE;
2705				if (mode == MCAST_UNDEFINED)
2706					record_has_sources = 0;
2707			}
2708		} else {
2709			if (record_has_sources) {
2710				is_filter_list_change = 1;
2711			} else {
2712				type = IGMP_DO_NOTHING;
2713			}
2714		}
2715	} else {
2716		/*
2717		 * Queue a current state record.
2718		 */
2719		if (mode == MCAST_EXCLUDE) {
2720			type = IGMP_MODE_IS_EXCLUDE;
2721		} else if (mode == MCAST_INCLUDE) {
2722			type = IGMP_MODE_IS_INCLUDE;
2723			KASSERT(inm->inm_st[1].iss_asm == 0,
2724			    ("%s: inm %p is INCLUDE but ASM count is %d",
2725			     __func__, inm, inm->inm_st[1].iss_asm));
2726		}
2727	}
2728
2729	/*
2730	 * Generate the filter list changes using a separate function.
2731	 */
2732	if (is_filter_list_change)
2733		return (igmp_v3_enqueue_filter_change(mq, inm));
2734
2735	if (type == IGMP_DO_NOTHING) {
2736		CTR3(KTR_IGMPV3, "%s: nothing to do for 0x%08x/%s", __func__,
2737		    ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2738		return (0);
2739	}
2740
2741	/*
2742	 * If any sources are present, we must be able to fit at least
2743	 * one in the trailing space of the tail packet's mbuf,
2744	 * ideally more.
2745	 */
2746	minrec0len = sizeof(struct igmp_grouprec);
2747	if (record_has_sources)
2748		minrec0len += sizeof(in_addr_t);
2749
2750	CTR4(KTR_IGMPV3, "%s: queueing %s for 0x%08x/%s", __func__,
2751	    igmp_rec_type_to_str(type), ntohl(inm->inm_addr.s_addr),
2752	    inm->inm_ifp->if_xname);
2753
2754	/*
2755	 * Check if we have a packet in the tail of the queue for this
2756	 * group into which the first group record for this group will fit.
2757	 * Otherwise allocate a new packet.
2758	 * Always allocate leading space for IP+RA_OPT+IGMP+REPORT.
2759	 * Note: Group records for G/GSR query responses MUST be sent
2760	 * in their own packet.
2761	 */
2762	m0 = mbufq_last(mq);
2763	if (!is_group_query &&
2764	    m0 != NULL &&
2765	    (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <= IGMP_V3_REPORT_MAXRECS) &&
2766	    (m0->m_pkthdr.len + minrec0len) <
2767	     (ifp->if_mtu - IGMP_LEADINGSPACE)) {
2768		m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
2769			    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2770		m = m0;
2771		CTR1(KTR_IGMPV3, "%s: use existing packet", __func__);
2772	} else {
2773		if (mbufq_full(mq)) {
2774			CTR1(KTR_IGMPV3, "%s: outbound queue full", __func__);
2775			return (-ENOMEM);
2776		}
2777		m = NULL;
2778		m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
2779		    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2780		if (!is_state_change && !is_group_query) {
2781			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2782			if (m)
2783				m->m_data += IGMP_LEADINGSPACE;
2784		}
2785		if (m == NULL) {
2786			m = m_gethdr(M_NOWAIT, MT_DATA);
2787			if (m)
2788				M_ALIGN(m, IGMP_LEADINGSPACE);
2789		}
2790		if (m == NULL)
2791			return (-ENOMEM);
2792
2793		igmp_save_context(m, ifp);
2794
2795		CTR1(KTR_IGMPV3, "%s: allocated first packet", __func__);
2796	}
2797
2798	/*
2799	 * Append group record.
2800	 * If we have sources, we don't know how many yet.
2801	 */
2802	ig.ig_type = type;
2803	ig.ig_datalen = 0;
2804	ig.ig_numsrc = 0;
2805	ig.ig_group = inm->inm_addr;
2806	if (!m_append(m, sizeof(struct igmp_grouprec), (void *)&ig)) {
2807		if (m != m0)
2808			m_freem(m);
2809		CTR1(KTR_IGMPV3, "%s: m_append() failed.", __func__);
2810		return (-ENOMEM);
2811	}
2812	nbytes += sizeof(struct igmp_grouprec);
2813
2814	/*
2815	 * Append as many sources as will fit in the first packet.
2816	 * If we are appending to a new packet, the chain allocation
2817	 * may potentially use clusters; use m_getptr() in this case.
2818	 * If we are appending to an existing packet, we need to obtain
2819	 * a pointer to the group record after m_append(), in case a new
2820	 * mbuf was allocated.
2821	 * Only append sources which are in-mode at t1. If we are
2822	 * transitioning to MCAST_UNDEFINED state on the group, do not
2823	 * include source entries.
2824	 * Only report recorded sources in our filter set when responding
2825	 * to a group-source query.
2826	 */
2827	if (record_has_sources) {
2828		if (m == m0) {
2829			md = m_last(m);
2830			pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) +
2831			    md->m_len - nbytes);
2832		} else {
2833			md = m_getptr(m, 0, &off);
2834			pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) +
2835			    off);
2836		}
2837		msrcs = 0;
2838		RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, nims) {
2839			CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2840			    ims->ims_haddr);
2841			now = ims_get_mode(inm, ims, 1);
2842			CTR2(KTR_IGMPV3, "%s: node is %d", __func__, now);
2843			if ((now != mode) ||
2844			    (now == mode && mode == MCAST_UNDEFINED)) {
2845				CTR1(KTR_IGMPV3, "%s: skip node", __func__);
2846				continue;
2847			}
2848			if (is_source_query && ims->ims_stp == 0) {
2849				CTR1(KTR_IGMPV3, "%s: skip unrecorded node",
2850				    __func__);
2851				continue;
2852			}
2853			CTR1(KTR_IGMPV3, "%s: append node", __func__);
2854			naddr = htonl(ims->ims_haddr);
2855			if (!m_append(m, sizeof(in_addr_t), (void *)&naddr)) {
2856				if (m != m0)
2857					m_freem(m);
2858				CTR1(KTR_IGMPV3, "%s: m_append() failed.",
2859				    __func__);
2860				return (-ENOMEM);
2861			}
2862			nbytes += sizeof(in_addr_t);
2863			++msrcs;
2864			if (msrcs == m0srcs)
2865				break;
2866		}
2867		CTR2(KTR_IGMPV3, "%s: msrcs is %d this packet", __func__,
2868		    msrcs);
2869		pig->ig_numsrc = htons(msrcs);
2870		nbytes += (msrcs * sizeof(in_addr_t));
2871	}
2872
2873	if (is_source_query && msrcs == 0) {
2874		CTR1(KTR_IGMPV3, "%s: no recorded sources to report", __func__);
2875		if (m != m0)
2876			m_freem(m);
2877		return (0);
2878	}
2879
2880	/*
2881	 * We are good to go with first packet.
2882	 */
2883	if (m != m0) {
2884		CTR1(KTR_IGMPV3, "%s: enqueueing first packet", __func__);
2885		m->m_pkthdr.PH_vt.vt_nrecs = 1;
2886		mbufq_enqueue(mq, m);
2887	} else
2888		m->m_pkthdr.PH_vt.vt_nrecs++;
2889
2890	/*
2891	 * No further work needed if no source list in packet(s).
2892	 */
2893	if (!record_has_sources)
2894		return (nbytes);
2895
2896	/*
2897	 * Whilst sources remain to be announced, we need to allocate
2898	 * a new packet and fill out as many sources as will fit.
2899	 * Always try for a cluster first.
2900	 */
2901	while (nims != NULL) {
2902		if (mbufq_full(mq)) {
2903			CTR1(KTR_IGMPV3, "%s: outbound queue full", __func__);
2904			return (-ENOMEM);
2905		}
2906		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2907		if (m)
2908			m->m_data += IGMP_LEADINGSPACE;
2909		if (m == NULL) {
2910			m = m_gethdr(M_NOWAIT, MT_DATA);
2911			if (m)
2912				M_ALIGN(m, IGMP_LEADINGSPACE);
2913		}
2914		if (m == NULL)
2915			return (-ENOMEM);
2916		igmp_save_context(m, ifp);
2917		md = m_getptr(m, 0, &off);
2918		pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) + off);
2919		CTR1(KTR_IGMPV3, "%s: allocated next packet", __func__);
2920
2921		if (!m_append(m, sizeof(struct igmp_grouprec), (void *)&ig)) {
2922			if (m != m0)
2923				m_freem(m);
2924			CTR1(KTR_IGMPV3, "%s: m_append() failed.", __func__);
2925			return (-ENOMEM);
2926		}
2927		m->m_pkthdr.PH_vt.vt_nrecs = 1;
2928		nbytes += sizeof(struct igmp_grouprec);
2929
2930		m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
2931		    sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2932
2933		msrcs = 0;
2934		RB_FOREACH_FROM(ims, ip_msource_tree, nims) {
2935			CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2936			    ims->ims_haddr);
2937			now = ims_get_mode(inm, ims, 1);
2938			if ((now != mode) ||
2939			    (now == mode && mode == MCAST_UNDEFINED)) {
2940				CTR1(KTR_IGMPV3, "%s: skip node", __func__);
2941				continue;
2942			}
2943			if (is_source_query && ims->ims_stp == 0) {
2944				CTR1(KTR_IGMPV3, "%s: skip unrecorded node",
2945				    __func__);
2946				continue;
2947			}
2948			CTR1(KTR_IGMPV3, "%s: append node", __func__);
2949			naddr = htonl(ims->ims_haddr);
2950			if (!m_append(m, sizeof(in_addr_t), (void *)&naddr)) {
2951				if (m != m0)
2952					m_freem(m);
2953				CTR1(KTR_IGMPV3, "%s: m_append() failed.",
2954				    __func__);
2955				return (-ENOMEM);
2956			}
2957			++msrcs;
2958			if (msrcs == m0srcs)
2959				break;
2960		}
2961		pig->ig_numsrc = htons(msrcs);
2962		nbytes += (msrcs * sizeof(in_addr_t));
2963
2964		CTR1(KTR_IGMPV3, "%s: enqueueing next packet", __func__);
2965		mbufq_enqueue(mq, m);
2966	}
2967
2968	return (nbytes);
2969}
2970
2971/*
2972 * Type used to mark record pass completion.
2973 * We exploit the fact we can cast to this easily from the
2974 * current filter modes on each ip_msource node.
2975 */
2976typedef enum {
2977	REC_NONE = 0x00,	/* MCAST_UNDEFINED */
2978	REC_ALLOW = 0x01,	/* MCAST_INCLUDE */
2979	REC_BLOCK = 0x02,	/* MCAST_EXCLUDE */
2980	REC_FULL = REC_ALLOW | REC_BLOCK
2981} rectype_t;
2982
2983/*
2984 * Enqueue an IGMPv3 filter list change to the given output queue.
2985 *
2986 * Source list filter state is held in an RB-tree. When the filter list
2987 * for a group is changed without changing its mode, we need to compute
2988 * the deltas between T0 and T1 for each source in the filter set,
2989 * and enqueue the appropriate ALLOW_NEW/BLOCK_OLD records.
2990 *
2991 * As we may potentially queue two record types, and the entire R-B tree
2992 * needs to be walked at once, we break this out into its own function
2993 * so we can generate a tightly packed queue of packets.
2994 *
2995 * XXX This could be written to only use one tree walk, although that makes
2996 * serializing into the mbuf chains a bit harder. For now we do two walks
2997 * which makes things easier on us, and it may or may not be harder on
2998 * the L2 cache.
2999 *
3000 * If successful the size of all data appended to the queue is returned,
3001 * otherwise an error code less than zero is returned, or zero if
3002 * no record(s) were appended.
3003 */
3004static int
3005igmp_v3_enqueue_filter_change(struct mbufq *mq, struct in_multi *inm)
3006{
3007	static const int MINRECLEN =
3008	    sizeof(struct igmp_grouprec) + sizeof(in_addr_t);
3009	struct ifnet		*ifp;
3010	struct igmp_grouprec	 ig;
3011	struct igmp_grouprec	*pig;
3012	struct ip_msource	*ims, *nims;
3013	struct mbuf		*m, *m0, *md;
3014	in_addr_t		 naddr;
3015	int			 m0srcs, nbytes, npbytes, off, rsrcs, schanged;
3016	int			 nallow, nblock;
3017	uint8_t			 mode, now, then;
3018	rectype_t		 crt, drt, nrt;
3019
3020	IN_MULTI_LOCK_ASSERT();
3021
3022	if (inm->inm_nsrc == 0 ||
3023	    (inm->inm_st[0].iss_asm > 0 && inm->inm_st[1].iss_asm > 0))
3024		return (0);
3025
3026	ifp = inm->inm_ifp;			/* interface */
3027	mode = inm->inm_st[1].iss_fmode;	/* filter mode at t1 */
3028	crt = REC_NONE;	/* current group record type */
3029	drt = REC_NONE;	/* mask of completed group record types */
3030	nrt = REC_NONE;	/* record type for current node */
3031	m0srcs = 0;	/* # source which will fit in current mbuf chain */
3032	nbytes = 0;	/* # of bytes appended to group's state-change queue */
3033	npbytes = 0;	/* # of bytes appended this packet */
3034	rsrcs = 0;	/* # sources encoded in current record */
3035	schanged = 0;	/* # nodes encoded in overall filter change */
3036	nallow = 0;	/* # of source entries in ALLOW_NEW */
3037	nblock = 0;	/* # of source entries in BLOCK_OLD */
3038	nims = NULL;	/* next tree node pointer */
3039
3040	/*
3041	 * For each possible filter record mode.
3042	 * The first kind of source we encounter tells us which
3043	 * is the first kind of record we start appending.
3044	 * If a node transitioned to UNDEFINED at t1, its mode is treated
3045	 * as the inverse of the group's filter mode.
3046	 */
3047	while (drt != REC_FULL) {
3048		do {
3049			m0 = mbufq_last(mq);
3050			if (m0 != NULL &&
3051			    (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <=
3052			     IGMP_V3_REPORT_MAXRECS) &&
3053			    (m0->m_pkthdr.len + MINRECLEN) <
3054			     (ifp->if_mtu - IGMP_LEADINGSPACE)) {
3055				m = m0;
3056				m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
3057					    sizeof(struct igmp_grouprec)) /
3058				    sizeof(in_addr_t);
3059				CTR1(KTR_IGMPV3,
3060				    "%s: use previous packet", __func__);
3061			} else {
3062				m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
3063				if (m)
3064					m->m_data += IGMP_LEADINGSPACE;
3065				if (m == NULL) {
3066					m = m_gethdr(M_NOWAIT, MT_DATA);
3067					if (m)
3068						M_ALIGN(m, IGMP_LEADINGSPACE);
3069				}
3070				if (m == NULL) {
3071					CTR1(KTR_IGMPV3,
3072					    "%s: m_get*() failed", __func__);
3073					return (-ENOMEM);
3074				}
3075				m->m_pkthdr.PH_vt.vt_nrecs = 0;
3076				igmp_save_context(m, ifp);
3077				m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
3078				    sizeof(struct igmp_grouprec)) /
3079				    sizeof(in_addr_t);
3080				npbytes = 0;
3081				CTR1(KTR_IGMPV3,
3082				    "%s: allocated new packet", __func__);
3083			}
3084			/*
3085			 * Append the IGMP group record header to the
3086			 * current packet's data area.
3087			 * Recalculate pointer to free space for next
3088			 * group record, in case m_append() allocated
3089			 * a new mbuf or cluster.
3090			 */
3091			memset(&ig, 0, sizeof(ig));
3092			ig.ig_group = inm->inm_addr;
3093			if (!m_append(m, sizeof(ig), (void *)&ig)) {
3094				if (m != m0)
3095					m_freem(m);
3096				CTR1(KTR_IGMPV3,
3097				    "%s: m_append() failed", __func__);
3098				return (-ENOMEM);
3099			}
3100			npbytes += sizeof(struct igmp_grouprec);
3101			if (m != m0) {
3102				/* new packet; offset in c hain */
3103				md = m_getptr(m, npbytes -
3104				    sizeof(struct igmp_grouprec), &off);
3105				pig = (struct igmp_grouprec *)(mtod(md,
3106				    uint8_t *) + off);
3107			} else {
3108				/* current packet; offset from last append */
3109				md = m_last(m);
3110				pig = (struct igmp_grouprec *)(mtod(md,
3111				    uint8_t *) + md->m_len -
3112				    sizeof(struct igmp_grouprec));
3113			}
3114			/*
3115			 * Begin walking the tree for this record type
3116			 * pass, or continue from where we left off
3117			 * previously if we had to allocate a new packet.
3118			 * Only report deltas in-mode at t1.
3119			 * We need not report included sources as allowed
3120			 * if we are in inclusive mode on the group,
3121			 * however the converse is not true.
3122			 */
3123			rsrcs = 0;
3124			if (nims == NULL)
3125				nims = RB_MIN(ip_msource_tree, &inm->inm_srcs);
3126			RB_FOREACH_FROM(ims, ip_msource_tree, nims) {
3127				CTR2(KTR_IGMPV3, "%s: visit node 0x%08x",
3128				    __func__, ims->ims_haddr);
3129				now = ims_get_mode(inm, ims, 1);
3130				then = ims_get_mode(inm, ims, 0);
3131				CTR3(KTR_IGMPV3, "%s: mode: t0 %d, t1 %d",
3132				    __func__, then, now);
3133				if (now == then) {
3134					CTR1(KTR_IGMPV3,
3135					    "%s: skip unchanged", __func__);
3136					continue;
3137				}
3138				if (mode == MCAST_EXCLUDE &&
3139				    now == MCAST_INCLUDE) {
3140					CTR1(KTR_IGMPV3,
3141					    "%s: skip IN src on EX group",
3142					    __func__);
3143					continue;
3144				}
3145				nrt = (rectype_t)now;
3146				if (nrt == REC_NONE)
3147					nrt = (rectype_t)(~mode & REC_FULL);
3148				if (schanged++ == 0) {
3149					crt = nrt;
3150				} else if (crt != nrt)
3151					continue;
3152				naddr = htonl(ims->ims_haddr);
3153				if (!m_append(m, sizeof(in_addr_t),
3154				    (void *)&naddr)) {
3155					if (m != m0)
3156						m_freem(m);
3157					CTR1(KTR_IGMPV3,
3158					    "%s: m_append() failed", __func__);
3159					return (-ENOMEM);
3160				}
3161				nallow += !!(crt == REC_ALLOW);
3162				nblock += !!(crt == REC_BLOCK);
3163				if (++rsrcs == m0srcs)
3164					break;
3165			}
3166			/*
3167			 * If we did not append any tree nodes on this
3168			 * pass, back out of allocations.
3169			 */
3170			if (rsrcs == 0) {
3171				npbytes -= sizeof(struct igmp_grouprec);
3172				if (m != m0) {
3173					CTR1(KTR_IGMPV3,
3174					    "%s: m_free(m)", __func__);
3175					m_freem(m);
3176				} else {
3177					CTR1(KTR_IGMPV3,
3178					    "%s: m_adj(m, -ig)", __func__);
3179					m_adj(m, -((int)sizeof(
3180					    struct igmp_grouprec)));
3181				}
3182				continue;
3183			}
3184			npbytes += (rsrcs * sizeof(in_addr_t));
3185			if (crt == REC_ALLOW)
3186				pig->ig_type = IGMP_ALLOW_NEW_SOURCES;
3187			else if (crt == REC_BLOCK)
3188				pig->ig_type = IGMP_BLOCK_OLD_SOURCES;
3189			pig->ig_numsrc = htons(rsrcs);
3190			/*
3191			 * Count the new group record, and enqueue this
3192			 * packet if it wasn't already queued.
3193			 */
3194			m->m_pkthdr.PH_vt.vt_nrecs++;
3195			if (m != m0)
3196				mbufq_enqueue(mq, m);
3197			nbytes += npbytes;
3198		} while (nims != NULL);
3199		drt |= crt;
3200		crt = (~crt & REC_FULL);
3201	}
3202
3203	CTR3(KTR_IGMPV3, "%s: queued %d ALLOW_NEW, %d BLOCK_OLD", __func__,
3204	    nallow, nblock);
3205
3206	return (nbytes);
3207}
3208
3209static int
3210igmp_v3_merge_state_changes(struct in_multi *inm, struct mbufq *scq)
3211{
3212	struct mbufq	*gq;
3213	struct mbuf	*m;		/* pending state-change */
3214	struct mbuf	*m0;		/* copy of pending state-change */
3215	struct mbuf	*mt;		/* last state-change in packet */
3216	int		 docopy, domerge;
3217	u_int		 recslen;
3218
3219	docopy = 0;
3220	domerge = 0;
3221	recslen = 0;
3222
3223	IN_MULTI_LOCK_ASSERT();
3224	IGMP_LOCK_ASSERT();
3225
3226	/*
3227	 * If there are further pending retransmissions, make a writable
3228	 * copy of each queued state-change message before merging.
3229	 */
3230	if (inm->inm_scrv > 0)
3231		docopy = 1;
3232
3233	gq = &inm->inm_scq;
3234#ifdef KTR
3235	if (mbufq_first(gq) == NULL) {
3236		CTR2(KTR_IGMPV3, "%s: WARNING: queue for inm %p is empty",
3237		    __func__, inm);
3238	}
3239#endif
3240
3241	m = mbufq_first(gq);
3242	while (m != NULL) {
3243		/*
3244		 * Only merge the report into the current packet if
3245		 * there is sufficient space to do so; an IGMPv3 report
3246		 * packet may only contain 65,535 group records.
3247		 * Always use a simple mbuf chain concatentation to do this,
3248		 * as large state changes for single groups may have
3249		 * allocated clusters.
3250		 */
3251		domerge = 0;
3252		mt = mbufq_last(scq);
3253		if (mt != NULL) {
3254			recslen = m_length(m, NULL);
3255
3256			if ((mt->m_pkthdr.PH_vt.vt_nrecs +
3257			    m->m_pkthdr.PH_vt.vt_nrecs <=
3258			    IGMP_V3_REPORT_MAXRECS) &&
3259			    (mt->m_pkthdr.len + recslen <=
3260			    (inm->inm_ifp->if_mtu - IGMP_LEADINGSPACE)))
3261				domerge = 1;
3262		}
3263
3264		if (!domerge && mbufq_full(gq)) {
3265			CTR2(KTR_IGMPV3,
3266			    "%s: outbound queue full, skipping whole packet %p",
3267			    __func__, m);
3268			mt = m->m_nextpkt;
3269			if (!docopy)
3270				m_freem(m);
3271			m = mt;
3272			continue;
3273		}
3274
3275		if (!docopy) {
3276			CTR2(KTR_IGMPV3, "%s: dequeueing %p", __func__, m);
3277			m0 = mbufq_dequeue(gq);
3278			m = m0->m_nextpkt;
3279		} else {
3280			CTR2(KTR_IGMPV3, "%s: copying %p", __func__, m);
3281			m0 = m_dup(m, M_NOWAIT);
3282			if (m0 == NULL)
3283				return (ENOMEM);
3284			m0->m_nextpkt = NULL;
3285			m = m->m_nextpkt;
3286		}
3287
3288		if (!domerge) {
3289			CTR3(KTR_IGMPV3, "%s: queueing %p to scq %p)",
3290			    __func__, m0, scq);
3291			mbufq_enqueue(scq, m0);
3292		} else {
3293			struct mbuf *mtl;	/* last mbuf of packet mt */
3294
3295			CTR3(KTR_IGMPV3, "%s: merging %p with scq tail %p)",
3296			    __func__, m0, mt);
3297
3298			mtl = m_last(mt);
3299			m0->m_flags &= ~M_PKTHDR;
3300			mt->m_pkthdr.len += recslen;
3301			mt->m_pkthdr.PH_vt.vt_nrecs +=
3302			    m0->m_pkthdr.PH_vt.vt_nrecs;
3303
3304			mtl->m_next = m0;
3305		}
3306	}
3307
3308	return (0);
3309}
3310
3311/*
3312 * Respond to a pending IGMPv3 General Query.
3313 */
3314static void
3315igmp_v3_dispatch_general_query(struct igmp_ifsoftc *igi)
3316{
3317	struct ifmultiaddr	*ifma;
3318	struct ifnet		*ifp;
3319	struct in_multi		*inm;
3320	int			 retval, loop;
3321
3322	IN_MULTI_LOCK_ASSERT();
3323	IGMP_LOCK_ASSERT();
3324
3325	KASSERT(igi->igi_version == IGMP_VERSION_3,
3326	    ("%s: called when version %d", __func__, igi->igi_version));
3327
3328	/*
3329	 * Check that there are some packets queued. If so, send them first.
3330	 * For large number of groups the reply to general query can take
3331	 * many packets, we should finish sending them before starting of
3332	 * queuing the new reply.
3333	 */
3334	if (mbufq_len(&igi->igi_gq) != 0)
3335		goto send;
3336
3337	ifp = igi->igi_ifp;
3338
3339	IF_ADDR_RLOCK(ifp);
3340	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3341		if (ifma->ifma_addr->sa_family != AF_INET ||
3342		    ifma->ifma_protospec == NULL)
3343			continue;
3344
3345		inm = (struct in_multi *)ifma->ifma_protospec;
3346		KASSERT(ifp == inm->inm_ifp,
3347		    ("%s: inconsistent ifp", __func__));
3348
3349		switch (inm->inm_state) {
3350		case IGMP_NOT_MEMBER:
3351		case IGMP_SILENT_MEMBER:
3352			break;
3353		case IGMP_REPORTING_MEMBER:
3354		case IGMP_IDLE_MEMBER:
3355		case IGMP_LAZY_MEMBER:
3356		case IGMP_SLEEPING_MEMBER:
3357		case IGMP_AWAKENING_MEMBER:
3358			inm->inm_state = IGMP_REPORTING_MEMBER;
3359			retval = igmp_v3_enqueue_group_record(&igi->igi_gq,
3360			    inm, 0, 0, 0);
3361			CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
3362			    __func__, retval);
3363			break;
3364		case IGMP_G_QUERY_PENDING_MEMBER:
3365		case IGMP_SG_QUERY_PENDING_MEMBER:
3366		case IGMP_LEAVING_MEMBER:
3367			break;
3368		}
3369	}
3370	IF_ADDR_RUNLOCK(ifp);
3371
3372send:
3373	loop = (igi->igi_flags & IGIF_LOOPBACK) ? 1 : 0;
3374	igmp_dispatch_queue(&igi->igi_gq, IGMP_MAX_RESPONSE_BURST, loop);
3375
3376	/*
3377	 * Slew transmission of bursts over 500ms intervals.
3378	 */
3379	if (mbufq_first(&igi->igi_gq) != NULL) {
3380		igi->igi_v3_timer = 1 + IGMP_RANDOM_DELAY(
3381		    IGMP_RESPONSE_BURST_INTERVAL);
3382		V_interface_timers_running = 1;
3383	}
3384}
3385
3386/*
3387 * Transmit the next pending IGMP message in the output queue.
3388 *
3389 * We get called from netisr_processqueue(). A mutex private to igmpoq
3390 * will be acquired and released around this routine.
3391 *
3392 * VIMAGE: Needs to store/restore vnet pointer on a per-mbuf-chain basis.
3393 * MRT: Nothing needs to be done, as IGMP traffic is always local to
3394 * a link and uses a link-scope multicast address.
3395 */
3396static void
3397igmp_intr(struct mbuf *m)
3398{
3399	struct ip_moptions	 imo;
3400	struct ifnet		*ifp;
3401	struct mbuf		*ipopts, *m0;
3402	int			 error;
3403	uint32_t		 ifindex;
3404
3405	CTR2(KTR_IGMPV3, "%s: transmit %p", __func__, m);
3406
3407	/*
3408	 * Set VNET image pointer from enqueued mbuf chain
3409	 * before doing anything else. Whilst we use interface
3410	 * indexes to guard against interface detach, they are
3411	 * unique to each VIMAGE and must be retrieved.
3412	 */
3413	CURVNET_SET((struct vnet *)(m->m_pkthdr.PH_loc.ptr));
3414	ifindex = igmp_restore_context(m);
3415
3416	/*
3417	 * Check if the ifnet still exists. This limits the scope of
3418	 * any race in the absence of a global ifp lock for low cost
3419	 * (an array lookup).
3420	 */
3421	ifp = ifnet_byindex(ifindex);
3422	if (ifp == NULL) {
3423		CTR3(KTR_IGMPV3, "%s: dropped %p as ifindex %u went away.",
3424		    __func__, m, ifindex);
3425		m_freem(m);
3426		IPSTAT_INC(ips_noroute);
3427		goto out;
3428	}
3429
3430	ipopts = V_igmp_sendra ? m_raopt : NULL;
3431
3432	imo.imo_multicast_ttl  = 1;
3433	imo.imo_multicast_vif  = -1;
3434	imo.imo_multicast_loop = (V_ip_mrouter != NULL);
3435
3436	/*
3437	 * If the user requested that IGMP traffic be explicitly
3438	 * redirected to the loopback interface (e.g. they are running a
3439	 * MANET interface and the routing protocol needs to see the
3440	 * updates), handle this now.
3441	 */
3442	if (m->m_flags & M_IGMP_LOOP)
3443		imo.imo_multicast_ifp = V_loif;
3444	else
3445		imo.imo_multicast_ifp = ifp;
3446
3447	if (m->m_flags & M_IGMPV2) {
3448		m0 = m;
3449	} else {
3450		m0 = igmp_v3_encap_report(ifp, m);
3451		if (m0 == NULL) {
3452			CTR2(KTR_IGMPV3, "%s: dropped %p", __func__, m);
3453			m_freem(m);
3454			IPSTAT_INC(ips_odropped);
3455			goto out;
3456		}
3457	}
3458
3459	igmp_scrub_context(m0);
3460	m_clrprotoflags(m);
3461	m0->m_pkthdr.rcvif = V_loif;
3462#ifdef MAC
3463	mac_netinet_igmp_send(ifp, m0);
3464#endif
3465	error = ip_output(m0, ipopts, NULL, 0, &imo, NULL);
3466	if (error) {
3467		CTR3(KTR_IGMPV3, "%s: ip_output(%p) = %d", __func__, m0, error);
3468		goto out;
3469	}
3470
3471	IGMPSTAT_INC(igps_snd_reports);
3472
3473out:
3474	/*
3475	 * We must restore the existing vnet pointer before
3476	 * continuing as we are run from netisr context.
3477	 */
3478	CURVNET_RESTORE();
3479}
3480
3481/*
3482 * Encapsulate an IGMPv3 report.
3483 *
3484 * The internal mbuf flag M_IGMPV3_HDR is used to indicate that the mbuf
3485 * chain has already had its IP/IGMPv3 header prepended. In this case
3486 * the function will not attempt to prepend; the lengths and checksums
3487 * will however be re-computed.
3488 *
3489 * Returns a pointer to the new mbuf chain head, or NULL if the
3490 * allocation failed.
3491 */
3492static struct mbuf *
3493igmp_v3_encap_report(struct ifnet *ifp, struct mbuf *m)
3494{
3495	struct rm_priotracker	in_ifa_tracker;
3496	struct igmp_report	*igmp;
3497	struct ip		*ip;
3498	int			 hdrlen, igmpreclen;
3499
3500	KASSERT((m->m_flags & M_PKTHDR),
3501	    ("%s: mbuf chain %p is !M_PKTHDR", __func__, m));
3502
3503	igmpreclen = m_length(m, NULL);
3504	hdrlen = sizeof(struct ip) + sizeof(struct igmp_report);
3505
3506	if (m->m_flags & M_IGMPV3_HDR) {
3507		igmpreclen -= hdrlen;
3508	} else {
3509		M_PREPEND(m, hdrlen, M_NOWAIT);
3510		if (m == NULL)
3511			return (NULL);
3512		m->m_flags |= M_IGMPV3_HDR;
3513	}
3514
3515	CTR2(KTR_IGMPV3, "%s: igmpreclen is %d", __func__, igmpreclen);
3516
3517	m->m_data += sizeof(struct ip);
3518	m->m_len -= sizeof(struct ip);
3519
3520	igmp = mtod(m, struct igmp_report *);
3521	igmp->ir_type = IGMP_v3_HOST_MEMBERSHIP_REPORT;
3522	igmp->ir_rsv1 = 0;
3523	igmp->ir_rsv2 = 0;
3524	igmp->ir_numgrps = htons(m->m_pkthdr.PH_vt.vt_nrecs);
3525	igmp->ir_cksum = 0;
3526	igmp->ir_cksum = in_cksum(m, sizeof(struct igmp_report) + igmpreclen);
3527	m->m_pkthdr.PH_vt.vt_nrecs = 0;
3528
3529	m->m_data -= sizeof(struct ip);
3530	m->m_len += sizeof(struct ip);
3531
3532	ip = mtod(m, struct ip *);
3533	ip->ip_tos = IPTOS_PREC_INTERNETCONTROL;
3534	ip->ip_len = htons(hdrlen + igmpreclen);
3535	ip->ip_off = htons(IP_DF);
3536	ip->ip_p = IPPROTO_IGMP;
3537	ip->ip_sum = 0;
3538
3539	ip->ip_src.s_addr = INADDR_ANY;
3540
3541	if (m->m_flags & M_IGMP_LOOP) {
3542		struct in_ifaddr *ia;
3543
3544		IFP_TO_IA(ifp, ia, &in_ifa_tracker);
3545		if (ia != NULL) {
3546			ip->ip_src = ia->ia_addr.sin_addr;
3547			ifa_free(&ia->ia_ifa);
3548		}
3549	}
3550
3551	ip->ip_dst.s_addr = htonl(INADDR_ALLRPTS_GROUP);
3552
3553	return (m);
3554}
3555
3556#ifdef KTR
3557static char *
3558igmp_rec_type_to_str(const int type)
3559{
3560
3561	switch (type) {
3562		case IGMP_CHANGE_TO_EXCLUDE_MODE:
3563			return "TO_EX";
3564			break;
3565		case IGMP_CHANGE_TO_INCLUDE_MODE:
3566			return "TO_IN";
3567			break;
3568		case IGMP_MODE_IS_EXCLUDE:
3569			return "MODE_EX";
3570			break;
3571		case IGMP_MODE_IS_INCLUDE:
3572			return "MODE_IN";
3573			break;
3574		case IGMP_ALLOW_NEW_SOURCES:
3575			return "ALLOW_NEW";
3576			break;
3577		case IGMP_BLOCK_OLD_SOURCES:
3578			return "BLOCK_OLD";
3579			break;
3580		default:
3581			break;
3582	}
3583	return "unknown";
3584}
3585#endif
3586
3587#ifdef VIMAGE
3588static void
3589vnet_igmp_init(const void *unused __unused)
3590{
3591
3592	netisr_register_vnet(&igmp_nh);
3593}
3594VNET_SYSINIT(vnet_igmp_init, SI_SUB_PROTO_MC, SI_ORDER_ANY,
3595    vnet_igmp_init, NULL);
3596
3597static void
3598vnet_igmp_uninit(const void *unused __unused)
3599{
3600
3601	/* This can happen when we shutdown the entire network stack. */
3602	CTR1(KTR_IGMPV3, "%s: tearing down", __func__);
3603
3604	netisr_unregister_vnet(&igmp_nh);
3605}
3606VNET_SYSUNINIT(vnet_igmp_uninit, SI_SUB_PROTO_MC, SI_ORDER_ANY,
3607    vnet_igmp_uninit, NULL);
3608#endif
3609
3610#ifdef DDB
3611DB_SHOW_COMMAND(igi_list, db_show_igi_list)
3612{
3613	struct igmp_ifsoftc *igi, *tigi;
3614	LIST_HEAD(_igi_list, igmp_ifsoftc) *igi_head;
3615
3616	if (!have_addr) {
3617		db_printf("usage: show igi_list <addr>\n");
3618		return;
3619	}
3620	igi_head = (struct _igi_list *)addr;
3621
3622	LIST_FOREACH_SAFE(igi, igi_head, igi_link, tigi) {
3623		db_printf("igmp_ifsoftc %p:\n", igi);
3624		db_printf("    ifp %p\n", igi->igi_ifp);
3625		db_printf("    version %u\n", igi->igi_version);
3626		db_printf("    v1_timer %u\n", igi->igi_v1_timer);
3627		db_printf("    v2_timer %u\n", igi->igi_v2_timer);
3628		db_printf("    v3_timer %u\n", igi->igi_v3_timer);
3629		db_printf("    flags %#x\n", igi->igi_flags);
3630		db_printf("    rv %u\n", igi->igi_rv);
3631		db_printf("    qi %u\n", igi->igi_qi);
3632		db_printf("    qri %u\n", igi->igi_qri);
3633		db_printf("    uri %u\n", igi->igi_uri);
3634		/* SLIST_HEAD(,in_multi)   igi_relinmhead */
3635		/* struct mbufq    igi_gq; */
3636		db_printf("\n");
3637	}
3638}
3639#endif
3640
3641static int
3642igmp_modevent(module_t mod, int type, void *unused __unused)
3643{
3644
3645	switch (type) {
3646	case MOD_LOAD:
3647		CTR1(KTR_IGMPV3, "%s: initializing", __func__);
3648		IGMP_LOCK_INIT();
3649		m_raopt = igmp_ra_alloc();
3650		netisr_register(&igmp_nh);
3651		break;
3652	case MOD_UNLOAD:
3653		CTR1(KTR_IGMPV3, "%s: tearing down", __func__);
3654		netisr_unregister(&igmp_nh);
3655		m_free(m_raopt);
3656		m_raopt = NULL;
3657		IGMP_LOCK_DESTROY();
3658		break;
3659	default:
3660		return (EOPNOTSUPP);
3661	}
3662	return (0);
3663}
3664
3665static moduledata_t igmp_mod = {
3666    "igmp",
3667    igmp_modevent,
3668    0
3669};
3670DECLARE_MODULE(igmp, igmp_mod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);
3671