mld6.c revision 195837
117683Spst/*-
217683Spst * Copyright (c) 2009 Bruce Simpson.
317683Spst *
417683Spst * Redistribution and use in source and binary forms, with or without
517683Spst * modification, are permitted provided that the following conditions
617683Spst * are met:
717683Spst * 1. Redistributions of source code must retain the above copyright
817683Spst *    notice, this list of conditions and the following disclaimer.
917683Spst * 2. Redistributions in binary form must reproduce the above copyright
1017683Spst *    notice, this list of conditions and the following disclaimer in the
1117683Spst *    documentation and/or other materials provided with the distribution.
1217683Spst * 3. The name of the author may not be used to endorse or promote
1317683Spst *    products derived from this software without specific prior written
1417683Spst *    permission.
1517683Spst *
16190225Srpaulo * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1717683Spst * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1817683Spst * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1917683Spst * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2017683Spst * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2117683Spst * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2217683Spst * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2317683Spst * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2417683Spst * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2517683Spst * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2617683Spst * SUCH DAMAGE.
2717683Spst *
2817683Spst *	$KAME: mld6.c,v 1.27 2001/04/04 05:17:30 itojun Exp $
2917683Spst */
3017683Spst
3117683Spst/*-
3217683Spst * Copyright (c) 1988 Stephen Deering.
3317683Spst * Copyright (c) 1992, 1993
3417683Spst *	The Regents of the University of California.  All rights reserved.
3517683Spst *
3617683Spst * This code is derived from software contributed to Berkeley by
3717683Spst * Stephen Deering of Stanford University.
3817683Spst *
3917683Spst * Redistribution and use in source and binary forms, with or without
4017683Spst * modification, are permitted provided that the following conditions
4117683Spst * are met:
4217683Spst * 1. Redistributions of source code must retain the above copyright
4317683Spst *    notice, this list of conditions and the following disclaimer.
4417683Spst * 2. Redistributions in binary form must reproduce the above copyright
4517683Spst *    notice, this list of conditions and the following disclaimer in the
4617683Spst *    documentation and/or other materials provided with the distribution.
4717683Spst * 4. Neither the name of the University nor the names of its contributors
4817683Spst *    may be used to endorse or promote products derived from this software
4917683Spst *    without specific prior written permission.
5017683Spst *
5117683Spst * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
5217683Spst * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
5317683Spst * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
5417683Spst * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
5517683Spst * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
5617683Spst * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
5717683Spst * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
5817683Spst * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
5917683Spst * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
6017683Spst * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
6117683Spst * SUCH DAMAGE.
6217683Spst *
6317683Spst *	@(#)igmp.c	8.1 (Berkeley) 7/19/93
6417683Spst */
6517683Spst
6617683Spst#include <sys/cdefs.h>
6717683Spst__FBSDID("$FreeBSD: head/sys/netinet6/mld6.c 195837 2009-07-23 20:46:49Z rwatson $");
6817683Spst
6917683Spst#include "opt_inet.h"
7017683Spst#include "opt_inet6.h"
7117683Spst
7217683Spst#include <sys/param.h>
7317683Spst#include <sys/systm.h>
7417683Spst#include <sys/mbuf.h>
7517683Spst#include <sys/socket.h>
7617683Spst#include <sys/protosw.h>
7717683Spst#include <sys/sysctl.h>
7817683Spst#include <sys/kernel.h>
7917683Spst#include <sys/callout.h>
8017683Spst#include <sys/malloc.h>
8117683Spst#include <sys/module.h>
8217683Spst#include <sys/vimage.h>
8317683Spst
8417683Spst#include <net/if.h>
8517683Spst#include <net/route.h>
8617683Spst#include <net/vnet.h>
8717683Spst
8817683Spst#include <netinet/in.h>
8917683Spst#include <netinet/in_var.h>
9017683Spst#include <netinet6/in6_var.h>
9117683Spst#include <netinet/ip6.h>
9217683Spst#include <netinet6/ip6_var.h>
9317683Spst#include <netinet6/scope6_var.h>
9417683Spst#include <netinet/icmp6.h>
9517683Spst#include <netinet6/mld6.h>
9617683Spst#include <netinet6/mld6_var.h>
9717683Spst
9817683Spst#include <security/mac/mac_framework.h>
9917683Spst
10017683Spst#ifndef KTR_MLD
10117683Spst#define KTR_MLD KTR_INET6
10217683Spst#endif
10317683Spst
10417683Spststatic struct mld_ifinfo *
10517683Spst		mli_alloc_locked(struct ifnet *);
10617683Spststatic void	mli_delete_locked(const struct ifnet *);
10717683Spststatic void	mld_dispatch_packet(struct mbuf *);
10817683Spststatic void	mld_dispatch_queue(struct ifqueue *, int);
10917683Spststatic void	mld_final_leave(struct in6_multi *, struct mld_ifinfo *);
110static void	mld_fasttimo_vnet(void);
111static int	mld_handle_state_change(struct in6_multi *,
112		    struct mld_ifinfo *);
113static int	mld_initial_join(struct in6_multi *, struct mld_ifinfo *,
114		    const int);
115#ifdef KTR
116static char *	mld_rec_type_to_str(const int);
117#endif
118static void	mld_set_version(struct mld_ifinfo *, const int);
119static void	mld_slowtimo_vnet(void);
120static int	mld_v1_input_query(struct ifnet *, const struct ip6_hdr *,
121		    /*const*/ struct mld_hdr *);
122static int	mld_v1_input_report(struct ifnet *, const struct ip6_hdr *,
123		    /*const*/ struct mld_hdr *);
124static void	mld_v1_process_group_timer(struct in6_multi *, const int);
125static void	mld_v1_process_querier_timers(struct mld_ifinfo *);
126static int	mld_v1_transmit_report(struct in6_multi *, const int);
127static void	mld_v1_update_group(struct in6_multi *, const int);
128static void	mld_v2_cancel_link_timers(struct mld_ifinfo *);
129static void	mld_v2_dispatch_general_query(struct mld_ifinfo *);
130static struct mbuf *
131		mld_v2_encap_report(struct ifnet *, struct mbuf *);
132static int	mld_v2_enqueue_filter_change(struct ifqueue *,
133		    struct in6_multi *);
134static int	mld_v2_enqueue_group_record(struct ifqueue *,
135		    struct in6_multi *, const int, const int, const int);
136static int	mld_v2_input_query(struct ifnet *, const struct ip6_hdr *,
137		    struct mbuf *, const int, const int);
138static int	mld_v2_merge_state_changes(struct in6_multi *,
139		    struct ifqueue *);
140static void	mld_v2_process_group_timers(struct mld_ifinfo *,
141		    struct ifqueue *, struct ifqueue *,
142		    struct in6_multi *, const int);
143static int	mld_v2_process_group_query(struct in6_multi *,
144		    struct mld_ifinfo *mli, int, struct mbuf *, const int);
145static int	sysctl_mld_gsr(SYSCTL_HANDLER_ARGS);
146static int	sysctl_mld_ifinfo(SYSCTL_HANDLER_ARGS);
147
148/*
149 * Normative references: RFC 2710, RFC 3590, RFC 3810.
150 *
151 * Locking:
152 *  * The MLD subsystem lock ends up being system-wide for the moment,
153 *    but could be per-VIMAGE later on.
154 *  * The permitted lock order is: IN6_MULTI_LOCK, MLD_LOCK, IF_ADDR_LOCK.
155 *    Any may be taken independently; if any are held at the same
156 *    time, the above lock order must be followed.
157 *  * IN6_MULTI_LOCK covers in_multi.
158 *  * MLD_LOCK covers per-link state and any global variables in this file.
159 *  * IF_ADDR_LOCK covers if_multiaddrs, which is used for a variety of
160 *    per-link state iterators.
161 *
162 *  XXX LOR PREVENTION
163 *  A special case for IPv6 is the in6_setscope() routine. ip6_output()
164 *  will not accept an ifp; it wants an embedded scope ID, unlike
165 *  ip_output(), which happily takes the ifp given to it. The embedded
166 *  scope ID is only used by MLD to select the outgoing interface.
167 *
168 *  During interface attach and detach, MLD will take MLD_LOCK *after*
169 *  the IF_AFDATA_LOCK.
170 *  As in6_setscope() takes IF_AFDATA_LOCK then SCOPE_LOCK, we can't call
171 *  it with MLD_LOCK held without triggering an LOR. A netisr with indirect
172 *  dispatch could work around this, but we'd rather not do that, as it
173 *  can introduce other races.
174 *
175 *  As such, we exploit the fact that the scope ID is just the interface
176 *  index, and embed it in the IPv6 destination address accordingly.
177 *  This is potentially NOT VALID for MLDv1 reports, as they
178 *  are always sent to the multicast group itself; as MLDv2
179 *  reports are always sent to ff02::16, this is not an issue
180 *  when MLDv2 is in use.
181 *
182 *  This does not however eliminate the LOR when ip6_output() itself
183 *  calls in6_setscope() internally whilst MLD_LOCK is held. This will
184 *  trigger a LOR warning in WITNESS when the ifnet is detached.
185 *
186 *  The right answer is probably to make IF_AFDATA_LOCK an rwlock, given
187 *  how it's used across the network stack. Here we're simply exploiting
188 *  the fact that MLD runs at a similar layer in the stack to scope6.c.
189 *
190 * VIMAGE:
191 *  * Each in6_multi corresponds to an ifp, and each ifp corresponds
192 *    to a vnet in ifp->if_vnet.
193 */
194static struct mtx		 mld_mtx;
195MALLOC_DEFINE(M_MLD, "mld", "mld state");
196
197#define	MLD_EMBEDSCOPE(pin6, zoneid) \
198	(pin6)->s6_addr16[1] = htons((zoneid) & 0xFFFF)
199
200/*
201 * VIMAGE-wide globals.
202 */
203static VNET_DEFINE(struct timeval, mld_gsrdelay) = {10, 0};
204static VNET_DEFINE(LIST_HEAD(, mld_ifinfo), mli_head);
205static VNET_DEFINE(int, interface_timers_running6);
206static VNET_DEFINE(int, state_change_timers_running6);
207static VNET_DEFINE(int, current_state_timers_running6);
208
209#define	V_mld_gsrdelay			VNET(mld_gsrdelay)
210#define	V_mli_head			VNET(mli_head)
211#define	V_interface_timers_running6	VNET(interface_timers_running6)
212#define	V_state_change_timers_running6	VNET(state_change_timers_running6)
213#define	V_current_state_timers_running6	VNET(current_state_timers_running6)
214
215SYSCTL_DECL(_net_inet6);	/* Note: Not in any common header. */
216
217SYSCTL_NODE(_net_inet6, OID_AUTO, mld, CTLFLAG_RW, 0,
218    "IPv6 Multicast Listener Discovery");
219
220/*
221 * Virtualized sysctls.
222 */
223SYSCTL_VNET_PROC(_net_inet6_mld, OID_AUTO, gsrdelay,
224    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
225    &VNET_NAME(mld_gsrdelay.tv_sec), 0, sysctl_mld_gsr, "I",
226    "Rate limit for MLDv2 Group-and-Source queries in seconds");
227
228/*
229 * Non-virtualized sysctls.
230 */
231SYSCTL_NODE(_net_inet6_mld, OID_AUTO, ifinfo, CTLFLAG_RD | CTLFLAG_MPSAFE,
232    sysctl_mld_ifinfo, "Per-interface MLDv2 state");
233
234static int	mld_v1enable = 1;
235SYSCTL_INT(_net_inet6_mld, OID_AUTO, v1enable, CTLFLAG_RW,
236    &mld_v1enable, 0, "Enable fallback to MLDv1");
237TUNABLE_INT("net.inet6.mld.v1enable", &mld_v1enable);
238
239/*
240 * Packed Router Alert option structure declaration.
241 */
242struct mld_raopt {
243	struct ip6_hbh		hbh;
244	struct ip6_opt		pad;
245	struct ip6_opt_router	ra;
246} __packed;
247
248/*
249 * Router Alert hop-by-hop option header.
250 */
251static struct mld_raopt mld_ra = {
252	.hbh = { 0, 0 },
253	.pad = { .ip6o_type = IP6OPT_PADN, 0 },
254	.ra = {
255	    .ip6or_type = IP6OPT_ROUTER_ALERT,
256	    .ip6or_len = IP6OPT_RTALERT_LEN - 2,
257	    .ip6or_value[0] = ((IP6OPT_RTALERT_MLD >> 8) & 0xFF),
258	    .ip6or_value[1] = (IP6OPT_RTALERT_MLD & 0xFF)
259	}
260};
261static struct ip6_pktopts mld_po;
262
263static __inline void
264mld_save_context(struct mbuf *m, struct ifnet *ifp)
265{
266
267#ifdef VIMAGE
268	m->m_pkthdr.header = ifp->if_vnet;
269#endif /* VIMAGE */
270	m->m_pkthdr.flowid = ifp->if_index;
271}
272
273static __inline void
274mld_scrub_context(struct mbuf *m)
275{
276
277	m->m_pkthdr.header = NULL;
278	m->m_pkthdr.flowid = 0;
279}
280
281/*
282 * Restore context from a queued output chain.
283 * Return saved ifindex.
284 *
285 * VIMAGE: The assertion is there to make sure that we
286 * actually called CURVNET_SET() with what's in the mbuf chain.
287 */
288static __inline uint32_t
289mld_restore_context(struct mbuf *m)
290{
291
292#if defined(VIMAGE) && defined(INVARIANTS)
293	KASSERT(curvnet == m->m_pkthdr.header,
294	    ("%s: called when curvnet was not restored", __func__));
295#endif
296	return (m->m_pkthdr.flowid);
297}
298
299/*
300 * Retrieve or set threshold between group-source queries in seconds.
301 *
302 * VIMAGE: Assume curvnet set by caller.
303 * SMPng: NOTE: Serialized by MLD lock.
304 */
305static int
306sysctl_mld_gsr(SYSCTL_HANDLER_ARGS)
307{
308	int error;
309	int i;
310
311	error = sysctl_wire_old_buffer(req, sizeof(int));
312	if (error)
313		return (error);
314
315	MLD_LOCK();
316
317	i = V_mld_gsrdelay.tv_sec;
318
319	error = sysctl_handle_int(oidp, &i, 0, req);
320	if (error || !req->newptr)
321		goto out_locked;
322
323	if (i < -1 || i >= 60) {
324		error = EINVAL;
325		goto out_locked;
326	}
327
328	CTR2(KTR_MLD, "change mld_gsrdelay from %d to %d",
329	     V_mld_gsrdelay.tv_sec, i);
330	V_mld_gsrdelay.tv_sec = i;
331
332out_locked:
333	MLD_UNLOCK();
334	return (error);
335}
336
337/*
338 * Expose struct mld_ifinfo to userland, keyed by ifindex.
339 * For use by ifmcstat(8).
340 *
341 * SMPng: NOTE: Does an unlocked ifindex space read.
342 * VIMAGE: Assume curvnet set by caller. The node handler itself
343 * is not directly virtualized.
344 */
345static int
346sysctl_mld_ifinfo(SYSCTL_HANDLER_ARGS)
347{
348	int			*name;
349	int			 error;
350	u_int			 namelen;
351	struct ifnet		*ifp;
352	struct mld_ifinfo	*mli;
353
354	name = (int *)arg1;
355	namelen = arg2;
356
357	if (req->newptr != NULL)
358		return (EPERM);
359
360	if (namelen != 1)
361		return (EINVAL);
362
363	error = sysctl_wire_old_buffer(req, sizeof(struct mld_ifinfo));
364	if (error)
365		return (error);
366
367	IN6_MULTI_LOCK();
368	MLD_LOCK();
369
370	if (name[0] <= 0 || name[0] > V_if_index) {
371		error = ENOENT;
372		goto out_locked;
373	}
374
375	error = ENOENT;
376
377	ifp = ifnet_byindex(name[0]);
378	if (ifp == NULL)
379		goto out_locked;
380
381	LIST_FOREACH(mli, &V_mli_head, mli_link) {
382		if (ifp == mli->mli_ifp) {
383			error = SYSCTL_OUT(req, mli,
384			    sizeof(struct mld_ifinfo));
385			break;
386		}
387	}
388
389out_locked:
390	MLD_UNLOCK();
391	IN6_MULTI_UNLOCK();
392	return (error);
393}
394
395/*
396 * Dispatch an entire queue of pending packet chains.
397 * VIMAGE: Assumes the vnet pointer has been set.
398 */
399static void
400mld_dispatch_queue(struct ifqueue *ifq, int limit)
401{
402	struct mbuf *m;
403
404	for (;;) {
405		_IF_DEQUEUE(ifq, m);
406		if (m == NULL)
407			break;
408		CTR3(KTR_MLD, "%s: dispatch %p from %p", __func__, ifq, m);
409		mld_dispatch_packet(m);
410		if (--limit == 0)
411			break;
412	}
413}
414
415/*
416 * Filter outgoing MLD report state by group.
417 *
418 * Reports are ALWAYS suppressed for ALL-HOSTS (ff02::1)
419 * and node-local addresses. However, kernel and socket consumers
420 * always embed the KAME scope ID in the address provided, so strip it
421 * when performing comparison.
422 * Note: This is not the same as the *multicast* scope.
423 *
424 * Return zero if the given group is one for which MLD reports
425 * should be suppressed, or non-zero if reports should be issued.
426 */
427static __inline int
428mld_is_addr_reported(const struct in6_addr *addr)
429{
430
431	KASSERT(IN6_IS_ADDR_MULTICAST(addr), ("%s: not multicast", __func__));
432
433	if (IPV6_ADDR_MC_SCOPE(addr) == IPV6_ADDR_SCOPE_NODELOCAL)
434		return (0);
435
436	if (IPV6_ADDR_MC_SCOPE(addr) == IPV6_ADDR_SCOPE_LINKLOCAL) {
437		struct in6_addr tmp = *addr;
438		in6_clearscope(&tmp);
439		if (IN6_ARE_ADDR_EQUAL(&tmp, &in6addr_linklocal_allnodes))
440			return (0);
441	}
442
443	return (1);
444}
445
446/*
447 * Attach MLD when PF_INET6 is attached to an interface.
448 *
449 * SMPng: Normally called with IF_AFDATA_LOCK held.
450 */
451struct mld_ifinfo *
452mld_domifattach(struct ifnet *ifp)
453{
454	struct mld_ifinfo *mli;
455
456	CTR3(KTR_MLD, "%s: called for ifp %p(%s)",
457	    __func__, ifp, ifp->if_xname);
458
459	MLD_LOCK();
460
461	mli = mli_alloc_locked(ifp);
462	if (!(ifp->if_flags & IFF_MULTICAST))
463		mli->mli_flags |= MLIF_SILENT;
464
465	MLD_UNLOCK();
466
467	return (mli);
468}
469
470/*
471 * VIMAGE: assume curvnet set by caller.
472 */
473static struct mld_ifinfo *
474mli_alloc_locked(/*const*/ struct ifnet *ifp)
475{
476	struct mld_ifinfo *mli;
477
478	MLD_LOCK_ASSERT();
479
480	mli = malloc(sizeof(struct mld_ifinfo), M_MLD, M_NOWAIT|M_ZERO);
481	if (mli == NULL)
482		goto out;
483
484	mli->mli_ifp = ifp;
485	mli->mli_version = MLD_VERSION_2;
486	mli->mli_flags = 0;
487	mli->mli_rv = MLD_RV_INIT;
488	mli->mli_qi = MLD_QI_INIT;
489	mli->mli_qri = MLD_QRI_INIT;
490	mli->mli_uri = MLD_URI_INIT;
491
492	SLIST_INIT(&mli->mli_relinmhead);
493
494	/*
495	 * Responses to general queries are subject to bounds.
496	 */
497	IFQ_SET_MAXLEN(&mli->mli_gq, MLD_MAX_RESPONSE_PACKETS);
498
499	LIST_INSERT_HEAD(&V_mli_head, mli, mli_link);
500
501	CTR2(KTR_MLD, "allocate mld_ifinfo for ifp %p(%s)",
502	     ifp, ifp->if_xname);
503
504out:
505	return (mli);
506}
507
508/*
509 * Hook for ifdetach.
510 *
511 * NOTE: Some finalization tasks need to run before the protocol domain
512 * is detached, but also before the link layer does its cleanup.
513 * Run before link-layer cleanup; cleanup groups, but do not free MLD state.
514 *
515 * SMPng: Caller must hold IN6_MULTI_LOCK().
516 * Must take IF_ADDR_LOCK() to cover if_multiaddrs iterator.
517 * XXX This routine is also bitten by unlocked ifma_protospec access.
518 */
519void
520mld_ifdetach(struct ifnet *ifp)
521{
522	struct mld_ifinfo	*mli;
523	struct ifmultiaddr	*ifma;
524	struct in6_multi	*inm, *tinm;
525
526	CTR3(KTR_MLD, "%s: called for ifp %p(%s)", __func__, ifp,
527	    ifp->if_xname);
528
529	IN6_MULTI_LOCK_ASSERT();
530	MLD_LOCK();
531
532	mli = MLD_IFINFO(ifp);
533	if (mli->mli_version == MLD_VERSION_2) {
534		IF_ADDR_LOCK(ifp);
535		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
536			if (ifma->ifma_addr->sa_family != AF_INET6 ||
537			    ifma->ifma_protospec == NULL)
538				continue;
539			inm = (struct in6_multi *)ifma->ifma_protospec;
540			if (inm->in6m_state == MLD_LEAVING_MEMBER) {
541				SLIST_INSERT_HEAD(&mli->mli_relinmhead,
542				    inm, in6m_nrele);
543			}
544			in6m_clear_recorded(inm);
545		}
546		IF_ADDR_UNLOCK(ifp);
547		SLIST_FOREACH_SAFE(inm, &mli->mli_relinmhead, in6m_nrele,
548		    tinm) {
549			SLIST_REMOVE_HEAD(&mli->mli_relinmhead, in6m_nrele);
550			in6m_release_locked(inm);
551		}
552	}
553
554	MLD_UNLOCK();
555}
556
557/*
558 * Hook for domifdetach.
559 * Runs after link-layer cleanup; free MLD state.
560 *
561 * SMPng: Normally called with IF_AFDATA_LOCK held.
562 */
563void
564mld_domifdetach(struct ifnet *ifp)
565{
566
567	CTR3(KTR_MLD, "%s: called for ifp %p(%s)",
568	    __func__, ifp, ifp->if_xname);
569
570	MLD_LOCK();
571	mli_delete_locked(ifp);
572	MLD_UNLOCK();
573}
574
575static void
576mli_delete_locked(const struct ifnet *ifp)
577{
578	struct mld_ifinfo *mli, *tmli;
579
580	CTR3(KTR_MLD, "%s: freeing mld_ifinfo for ifp %p(%s)",
581	    __func__, ifp, ifp->if_xname);
582
583	MLD_LOCK_ASSERT();
584
585	LIST_FOREACH_SAFE(mli, &V_mli_head, mli_link, tmli) {
586		if (mli->mli_ifp == ifp) {
587			/*
588			 * Free deferred General Query responses.
589			 */
590			_IF_DRAIN(&mli->mli_gq);
591
592			LIST_REMOVE(mli, mli_link);
593
594			KASSERT(SLIST_EMPTY(&mli->mli_relinmhead),
595			    ("%s: there are dangling in_multi references",
596			    __func__));
597
598			free(mli, M_MLD);
599			return;
600		}
601	}
602#ifdef INVARIANTS
603	panic("%s: mld_ifinfo not found for ifp %p\n", __func__,  ifp);
604#endif
605}
606
607/*
608 * Process a received MLDv1 general or address-specific query.
609 * Assumes that the query header has been pulled up to sizeof(mld_hdr).
610 *
611 * NOTE: Can't be fully const correct as we temporarily embed scope ID in
612 * mld_addr. This is OK as we own the mbuf chain.
613 */
614static int
615mld_v1_input_query(struct ifnet *ifp, const struct ip6_hdr *ip6,
616    /*const*/ struct mld_hdr *mld)
617{
618	struct ifmultiaddr	*ifma;
619	struct mld_ifinfo	*mli;
620	struct in6_multi	*inm;
621	int			 is_general_query;
622	uint16_t		 timer;
623#ifdef KTR
624	char			 ip6tbuf[INET6_ADDRSTRLEN];
625#endif
626
627	is_general_query = 0;
628
629	if (!mld_v1enable) {
630		CTR3(KTR_MLD, "ignore v1 query %s on ifp %p(%s)",
631		    ip6_sprintf(ip6tbuf, &mld->mld_addr),
632		    ifp, ifp->if_xname);
633		return (0);
634	}
635
636	/*
637	 * RFC3810 Section 6.2: MLD queries must originate from
638	 * a router's link-local address.
639	 */
640	if (!IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
641		CTR3(KTR_MLD, "ignore v1 query src %s on ifp %p(%s)",
642		    ip6_sprintf(ip6tbuf, &ip6->ip6_src),
643		    ifp, ifp->if_xname);
644		return (0);
645	}
646
647	/*
648	 * Do address field validation upfront before we accept
649	 * the query.
650	 */
651	if (IN6_IS_ADDR_UNSPECIFIED(&mld->mld_addr)) {
652		/*
653		 * MLDv1 General Query.
654		 * If this was not sent to the all-nodes group, ignore it.
655		 */
656		struct in6_addr		 dst;
657
658		dst = ip6->ip6_dst;
659		in6_clearscope(&dst);
660		if (!IN6_ARE_ADDR_EQUAL(&dst, &in6addr_linklocal_allnodes))
661			return (EINVAL);
662		is_general_query = 1;
663	} else {
664		/*
665		 * Embed scope ID of receiving interface in MLD query for
666		 * lookup whilst we don't hold other locks.
667		 */
668		in6_setscope(&mld->mld_addr, ifp, NULL);
669	}
670
671	IN6_MULTI_LOCK();
672	MLD_LOCK();
673	IF_ADDR_LOCK(ifp);
674
675	/*
676	 * Switch to MLDv1 host compatibility mode.
677	 */
678	mli = MLD_IFINFO(ifp);
679	KASSERT(mli != NULL, ("%s: no mld_ifinfo for ifp %p", __func__, ifp));
680	mld_set_version(mli, MLD_VERSION_1);
681
682	timer = (ntohs(mld->mld_maxdelay) * PR_FASTHZ) / MLD_TIMER_SCALE;
683	if (timer == 0)
684		timer = 1;
685
686	if (is_general_query) {
687		/*
688		 * For each reporting group joined on this
689		 * interface, kick the report timer.
690		 */
691		CTR2(KTR_MLD, "process v1 general query on ifp %p(%s)",
692		    ifp, ifp->if_xname);
693		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
694			if (ifma->ifma_addr->sa_family != AF_INET6 ||
695			    ifma->ifma_protospec == NULL)
696				continue;
697			inm = (struct in6_multi *)ifma->ifma_protospec;
698			mld_v1_update_group(inm, timer);
699		}
700	} else {
701		/*
702		 * MLDv1 Group-Specific Query.
703		 * If this is a group-specific MLDv1 query, we need only
704		 * look up the single group to process it.
705		 */
706		inm = in6m_lookup_locked(ifp, &mld->mld_addr);
707		if (inm != NULL) {
708			CTR3(KTR_MLD, "process v1 query %s on ifp %p(%s)",
709			    ip6_sprintf(ip6tbuf, &mld->mld_addr),
710			    ifp, ifp->if_xname);
711			mld_v1_update_group(inm, timer);
712		}
713		/* XXX Clear embedded scope ID as userland won't expect it. */
714		in6_clearscope(&mld->mld_addr);
715	}
716
717	IF_ADDR_UNLOCK(ifp);
718	MLD_UNLOCK();
719	IN6_MULTI_UNLOCK();
720
721	return (0);
722}
723
724/*
725 * Update the report timer on a group in response to an MLDv1 query.
726 *
727 * If we are becoming the reporting member for this group, start the timer.
728 * If we already are the reporting member for this group, and timer is
729 * below the threshold, reset it.
730 *
731 * We may be updating the group for the first time since we switched
732 * to MLDv2. If we are, then we must clear any recorded source lists,
733 * and transition to REPORTING state; the group timer is overloaded
734 * for group and group-source query responses.
735 *
736 * Unlike MLDv2, the delay per group should be jittered
737 * to avoid bursts of MLDv1 reports.
738 */
739static void
740mld_v1_update_group(struct in6_multi *inm, const int timer)
741{
742#ifdef KTR
743	char			 ip6tbuf[INET6_ADDRSTRLEN];
744#endif
745
746	CTR4(KTR_MLD, "%s: %s/%s timer=%d", __func__,
747	    ip6_sprintf(ip6tbuf, &inm->in6m_addr),
748	    inm->in6m_ifp->if_xname, timer);
749
750	IN6_MULTI_LOCK_ASSERT();
751
752	switch (inm->in6m_state) {
753	case MLD_NOT_MEMBER:
754	case MLD_SILENT_MEMBER:
755		break;
756	case MLD_REPORTING_MEMBER:
757		if (inm->in6m_timer != 0 &&
758		    inm->in6m_timer <= timer) {
759			CTR1(KTR_MLD, "%s: REPORTING and timer running, "
760			    "skipping.", __func__);
761			break;
762		}
763		/* FALLTHROUGH */
764	case MLD_SG_QUERY_PENDING_MEMBER:
765	case MLD_G_QUERY_PENDING_MEMBER:
766	case MLD_IDLE_MEMBER:
767	case MLD_LAZY_MEMBER:
768	case MLD_AWAKENING_MEMBER:
769		CTR1(KTR_MLD, "%s: ->REPORTING", __func__);
770		inm->in6m_state = MLD_REPORTING_MEMBER;
771		inm->in6m_timer = MLD_RANDOM_DELAY(timer);
772		V_current_state_timers_running6 = 1;
773		break;
774	case MLD_SLEEPING_MEMBER:
775		CTR1(KTR_MLD, "%s: ->AWAKENING", __func__);
776		inm->in6m_state = MLD_AWAKENING_MEMBER;
777		break;
778	case MLD_LEAVING_MEMBER:
779		break;
780	}
781}
782
783/*
784 * Process a received MLDv2 general, group-specific or
785 * group-and-source-specific query.
786 *
787 * Assumes that the query header has been pulled up to sizeof(mldv2_query).
788 *
789 * Return 0 if successful, otherwise an appropriate error code is returned.
790 */
791static int
792mld_v2_input_query(struct ifnet *ifp, const struct ip6_hdr *ip6,
793    struct mbuf *m, const int off, const int icmp6len)
794{
795	struct mld_ifinfo	*mli;
796	struct mldv2_query	*mld;
797	struct in6_multi	*inm;
798	uint32_t		 maxdelay, nsrc, qqi;
799	int			 is_general_query;
800	uint16_t		 timer;
801	uint8_t			 qrv;
802#ifdef KTR
803	char			 ip6tbuf[INET6_ADDRSTRLEN];
804#endif
805
806	is_general_query = 0;
807
808	/*
809	 * RFC3810 Section 6.2: MLD queries must originate from
810	 * a router's link-local address.
811	 */
812	if (!IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
813		CTR3(KTR_MLD, "ignore v1 query src %s on ifp %p(%s)",
814		    ip6_sprintf(ip6tbuf, &ip6->ip6_src),
815		    ifp, ifp->if_xname);
816		return (0);
817	}
818
819	CTR2(KTR_MLD, "input v2 query on ifp %p(%s)", ifp, ifp->if_xname);
820
821	mld = (struct mldv2_query *)(mtod(m, uint8_t *) + off);
822
823	maxdelay = ntohs(mld->mld_maxdelay);	/* in 1/10ths of a second */
824	if (maxdelay >= 32678) {
825		maxdelay = (MLD_MRC_MANT(maxdelay) | 0x1000) <<
826			   (MLD_MRC_EXP(maxdelay) + 3);
827	}
828	timer = (maxdelay * PR_FASTHZ) / MLD_TIMER_SCALE;
829	if (timer == 0)
830		timer = 1;
831
832	qrv = MLD_QRV(mld->mld_misc);
833	if (qrv < 2) {
834		CTR3(KTR_MLD, "%s: clamping qrv %d to %d", __func__,
835		    qrv, MLD_RV_INIT);
836		qrv = MLD_RV_INIT;
837	}
838
839	qqi = mld->mld_qqi;
840	if (qqi >= 128) {
841		qqi = MLD_QQIC_MANT(mld->mld_qqi) <<
842		     (MLD_QQIC_EXP(mld->mld_qqi) + 3);
843	}
844
845	nsrc = ntohs(mld->mld_numsrc);
846	if (nsrc > MLD_MAX_GS_SOURCES)
847		return (EMSGSIZE);
848	if (icmp6len < sizeof(struct mldv2_query) +
849	    (nsrc * sizeof(struct in6_addr)))
850		return (EMSGSIZE);
851
852	/*
853	 * Do further input validation upfront to avoid resetting timers
854	 * should we need to discard this query.
855	 */
856	if (IN6_IS_ADDR_UNSPECIFIED(&mld->mld_addr)) {
857		/*
858		 * General Queries SHOULD be directed to ff02::1.
859		 * A general query with a source list has undefined
860		 * behaviour; discard it.
861		 */
862		struct in6_addr		 dst;
863
864		dst = ip6->ip6_dst;
865		in6_clearscope(&dst);
866		if (!IN6_ARE_ADDR_EQUAL(&dst, &in6addr_linklocal_allnodes) ||
867		    nsrc > 0)
868			return (EINVAL);
869		is_general_query = 1;
870	} else {
871		/*
872		 * Embed scope ID of receiving interface in MLD query for
873		 * lookup whilst we don't hold other locks (due to KAME
874		 * locking lameness). We own this mbuf chain just now.
875		 */
876		in6_setscope(&mld->mld_addr, ifp, NULL);
877	}
878
879	IN6_MULTI_LOCK();
880	MLD_LOCK();
881	IF_ADDR_LOCK(ifp);
882
883	mli = MLD_IFINFO(ifp);
884	KASSERT(mli != NULL, ("%s: no mld_ifinfo for ifp %p", __func__, ifp));
885
886	/*
887	 * Discard the v2 query if we're in Compatibility Mode.
888	 * The RFC is pretty clear that hosts need to stay in MLDv1 mode
889	 * until the Old Version Querier Present timer expires.
890	 */
891	if (mli->mli_version != MLD_VERSION_2)
892		goto out_locked;
893
894	mld_set_version(mli, MLD_VERSION_2);
895	mli->mli_rv = qrv;
896	mli->mli_qi = qqi;
897	mli->mli_qri = maxdelay;
898
899	CTR4(KTR_MLD, "%s: qrv %d qi %d maxdelay %d", __func__, qrv, qqi,
900	    maxdelay);
901
902	if (is_general_query) {
903		/*
904		 * MLDv2 General Query.
905		 *
906		 * Schedule a current-state report on this ifp for
907		 * all groups, possibly containing source lists.
908		 *
909		 * If there is a pending General Query response
910		 * scheduled earlier than the selected delay, do
911		 * not schedule any other reports.
912		 * Otherwise, reset the interface timer.
913		 */
914		CTR2(KTR_MLD, "process v2 general query on ifp %p(%s)",
915		    ifp, ifp->if_xname);
916		if (mli->mli_v2_timer == 0 || mli->mli_v2_timer >= timer) {
917			mli->mli_v2_timer = MLD_RANDOM_DELAY(timer);
918			V_interface_timers_running6 = 1;
919		}
920	} else {
921		/*
922		 * MLDv2 Group-specific or Group-and-source-specific Query.
923		 *
924		 * Group-source-specific queries are throttled on
925		 * a per-group basis to defeat denial-of-service attempts.
926		 * Queries for groups we are not a member of on this
927		 * link are simply ignored.
928		 */
929		inm = in6m_lookup_locked(ifp, &mld->mld_addr);
930		if (inm == NULL)
931			goto out_locked;
932		if (nsrc > 0) {
933			if (!ratecheck(&inm->in6m_lastgsrtv,
934			    &V_mld_gsrdelay)) {
935				CTR1(KTR_MLD, "%s: GS query throttled.",
936				    __func__);
937				goto out_locked;
938			}
939		}
940		CTR2(KTR_MLD, "process v2 group query on ifp %p(%s)",
941		     ifp, ifp->if_xname);
942		/*
943		 * If there is a pending General Query response
944		 * scheduled sooner than the selected delay, no
945		 * further report need be scheduled.
946		 * Otherwise, prepare to respond to the
947		 * group-specific or group-and-source query.
948		 */
949		if (mli->mli_v2_timer == 0 || mli->mli_v2_timer >= timer)
950			mld_v2_process_group_query(inm, mli, timer, m, off);
951
952		/* XXX Clear embedded scope ID as userland won't expect it. */
953		in6_clearscope(&mld->mld_addr);
954	}
955
956out_locked:
957	IF_ADDR_UNLOCK(ifp);
958	MLD_UNLOCK();
959	IN6_MULTI_UNLOCK();
960
961	return (0);
962}
963
964/*
965 * Process a recieved MLDv2 group-specific or group-and-source-specific
966 * query.
967 * Return <0 if any error occured. Currently this is ignored.
968 */
969static int
970mld_v2_process_group_query(struct in6_multi *inm, struct mld_ifinfo *mli,
971    int timer, struct mbuf *m0, const int off)
972{
973	struct mldv2_query	*mld;
974	int			 retval;
975	uint16_t		 nsrc;
976
977	IN6_MULTI_LOCK_ASSERT();
978	MLD_LOCK_ASSERT();
979
980	retval = 0;
981	mld = (struct mldv2_query *)(mtod(m0, uint8_t *) + off);
982
983	switch (inm->in6m_state) {
984	case MLD_NOT_MEMBER:
985	case MLD_SILENT_MEMBER:
986	case MLD_SLEEPING_MEMBER:
987	case MLD_LAZY_MEMBER:
988	case MLD_AWAKENING_MEMBER:
989	case MLD_IDLE_MEMBER:
990	case MLD_LEAVING_MEMBER:
991		return (retval);
992		break;
993	case MLD_REPORTING_MEMBER:
994	case MLD_G_QUERY_PENDING_MEMBER:
995	case MLD_SG_QUERY_PENDING_MEMBER:
996		break;
997	}
998
999	nsrc = ntohs(mld->mld_numsrc);
1000
1001	/*
1002	 * Deal with group-specific queries upfront.
1003	 * If any group query is already pending, purge any recorded
1004	 * source-list state if it exists, and schedule a query response
1005	 * for this group-specific query.
1006	 */
1007	if (nsrc == 0) {
1008		if (inm->in6m_state == MLD_G_QUERY_PENDING_MEMBER ||
1009		    inm->in6m_state == MLD_SG_QUERY_PENDING_MEMBER) {
1010			in6m_clear_recorded(inm);
1011			timer = min(inm->in6m_timer, timer);
1012		}
1013		inm->in6m_state = MLD_G_QUERY_PENDING_MEMBER;
1014		inm->in6m_timer = MLD_RANDOM_DELAY(timer);
1015		V_current_state_timers_running6 = 1;
1016		return (retval);
1017	}
1018
1019	/*
1020	 * Deal with the case where a group-and-source-specific query has
1021	 * been received but a group-specific query is already pending.
1022	 */
1023	if (inm->in6m_state == MLD_G_QUERY_PENDING_MEMBER) {
1024		timer = min(inm->in6m_timer, timer);
1025		inm->in6m_timer = MLD_RANDOM_DELAY(timer);
1026		V_current_state_timers_running6 = 1;
1027		return (retval);
1028	}
1029
1030	/*
1031	 * Finally, deal with the case where a group-and-source-specific
1032	 * query has been received, where a response to a previous g-s-r
1033	 * query exists, or none exists.
1034	 * In this case, we need to parse the source-list which the Querier
1035	 * has provided us with and check if we have any source list filter
1036	 * entries at T1 for these sources. If we do not, there is no need
1037	 * schedule a report and the query may be dropped.
1038	 * If we do, we must record them and schedule a current-state
1039	 * report for those sources.
1040	 */
1041	if (inm->in6m_nsrc > 0) {
1042		struct mbuf		*m;
1043		uint8_t			*sp;
1044		int			 i, nrecorded;
1045		int			 soff;
1046
1047		m = m0;
1048		soff = off + sizeof(struct mldv2_query);
1049		nrecorded = 0;
1050		for (i = 0; i < nsrc; i++) {
1051			sp = mtod(m, uint8_t *) + soff;
1052			retval = in6m_record_source(inm,
1053			    (const struct in6_addr *)sp);
1054			if (retval < 0)
1055				break;
1056			nrecorded += retval;
1057			soff += sizeof(struct in6_addr);
1058			if (soff >= m->m_len) {
1059				soff = soff - m->m_len;
1060				m = m->m_next;
1061				if (m == NULL)
1062					break;
1063			}
1064		}
1065		if (nrecorded > 0) {
1066			CTR1(KTR_MLD,
1067			    "%s: schedule response to SG query", __func__);
1068			inm->in6m_state = MLD_SG_QUERY_PENDING_MEMBER;
1069			inm->in6m_timer = MLD_RANDOM_DELAY(timer);
1070			V_current_state_timers_running6 = 1;
1071		}
1072	}
1073
1074	return (retval);
1075}
1076
1077/*
1078 * Process a received MLDv1 host membership report.
1079 * Assumes mld points to mld_hdr in pulled up mbuf chain.
1080 *
1081 * NOTE: Can't be fully const correct as we temporarily embed scope ID in
1082 * mld_addr. This is OK as we own the mbuf chain.
1083 */
1084static int
1085mld_v1_input_report(struct ifnet *ifp, const struct ip6_hdr *ip6,
1086    /*const*/ struct mld_hdr *mld)
1087{
1088	struct in6_addr		 src, dst;
1089	struct in6_ifaddr	*ia;
1090	struct in6_multi	*inm;
1091#ifdef KTR
1092	char			 ip6tbuf[INET6_ADDRSTRLEN];
1093#endif
1094
1095	if (!mld_v1enable) {
1096		CTR3(KTR_MLD, "ignore v1 report %s on ifp %p(%s)",
1097		    ip6_sprintf(ip6tbuf, &mld->mld_addr),
1098		    ifp, ifp->if_xname);
1099		return (0);
1100	}
1101
1102	if (ifp->if_flags & IFF_LOOPBACK)
1103		return (0);
1104
1105	/*
1106	 * MLDv1 reports must originate from a host's link-local address,
1107	 * or the unspecified address (when booting).
1108	 */
1109	src = ip6->ip6_src;
1110	in6_clearscope(&src);
1111	if (!IN6_IS_SCOPE_LINKLOCAL(&src) && !IN6_IS_ADDR_UNSPECIFIED(&src)) {
1112		CTR3(KTR_MLD, "ignore v1 query src %s on ifp %p(%s)",
1113		    ip6_sprintf(ip6tbuf, &ip6->ip6_src),
1114		    ifp, ifp->if_xname);
1115		return (EINVAL);
1116	}
1117
1118	/*
1119	 * RFC2710 Section 4: MLDv1 reports must pertain to a multicast
1120	 * group, and must be directed to the group itself.
1121	 */
1122	dst = ip6->ip6_dst;
1123	in6_clearscope(&dst);
1124	if (!IN6_IS_ADDR_MULTICAST(&mld->mld_addr) ||
1125	    !IN6_ARE_ADDR_EQUAL(&mld->mld_addr, &dst)) {
1126		CTR3(KTR_MLD, "ignore v1 query dst %s on ifp %p(%s)",
1127		    ip6_sprintf(ip6tbuf, &ip6->ip6_dst),
1128		    ifp, ifp->if_xname);
1129		return (EINVAL);
1130	}
1131
1132	/*
1133	 * Make sure we don't hear our own membership report, as fast
1134	 * leave requires knowing that we are the only member of a
1135	 * group. Assume we used the link-local address if available,
1136	 * otherwise look for ::.
1137	 *
1138	 * XXX Note that scope ID comparison is needed for the address
1139	 * returned by in6ifa_ifpforlinklocal(), but SHOULD NOT be
1140	 * performed for the on-wire address.
1141	 */
1142	ia = in6ifa_ifpforlinklocal(ifp, IN6_IFF_NOTREADY|IN6_IFF_ANYCAST);
1143	if ((ia && IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, IA6_IN6(ia))) ||
1144	    (ia == NULL && IN6_IS_ADDR_UNSPECIFIED(&src))) {
1145		if (ia != NULL)
1146			ifa_free(&ia->ia_ifa);
1147		return (0);
1148	}
1149	if (ia != NULL)
1150		ifa_free(&ia->ia_ifa);
1151
1152	CTR3(KTR_MLD, "process v1 report %s on ifp %p(%s)",
1153	    ip6_sprintf(ip6tbuf, &mld->mld_addr), ifp, ifp->if_xname);
1154
1155	/*
1156	 * Embed scope ID of receiving interface in MLD query for lookup
1157	 * whilst we don't hold other locks (due to KAME locking lameness).
1158	 */
1159	if (!IN6_IS_ADDR_UNSPECIFIED(&mld->mld_addr))
1160		in6_setscope(&mld->mld_addr, ifp, NULL);
1161
1162	IN6_MULTI_LOCK();
1163	MLD_LOCK();
1164	IF_ADDR_LOCK(ifp);
1165
1166	/*
1167	 * MLDv1 report suppression.
1168	 * If we are a member of this group, and our membership should be
1169	 * reported, and our group timer is pending or about to be reset,
1170	 * stop our group timer by transitioning to the 'lazy' state.
1171	 */
1172	inm = in6m_lookup_locked(ifp, &mld->mld_addr);
1173	if (inm != NULL) {
1174		struct mld_ifinfo *mli;
1175
1176		mli = inm->in6m_mli;
1177		KASSERT(mli != NULL,
1178		    ("%s: no mli for ifp %p", __func__, ifp));
1179
1180		/*
1181		 * If we are in MLDv2 host mode, do not allow the
1182		 * other host's MLDv1 report to suppress our reports.
1183		 */
1184		if (mli->mli_version == MLD_VERSION_2)
1185			goto out_locked;
1186
1187		inm->in6m_timer = 0;
1188
1189		switch (inm->in6m_state) {
1190		case MLD_NOT_MEMBER:
1191		case MLD_SILENT_MEMBER:
1192		case MLD_SLEEPING_MEMBER:
1193			break;
1194		case MLD_REPORTING_MEMBER:
1195		case MLD_IDLE_MEMBER:
1196		case MLD_AWAKENING_MEMBER:
1197			CTR3(KTR_MLD,
1198			    "report suppressed for %s on ifp %p(%s)",
1199			    ip6_sprintf(ip6tbuf, &mld->mld_addr),
1200			    ifp, ifp->if_xname);
1201		case MLD_LAZY_MEMBER:
1202			inm->in6m_state = MLD_LAZY_MEMBER;
1203			break;
1204		case MLD_G_QUERY_PENDING_MEMBER:
1205		case MLD_SG_QUERY_PENDING_MEMBER:
1206		case MLD_LEAVING_MEMBER:
1207			break;
1208		}
1209	}
1210
1211out_locked:
1212	MLD_UNLOCK();
1213	IF_ADDR_UNLOCK(ifp);
1214	IN6_MULTI_UNLOCK();
1215
1216	/* XXX Clear embedded scope ID as userland won't expect it. */
1217	in6_clearscope(&mld->mld_addr);
1218
1219	return (0);
1220}
1221
1222/*
1223 * MLD input path.
1224 *
1225 * Assume query messages which fit in a single ICMPv6 message header
1226 * have been pulled up.
1227 * Assume that userland will want to see the message, even if it
1228 * otherwise fails kernel input validation; do not free it.
1229 * Pullup may however free the mbuf chain m if it fails.
1230 *
1231 * Return IPPROTO_DONE if we freed m. Otherwise, return 0.
1232 */
1233int
1234mld_input(struct mbuf *m, int off, int icmp6len)
1235{
1236	struct ifnet	*ifp;
1237	struct ip6_hdr	*ip6;
1238	struct mld_hdr	*mld;
1239	int		 mldlen;
1240
1241	CTR3(KTR_MLD, "%s: called w/mbuf (%p,%d)", __func__, m, off);
1242
1243	ifp = m->m_pkthdr.rcvif;
1244
1245	ip6 = mtod(m, struct ip6_hdr *);
1246
1247	/* Pullup to appropriate size. */
1248	mld = (struct mld_hdr *)(mtod(m, uint8_t *) + off);
1249	if (mld->mld_type == MLD_LISTENER_QUERY &&
1250	    icmp6len >= sizeof(struct mldv2_query)) {
1251		mldlen = sizeof(struct mldv2_query);
1252	} else {
1253		mldlen = sizeof(struct mld_hdr);
1254	}
1255	IP6_EXTHDR_GET(mld, struct mld_hdr *, m, off, mldlen);
1256	if (mld == NULL) {
1257		ICMP6STAT_INC(icp6s_badlen);
1258		return (IPPROTO_DONE);
1259	}
1260
1261	/*
1262	 * Userland needs to see all of this traffic for implementing
1263	 * the endpoint discovery portion of multicast routing.
1264	 */
1265	switch (mld->mld_type) {
1266	case MLD_LISTENER_QUERY:
1267		icmp6_ifstat_inc(ifp, ifs6_in_mldquery);
1268		if (icmp6len == sizeof(struct mld_hdr)) {
1269			if (mld_v1_input_query(ifp, ip6, mld) != 0)
1270				return (0);
1271		} else if (icmp6len >= sizeof(struct mldv2_query)) {
1272			if (mld_v2_input_query(ifp, ip6, m, off,
1273			    icmp6len) != 0)
1274				return (0);
1275		}
1276		break;
1277	case MLD_LISTENER_REPORT:
1278		icmp6_ifstat_inc(ifp, ifs6_in_mldreport);
1279		if (mld_v1_input_report(ifp, ip6, mld) != 0)
1280			return (0);
1281		break;
1282	case MLDV2_LISTENER_REPORT:
1283		icmp6_ifstat_inc(ifp, ifs6_in_mldreport);
1284		break;
1285	case MLD_LISTENER_DONE:
1286		icmp6_ifstat_inc(ifp, ifs6_in_mlddone);
1287		break;
1288	default:
1289		break;
1290	}
1291
1292	return (0);
1293}
1294
1295/*
1296 * Fast timeout handler (global).
1297 * VIMAGE: Timeout handlers are expected to service all vimages.
1298 */
1299void
1300mld_fasttimo(void)
1301{
1302	VNET_ITERATOR_DECL(vnet_iter);
1303
1304	VNET_LIST_RLOCK_NOSLEEP();
1305	VNET_FOREACH(vnet_iter) {
1306		CURVNET_SET(vnet_iter);
1307		mld_fasttimo_vnet();
1308		CURVNET_RESTORE();
1309	}
1310	VNET_LIST_RUNLOCK_NOSLEEP();
1311}
1312
1313/*
1314 * Fast timeout handler (per-vnet).
1315 *
1316 * VIMAGE: Assume caller has set up our curvnet.
1317 */
1318static void
1319mld_fasttimo_vnet(void)
1320{
1321	struct ifqueue		 scq;	/* State-change packets */
1322	struct ifqueue		 qrq;	/* Query response packets */
1323	struct ifnet		*ifp;
1324	struct mld_ifinfo	*mli;
1325	struct ifmultiaddr	*ifma, *tifma;
1326	struct in6_multi	*inm;
1327	int			 uri_fasthz;
1328
1329	uri_fasthz = 0;
1330
1331	/*
1332	 * Quick check to see if any work needs to be done, in order to
1333	 * minimize the overhead of fasttimo processing.
1334	 * SMPng: XXX Unlocked reads.
1335	 */
1336	if (!V_current_state_timers_running6 &&
1337	    !V_interface_timers_running6 &&
1338	    !V_state_change_timers_running6)
1339		return;
1340
1341	IN6_MULTI_LOCK();
1342	MLD_LOCK();
1343
1344	/*
1345	 * MLDv2 General Query response timer processing.
1346	 */
1347	if (V_interface_timers_running6) {
1348		CTR1(KTR_MLD, "%s: interface timers running", __func__);
1349
1350		V_interface_timers_running6 = 0;
1351		LIST_FOREACH(mli, &V_mli_head, mli_link) {
1352			if (mli->mli_v2_timer == 0) {
1353				/* Do nothing. */
1354			} else if (--mli->mli_v2_timer == 0) {
1355				mld_v2_dispatch_general_query(mli);
1356			} else {
1357				V_interface_timers_running6 = 1;
1358			}
1359		}
1360	}
1361
1362	if (!V_current_state_timers_running6 &&
1363	    !V_state_change_timers_running6)
1364		goto out_locked;
1365
1366	V_current_state_timers_running6 = 0;
1367	V_state_change_timers_running6 = 0;
1368
1369	CTR1(KTR_MLD, "%s: state change timers running", __func__);
1370
1371	/*
1372	 * MLD host report and state-change timer processing.
1373	 * Note: Processing a v2 group timer may remove a node.
1374	 */
1375	LIST_FOREACH(mli, &V_mli_head, mli_link) {
1376		ifp = mli->mli_ifp;
1377
1378		if (mli->mli_version == MLD_VERSION_2) {
1379			uri_fasthz = MLD_RANDOM_DELAY(mli->mli_uri *
1380			    PR_FASTHZ);
1381
1382			memset(&qrq, 0, sizeof(struct ifqueue));
1383			IFQ_SET_MAXLEN(&qrq, MLD_MAX_G_GS_PACKETS);
1384
1385			memset(&scq, 0, sizeof(struct ifqueue));
1386			IFQ_SET_MAXLEN(&scq, MLD_MAX_STATE_CHANGE_PACKETS);
1387		}
1388
1389		IF_ADDR_LOCK(ifp);
1390		TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link,
1391		    tifma) {
1392			if (ifma->ifma_addr->sa_family != AF_INET6 ||
1393			    ifma->ifma_protospec == NULL)
1394				continue;
1395			inm = (struct in6_multi *)ifma->ifma_protospec;
1396			switch (mli->mli_version) {
1397			case MLD_VERSION_1:
1398				/*
1399				 * XXX Drop IF_ADDR lock temporarily to
1400				 * avoid recursion caused by a potential
1401				 * call by in6ifa_ifpforlinklocal().
1402				 * rwlock candidate?
1403				 */
1404				IF_ADDR_UNLOCK(ifp);
1405				mld_v1_process_group_timer(inm,
1406				    mli->mli_version);
1407				IF_ADDR_LOCK(ifp);
1408				break;
1409			case MLD_VERSION_2:
1410				mld_v2_process_group_timers(mli, &qrq,
1411				    &scq, inm, uri_fasthz);
1412				break;
1413			}
1414		}
1415		IF_ADDR_UNLOCK(ifp);
1416
1417		if (mli->mli_version == MLD_VERSION_2) {
1418			struct in6_multi		*tinm;
1419
1420			mld_dispatch_queue(&qrq, 0);
1421			mld_dispatch_queue(&scq, 0);
1422
1423			/*
1424			 * Free the in_multi reference(s) for
1425			 * this lifecycle.
1426			 */
1427			SLIST_FOREACH_SAFE(inm, &mli->mli_relinmhead,
1428			    in6m_nrele, tinm) {
1429				SLIST_REMOVE_HEAD(&mli->mli_relinmhead,
1430				    in6m_nrele);
1431				in6m_release_locked(inm);
1432			}
1433		}
1434	}
1435
1436out_locked:
1437	MLD_UNLOCK();
1438	IN6_MULTI_UNLOCK();
1439}
1440
1441/*
1442 * Update host report group timer.
1443 * Will update the global pending timer flags.
1444 */
1445static void
1446mld_v1_process_group_timer(struct in6_multi *inm, const int version)
1447{
1448	int report_timer_expired;
1449
1450	IN6_MULTI_LOCK_ASSERT();
1451	MLD_LOCK_ASSERT();
1452
1453	if (inm->in6m_timer == 0) {
1454		report_timer_expired = 0;
1455	} else if (--inm->in6m_timer == 0) {
1456		report_timer_expired = 1;
1457	} else {
1458		V_current_state_timers_running6 = 1;
1459		return;
1460	}
1461
1462	switch (inm->in6m_state) {
1463	case MLD_NOT_MEMBER:
1464	case MLD_SILENT_MEMBER:
1465	case MLD_IDLE_MEMBER:
1466	case MLD_LAZY_MEMBER:
1467	case MLD_SLEEPING_MEMBER:
1468	case MLD_AWAKENING_MEMBER:
1469		break;
1470	case MLD_REPORTING_MEMBER:
1471		if (report_timer_expired) {
1472			inm->in6m_state = MLD_IDLE_MEMBER;
1473			(void)mld_v1_transmit_report(inm,
1474			     MLD_LISTENER_REPORT);
1475		}
1476		break;
1477	case MLD_G_QUERY_PENDING_MEMBER:
1478	case MLD_SG_QUERY_PENDING_MEMBER:
1479	case MLD_LEAVING_MEMBER:
1480		break;
1481	}
1482}
1483
1484/*
1485 * Update a group's timers for MLDv2.
1486 * Will update the global pending timer flags.
1487 * Note: Unlocked read from mli.
1488 */
1489static void
1490mld_v2_process_group_timers(struct mld_ifinfo *mli,
1491    struct ifqueue *qrq, struct ifqueue *scq,
1492    struct in6_multi *inm, const int uri_fasthz)
1493{
1494	int query_response_timer_expired;
1495	int state_change_retransmit_timer_expired;
1496#ifdef KTR
1497	char ip6tbuf[INET6_ADDRSTRLEN];
1498#endif
1499
1500	IN6_MULTI_LOCK_ASSERT();
1501	MLD_LOCK_ASSERT();
1502
1503	query_response_timer_expired = 0;
1504	state_change_retransmit_timer_expired = 0;
1505
1506	/*
1507	 * During a transition from compatibility mode back to MLDv2,
1508	 * a group record in REPORTING state may still have its group
1509	 * timer active. This is a no-op in this function; it is easier
1510	 * to deal with it here than to complicate the slow-timeout path.
1511	 */
1512	if (inm->in6m_timer == 0) {
1513		query_response_timer_expired = 0;
1514	} else if (--inm->in6m_timer == 0) {
1515		query_response_timer_expired = 1;
1516	} else {
1517		V_current_state_timers_running6 = 1;
1518	}
1519
1520	if (inm->in6m_sctimer == 0) {
1521		state_change_retransmit_timer_expired = 0;
1522	} else if (--inm->in6m_sctimer == 0) {
1523		state_change_retransmit_timer_expired = 1;
1524	} else {
1525		V_state_change_timers_running6 = 1;
1526	}
1527
1528	/* We are in fasttimo, so be quick about it. */
1529	if (!state_change_retransmit_timer_expired &&
1530	    !query_response_timer_expired)
1531		return;
1532
1533	switch (inm->in6m_state) {
1534	case MLD_NOT_MEMBER:
1535	case MLD_SILENT_MEMBER:
1536	case MLD_SLEEPING_MEMBER:
1537	case MLD_LAZY_MEMBER:
1538	case MLD_AWAKENING_MEMBER:
1539	case MLD_IDLE_MEMBER:
1540		break;
1541	case MLD_G_QUERY_PENDING_MEMBER:
1542	case MLD_SG_QUERY_PENDING_MEMBER:
1543		/*
1544		 * Respond to a previously pending Group-Specific
1545		 * or Group-and-Source-Specific query by enqueueing
1546		 * the appropriate Current-State report for
1547		 * immediate transmission.
1548		 */
1549		if (query_response_timer_expired) {
1550			int retval;
1551
1552			retval = mld_v2_enqueue_group_record(qrq, inm, 0, 1,
1553			    (inm->in6m_state == MLD_SG_QUERY_PENDING_MEMBER));
1554			CTR2(KTR_MLD, "%s: enqueue record = %d",
1555			    __func__, retval);
1556			inm->in6m_state = MLD_REPORTING_MEMBER;
1557			in6m_clear_recorded(inm);
1558		}
1559		/* FALLTHROUGH */
1560	case MLD_REPORTING_MEMBER:
1561	case MLD_LEAVING_MEMBER:
1562		if (state_change_retransmit_timer_expired) {
1563			/*
1564			 * State-change retransmission timer fired.
1565			 * If there are any further pending retransmissions,
1566			 * set the global pending state-change flag, and
1567			 * reset the timer.
1568			 */
1569			if (--inm->in6m_scrv > 0) {
1570				inm->in6m_sctimer = uri_fasthz;
1571				V_state_change_timers_running6 = 1;
1572			}
1573			/*
1574			 * Retransmit the previously computed state-change
1575			 * report. If there are no further pending
1576			 * retransmissions, the mbuf queue will be consumed.
1577			 * Update T0 state to T1 as we have now sent
1578			 * a state-change.
1579			 */
1580			(void)mld_v2_merge_state_changes(inm, scq);
1581
1582			in6m_commit(inm);
1583			CTR3(KTR_MLD, "%s: T1 -> T0 for %s/%s", __func__,
1584			    ip6_sprintf(ip6tbuf, &inm->in6m_addr),
1585			    inm->in6m_ifp->if_xname);
1586
1587			/*
1588			 * If we are leaving the group for good, make sure
1589			 * we release MLD's reference to it.
1590			 * This release must be deferred using a SLIST,
1591			 * as we are called from a loop which traverses
1592			 * the in_ifmultiaddr TAILQ.
1593			 */
1594			if (inm->in6m_state == MLD_LEAVING_MEMBER &&
1595			    inm->in6m_scrv == 0) {
1596				inm->in6m_state = MLD_NOT_MEMBER;
1597				SLIST_INSERT_HEAD(&mli->mli_relinmhead,
1598				    inm, in6m_nrele);
1599			}
1600		}
1601		break;
1602	}
1603}
1604
1605/*
1606 * Switch to a different version on the given interface,
1607 * as per Section 9.12.
1608 */
1609static void
1610mld_set_version(struct mld_ifinfo *mli, const int version)
1611{
1612	int old_version_timer;
1613
1614	MLD_LOCK_ASSERT();
1615
1616	CTR4(KTR_MLD, "%s: switching to v%d on ifp %p(%s)", __func__,
1617	    version, mli->mli_ifp, mli->mli_ifp->if_xname);
1618
1619	if (version == MLD_VERSION_1) {
1620		/*
1621		 * Compute the "Older Version Querier Present" timer as per
1622		 * Section 9.12.
1623		 */
1624		old_version_timer = (mli->mli_rv * mli->mli_qi) + mli->mli_qri;
1625		old_version_timer *= PR_SLOWHZ;
1626		mli->mli_v1_timer = old_version_timer;
1627	}
1628
1629	if (mli->mli_v1_timer > 0 && mli->mli_version != MLD_VERSION_1) {
1630		mli->mli_version = MLD_VERSION_1;
1631		mld_v2_cancel_link_timers(mli);
1632	}
1633}
1634
1635/*
1636 * Cancel pending MLDv2 timers for the given link and all groups
1637 * joined on it; state-change, general-query, and group-query timers.
1638 */
1639static void
1640mld_v2_cancel_link_timers(struct mld_ifinfo *mli)
1641{
1642	struct ifmultiaddr	*ifma;
1643	struct ifnet		*ifp;
1644	struct in6_multi		*inm;
1645
1646	CTR3(KTR_MLD, "%s: cancel v2 timers on ifp %p(%s)", __func__,
1647	    mli->mli_ifp, mli->mli_ifp->if_xname);
1648
1649	IN6_MULTI_LOCK_ASSERT();
1650	MLD_LOCK_ASSERT();
1651
1652	/*
1653	 * Fast-track this potentially expensive operation
1654	 * by checking all the global 'timer pending' flags.
1655	 */
1656	if (!V_interface_timers_running6 &&
1657	    !V_state_change_timers_running6 &&
1658	    !V_current_state_timers_running6)
1659		return;
1660
1661	mli->mli_v2_timer = 0;
1662
1663	ifp = mli->mli_ifp;
1664
1665	IF_ADDR_LOCK(ifp);
1666	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1667		if (ifma->ifma_addr->sa_family != AF_INET6)
1668			continue;
1669		inm = (struct in6_multi *)ifma->ifma_protospec;
1670		switch (inm->in6m_state) {
1671		case MLD_NOT_MEMBER:
1672		case MLD_SILENT_MEMBER:
1673		case MLD_IDLE_MEMBER:
1674		case MLD_LAZY_MEMBER:
1675		case MLD_SLEEPING_MEMBER:
1676		case MLD_AWAKENING_MEMBER:
1677			break;
1678		case MLD_LEAVING_MEMBER:
1679			/*
1680			 * If we are leaving the group and switching
1681			 * version, we need to release the final
1682			 * reference held for issuing the INCLUDE {}.
1683			 *
1684			 * SMPNG: Must drop and re-acquire IF_ADDR_LOCK
1685			 * around in6m_release_locked(), as it is not
1686			 * a recursive mutex.
1687			 */
1688			IF_ADDR_UNLOCK(ifp);
1689			in6m_release_locked(inm);
1690			IF_ADDR_LOCK(ifp);
1691			/* FALLTHROUGH */
1692		case MLD_G_QUERY_PENDING_MEMBER:
1693		case MLD_SG_QUERY_PENDING_MEMBER:
1694			in6m_clear_recorded(inm);
1695			/* FALLTHROUGH */
1696		case MLD_REPORTING_MEMBER:
1697			inm->in6m_sctimer = 0;
1698			inm->in6m_timer = 0;
1699			inm->in6m_state = MLD_REPORTING_MEMBER;
1700			/*
1701			 * Free any pending MLDv2 state-change records.
1702			 */
1703			_IF_DRAIN(&inm->in6m_scq);
1704			break;
1705		}
1706	}
1707	IF_ADDR_UNLOCK(ifp);
1708}
1709
1710/*
1711 * Global slowtimo handler.
1712 * VIMAGE: Timeout handlers are expected to service all vimages.
1713 */
1714void
1715mld_slowtimo(void)
1716{
1717	VNET_ITERATOR_DECL(vnet_iter);
1718
1719	VNET_LIST_RLOCK_NOSLEEP();
1720	VNET_FOREACH(vnet_iter) {
1721		CURVNET_SET(vnet_iter);
1722		mld_slowtimo_vnet();
1723		CURVNET_RESTORE();
1724	}
1725	VNET_LIST_RUNLOCK_NOSLEEP();
1726}
1727
1728/*
1729 * Per-vnet slowtimo handler.
1730 */
1731static void
1732mld_slowtimo_vnet(void)
1733{
1734	struct mld_ifinfo *mli;
1735
1736	MLD_LOCK();
1737
1738	LIST_FOREACH(mli, &V_mli_head, mli_link) {
1739		mld_v1_process_querier_timers(mli);
1740	}
1741
1742	MLD_UNLOCK();
1743}
1744
1745/*
1746 * Update the Older Version Querier Present timers for a link.
1747 * See Section 9.12 of RFC 3810.
1748 */
1749static void
1750mld_v1_process_querier_timers(struct mld_ifinfo *mli)
1751{
1752
1753	MLD_LOCK_ASSERT();
1754
1755	if (mli->mli_version != MLD_VERSION_2 && --mli->mli_v1_timer == 0) {
1756		/*
1757		 * MLDv1 Querier Present timer expired; revert to MLDv2.
1758		 */
1759		CTR5(KTR_MLD,
1760		    "%s: transition from v%d -> v%d on %p(%s)",
1761		    __func__, mli->mli_version, MLD_VERSION_2,
1762		    mli->mli_ifp, mli->mli_ifp->if_xname);
1763		mli->mli_version = MLD_VERSION_2;
1764	}
1765}
1766
1767/*
1768 * Transmit an MLDv1 report immediately.
1769 */
1770static int
1771mld_v1_transmit_report(struct in6_multi *in6m, const int type)
1772{
1773	struct ifnet		*ifp;
1774	struct in6_ifaddr	*ia;
1775	struct ip6_hdr		*ip6;
1776	struct mbuf		*mh, *md;
1777	struct mld_hdr		*mld;
1778
1779	IN6_MULTI_LOCK_ASSERT();
1780	MLD_LOCK_ASSERT();
1781
1782	ifp = in6m->in6m_ifp;
1783	ia = in6ifa_ifpforlinklocal(ifp, IN6_IFF_NOTREADY|IN6_IFF_ANYCAST);
1784	/* ia may be NULL if link-local address is tentative. */
1785
1786	MGETHDR(mh, M_DONTWAIT, MT_HEADER);
1787	if (mh == NULL) {
1788		if (ia != NULL)
1789			ifa_free(&ia->ia_ifa);
1790		return (ENOMEM);
1791	}
1792	MGET(md, M_DONTWAIT, MT_DATA);
1793	if (md == NULL) {
1794		m_free(mh);
1795		if (ia != NULL)
1796			ifa_free(&ia->ia_ifa);
1797		return (ENOMEM);
1798	}
1799	mh->m_next = md;
1800
1801	/*
1802	 * FUTURE: Consider increasing alignment by ETHER_HDR_LEN, so
1803	 * that ether_output() does not need to allocate another mbuf
1804	 * for the header in the most common case.
1805	 */
1806	MH_ALIGN(mh, sizeof(struct ip6_hdr));
1807	mh->m_pkthdr.len = sizeof(struct ip6_hdr) + sizeof(struct mld_hdr);
1808	mh->m_len = sizeof(struct ip6_hdr);
1809
1810	ip6 = mtod(mh, struct ip6_hdr *);
1811	ip6->ip6_flow = 0;
1812	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
1813	ip6->ip6_vfc |= IPV6_VERSION;
1814	ip6->ip6_nxt = IPPROTO_ICMPV6;
1815	ip6->ip6_src = ia ? ia->ia_addr.sin6_addr : in6addr_any;
1816	ip6->ip6_dst = in6m->in6m_addr;
1817
1818	md->m_len = sizeof(struct mld_hdr);
1819	mld = mtod(md, struct mld_hdr *);
1820	mld->mld_type = type;
1821	mld->mld_code = 0;
1822	mld->mld_cksum = 0;
1823	mld->mld_maxdelay = 0;
1824	mld->mld_reserved = 0;
1825	mld->mld_addr = in6m->in6m_addr;
1826	in6_clearscope(&mld->mld_addr);
1827	mld->mld_cksum = in6_cksum(mh, IPPROTO_ICMPV6,
1828	    sizeof(struct ip6_hdr), sizeof(struct mld_hdr));
1829
1830	mld_save_context(mh, ifp);
1831	mh->m_flags |= M_MLDV1;
1832
1833	mld_dispatch_packet(mh);
1834
1835	if (ia != NULL)
1836		ifa_free(&ia->ia_ifa);
1837	return (0);
1838}
1839
1840/*
1841 * Process a state change from the upper layer for the given IPv6 group.
1842 *
1843 * Each socket holds a reference on the in_multi in its own ip_moptions.
1844 * The socket layer will have made the necessary updates to.the group
1845 * state, it is now up to MLD to issue a state change report if there
1846 * has been any change between T0 (when the last state-change was issued)
1847 * and T1 (now).
1848 *
1849 * We use the MLDv2 state machine at group level. The MLd module
1850 * however makes the decision as to which MLD protocol version to speak.
1851 * A state change *from* INCLUDE {} always means an initial join.
1852 * A state change *to* INCLUDE {} always means a final leave.
1853 *
1854 * If delay is non-zero, and the state change is an initial multicast
1855 * join, the state change report will be delayed by 'delay' ticks
1856 * in units of PR_FASTHZ if MLDv1 is active on the link; otherwise
1857 * the initial MLDv2 state change report will be delayed by whichever
1858 * is sooner, a pending state-change timer or delay itself.
1859 *
1860 * VIMAGE: curvnet should have been set by caller, as this routine
1861 * is called from the socket option handlers.
1862 */
1863int
1864mld_change_state(struct in6_multi *inm, const int delay)
1865{
1866	struct mld_ifinfo *mli;
1867	struct ifnet *ifp;
1868	int error;
1869
1870	IN6_MULTI_LOCK_ASSERT();
1871
1872	error = 0;
1873
1874	/*
1875	 * Try to detect if the upper layer just asked us to change state
1876	 * for an interface which has now gone away.
1877	 */
1878	KASSERT(inm->in6m_ifma != NULL, ("%s: no ifma", __func__));
1879	ifp = inm->in6m_ifma->ifma_ifp;
1880	if (ifp != NULL) {
1881		/*
1882		 * Sanity check that netinet6's notion of ifp is the
1883		 * same as net's.
1884		 */
1885		KASSERT(inm->in6m_ifp == ifp, ("%s: bad ifp", __func__));
1886	}
1887
1888	MLD_LOCK();
1889
1890	mli = MLD_IFINFO(ifp);
1891	KASSERT(mli != NULL, ("%s: no mld_ifinfo for ifp %p", __func__, ifp));
1892
1893	/*
1894	 * If we detect a state transition to or from MCAST_UNDEFINED
1895	 * for this group, then we are starting or finishing an MLD
1896	 * life cycle for this group.
1897	 */
1898	if (inm->in6m_st[1].iss_fmode != inm->in6m_st[0].iss_fmode) {
1899		CTR3(KTR_MLD, "%s: inm transition %d -> %d", __func__,
1900		    inm->in6m_st[0].iss_fmode, inm->in6m_st[1].iss_fmode);
1901		if (inm->in6m_st[0].iss_fmode == MCAST_UNDEFINED) {
1902			CTR1(KTR_MLD, "%s: initial join", __func__);
1903			error = mld_initial_join(inm, mli, delay);
1904			goto out_locked;
1905		} else if (inm->in6m_st[1].iss_fmode == MCAST_UNDEFINED) {
1906			CTR1(KTR_MLD, "%s: final leave", __func__);
1907			mld_final_leave(inm, mli);
1908			goto out_locked;
1909		}
1910	} else {
1911		CTR1(KTR_MLD, "%s: filter set change", __func__);
1912	}
1913
1914	error = mld_handle_state_change(inm, mli);
1915
1916out_locked:
1917	MLD_UNLOCK();
1918	return (error);
1919}
1920
1921/*
1922 * Perform the initial join for an MLD group.
1923 *
1924 * When joining a group:
1925 *  If the group should have its MLD traffic suppressed, do nothing.
1926 *  MLDv1 starts sending MLDv1 host membership reports.
1927 *  MLDv2 will schedule an MLDv2 state-change report containing the
1928 *  initial state of the membership.
1929 *
1930 * If the delay argument is non-zero, then we must delay sending the
1931 * initial state change for delay ticks (in units of PR_FASTHZ).
1932 */
1933static int
1934mld_initial_join(struct in6_multi *inm, struct mld_ifinfo *mli,
1935    const int delay)
1936{
1937	struct ifnet		*ifp;
1938	struct ifqueue		*ifq;
1939	int			 error, retval, syncstates;
1940	int			 odelay;
1941#ifdef KTR
1942	char			 ip6tbuf[INET6_ADDRSTRLEN];
1943#endif
1944
1945	CTR4(KTR_MLD, "%s: initial join %s on ifp %p(%s)",
1946	    __func__, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
1947	    inm->in6m_ifp, inm->in6m_ifp->if_xname);
1948
1949	error = 0;
1950	syncstates = 1;
1951
1952	ifp = inm->in6m_ifp;
1953
1954	IN6_MULTI_LOCK_ASSERT();
1955	MLD_LOCK_ASSERT();
1956
1957	KASSERT(mli && mli->mli_ifp == ifp, ("%s: inconsistent ifp", __func__));
1958
1959	/*
1960	 * Groups joined on loopback or marked as 'not reported',
1961	 * enter the MLD_SILENT_MEMBER state and
1962	 * are never reported in any protocol exchanges.
1963	 * All other groups enter the appropriate state machine
1964	 * for the version in use on this link.
1965	 * A link marked as MLIF_SILENT causes MLD to be completely
1966	 * disabled for the link.
1967	 */
1968	if ((ifp->if_flags & IFF_LOOPBACK) ||
1969	    (mli->mli_flags & MLIF_SILENT) ||
1970	    !mld_is_addr_reported(&inm->in6m_addr)) {
1971		CTR1(KTR_MLD,
1972"%s: not kicking state machine for silent group", __func__);
1973		inm->in6m_state = MLD_SILENT_MEMBER;
1974		inm->in6m_timer = 0;
1975	} else {
1976		/*
1977		 * Deal with overlapping in_multi lifecycle.
1978		 * If this group was LEAVING, then make sure
1979		 * we drop the reference we picked up to keep the
1980		 * group around for the final INCLUDE {} enqueue.
1981		 */
1982		if (mli->mli_version == MLD_VERSION_2 &&
1983		    inm->in6m_state == MLD_LEAVING_MEMBER)
1984			in6m_release_locked(inm);
1985
1986		inm->in6m_state = MLD_REPORTING_MEMBER;
1987
1988		switch (mli->mli_version) {
1989		case MLD_VERSION_1:
1990			/*
1991			 * If a delay was provided, only use it if
1992			 * it is greater than the delay normally
1993			 * used for an MLDv1 state change report,
1994			 * and delay sending the initial MLDv1 report
1995			 * by not transitioning to the IDLE state.
1996			 */
1997			odelay = MLD_RANDOM_DELAY(MLD_V1_MAX_RI * PR_FASTHZ);
1998			if (delay) {
1999				inm->in6m_timer = max(delay, odelay);
2000				V_current_state_timers_running6 = 1;
2001			} else {
2002				inm->in6m_state = MLD_IDLE_MEMBER;
2003				error = mld_v1_transmit_report(inm,
2004				     MLD_LISTENER_REPORT);
2005				if (error == 0) {
2006					inm->in6m_timer = odelay;
2007					V_current_state_timers_running6 = 1;
2008				}
2009			}
2010			break;
2011
2012		case MLD_VERSION_2:
2013			/*
2014			 * Defer update of T0 to T1, until the first copy
2015			 * of the state change has been transmitted.
2016			 */
2017			syncstates = 0;
2018
2019			/*
2020			 * Immediately enqueue a State-Change Report for
2021			 * this interface, freeing any previous reports.
2022			 * Don't kick the timers if there is nothing to do,
2023			 * or if an error occurred.
2024			 */
2025			ifq = &inm->in6m_scq;
2026			_IF_DRAIN(ifq);
2027			retval = mld_v2_enqueue_group_record(ifq, inm, 1,
2028			    0, 0);
2029			CTR2(KTR_MLD, "%s: enqueue record = %d",
2030			    __func__, retval);
2031			if (retval <= 0) {
2032				error = retval * -1;
2033				break;
2034			}
2035
2036			/*
2037			 * Schedule transmission of pending state-change
2038			 * report up to RV times for this link. The timer
2039			 * will fire at the next mld_fasttimo (~200ms),
2040			 * giving us an opportunity to merge the reports.
2041			 *
2042			 * If a delay was provided to this function, only
2043			 * use this delay if sooner than the existing one.
2044			 */
2045			KASSERT(mli->mli_rv > 1,
2046			   ("%s: invalid robustness %d", __func__,
2047			    mli->mli_rv));
2048			inm->in6m_scrv = mli->mli_rv;
2049			if (delay) {
2050				if (inm->in6m_sctimer > 1) {
2051					inm->in6m_sctimer =
2052					    min(inm->in6m_sctimer, delay);
2053				} else
2054					inm->in6m_sctimer = delay;
2055			} else
2056				inm->in6m_sctimer = 1;
2057			V_state_change_timers_running6 = 1;
2058
2059			error = 0;
2060			break;
2061		}
2062	}
2063
2064	/*
2065	 * Only update the T0 state if state change is atomic,
2066	 * i.e. we don't need to wait for a timer to fire before we
2067	 * can consider the state change to have been communicated.
2068	 */
2069	if (syncstates) {
2070		in6m_commit(inm);
2071		CTR3(KTR_MLD, "%s: T1 -> T0 for %s/%s", __func__,
2072		    ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2073		    inm->in6m_ifp->if_xname);
2074	}
2075
2076	return (error);
2077}
2078
2079/*
2080 * Issue an intermediate state change during the life-cycle.
2081 */
2082static int
2083mld_handle_state_change(struct in6_multi *inm, struct mld_ifinfo *mli)
2084{
2085	struct ifnet		*ifp;
2086	int			 retval;
2087#ifdef KTR
2088	char			 ip6tbuf[INET6_ADDRSTRLEN];
2089#endif
2090
2091	CTR4(KTR_MLD, "%s: state change for %s on ifp %p(%s)",
2092	    __func__, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2093	    inm->in6m_ifp, inm->in6m_ifp->if_xname);
2094
2095	ifp = inm->in6m_ifp;
2096
2097	IN6_MULTI_LOCK_ASSERT();
2098	MLD_LOCK_ASSERT();
2099
2100	KASSERT(mli && mli->mli_ifp == ifp,
2101	    ("%s: inconsistent ifp", __func__));
2102
2103	if ((ifp->if_flags & IFF_LOOPBACK) ||
2104	    (mli->mli_flags & MLIF_SILENT) ||
2105	    !mld_is_addr_reported(&inm->in6m_addr) ||
2106	    (mli->mli_version != MLD_VERSION_2)) {
2107		if (!mld_is_addr_reported(&inm->in6m_addr)) {
2108			CTR1(KTR_MLD,
2109"%s: not kicking state machine for silent group", __func__);
2110		}
2111		CTR1(KTR_MLD, "%s: nothing to do", __func__);
2112		in6m_commit(inm);
2113		CTR3(KTR_MLD, "%s: T1 -> T0 for %s/%s", __func__,
2114		    ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2115		    inm->in6m_ifp->if_xname);
2116		return (0);
2117	}
2118
2119	_IF_DRAIN(&inm->in6m_scq);
2120
2121	retval = mld_v2_enqueue_group_record(&inm->in6m_scq, inm, 1, 0, 0);
2122	CTR2(KTR_MLD, "%s: enqueue record = %d", __func__, retval);
2123	if (retval <= 0)
2124		return (-retval);
2125
2126	/*
2127	 * If record(s) were enqueued, start the state-change
2128	 * report timer for this group.
2129	 */
2130	inm->in6m_scrv = mli->mli_rv;
2131	inm->in6m_sctimer = 1;
2132	V_state_change_timers_running6 = 1;
2133
2134	return (0);
2135}
2136
2137/*
2138 * Perform the final leave for a multicast address.
2139 *
2140 * When leaving a group:
2141 *  MLDv1 sends a DONE message, if and only if we are the reporter.
2142 *  MLDv2 enqueues a state-change report containing a transition
2143 *  to INCLUDE {} for immediate transmission.
2144 */
2145static void
2146mld_final_leave(struct in6_multi *inm, struct mld_ifinfo *mli)
2147{
2148	int syncstates;
2149#ifdef KTR
2150	char ip6tbuf[INET6_ADDRSTRLEN];
2151#endif
2152
2153	syncstates = 1;
2154
2155	CTR4(KTR_MLD, "%s: final leave %s on ifp %p(%s)",
2156	    __func__, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2157	    inm->in6m_ifp, inm->in6m_ifp->if_xname);
2158
2159	IN6_MULTI_LOCK_ASSERT();
2160	MLD_LOCK_ASSERT();
2161
2162	switch (inm->in6m_state) {
2163	case MLD_NOT_MEMBER:
2164	case MLD_SILENT_MEMBER:
2165	case MLD_LEAVING_MEMBER:
2166		/* Already leaving or left; do nothing. */
2167		CTR1(KTR_MLD,
2168"%s: not kicking state machine for silent group", __func__);
2169		break;
2170	case MLD_REPORTING_MEMBER:
2171	case MLD_IDLE_MEMBER:
2172	case MLD_G_QUERY_PENDING_MEMBER:
2173	case MLD_SG_QUERY_PENDING_MEMBER:
2174		if (mli->mli_version == MLD_VERSION_1) {
2175#ifdef INVARIANTS
2176			if (inm->in6m_state == MLD_G_QUERY_PENDING_MEMBER ||
2177			    inm->in6m_state == MLD_SG_QUERY_PENDING_MEMBER)
2178			panic("%s: MLDv2 state reached, not MLDv2 mode",
2179			     __func__);
2180#endif
2181			mld_v1_transmit_report(inm, MLD_LISTENER_DONE);
2182			inm->in6m_state = MLD_NOT_MEMBER;
2183		} else if (mli->mli_version == MLD_VERSION_2) {
2184			/*
2185			 * Stop group timer and all pending reports.
2186			 * Immediately enqueue a state-change report
2187			 * TO_IN {} to be sent on the next fast timeout,
2188			 * giving us an opportunity to merge reports.
2189			 */
2190			_IF_DRAIN(&inm->in6m_scq);
2191			inm->in6m_timer = 0;
2192			inm->in6m_scrv = mli->mli_rv;
2193			CTR4(KTR_MLD, "%s: Leaving %s/%s with %d "
2194			    "pending retransmissions.", __func__,
2195			    ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2196			    inm->in6m_ifp->if_xname, inm->in6m_scrv);
2197			if (inm->in6m_scrv == 0) {
2198				inm->in6m_state = MLD_NOT_MEMBER;
2199				inm->in6m_sctimer = 0;
2200			} else {
2201				int retval;
2202
2203				in6m_acquire_locked(inm);
2204
2205				retval = mld_v2_enqueue_group_record(
2206				    &inm->in6m_scq, inm, 1, 0, 0);
2207				KASSERT(retval != 0,
2208				    ("%s: enqueue record = %d", __func__,
2209				     retval));
2210
2211				inm->in6m_state = MLD_LEAVING_MEMBER;
2212				inm->in6m_sctimer = 1;
2213				V_state_change_timers_running6 = 1;
2214				syncstates = 0;
2215			}
2216			break;
2217		}
2218		break;
2219	case MLD_LAZY_MEMBER:
2220	case MLD_SLEEPING_MEMBER:
2221	case MLD_AWAKENING_MEMBER:
2222		/* Our reports are suppressed; do nothing. */
2223		break;
2224	}
2225
2226	if (syncstates) {
2227		in6m_commit(inm);
2228		CTR3(KTR_MLD, "%s: T1 -> T0 for %s/%s", __func__,
2229		    ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2230		    inm->in6m_ifp->if_xname);
2231		inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
2232		CTR3(KTR_MLD, "%s: T1 now MCAST_UNDEFINED for %p/%s",
2233		    __func__, &inm->in6m_addr, inm->in6m_ifp->if_xname);
2234	}
2235}
2236
2237/*
2238 * Enqueue an MLDv2 group record to the given output queue.
2239 *
2240 * If is_state_change is zero, a current-state record is appended.
2241 * If is_state_change is non-zero, a state-change report is appended.
2242 *
2243 * If is_group_query is non-zero, an mbuf packet chain is allocated.
2244 * If is_group_query is zero, and if there is a packet with free space
2245 * at the tail of the queue, it will be appended to providing there
2246 * is enough free space.
2247 * Otherwise a new mbuf packet chain is allocated.
2248 *
2249 * If is_source_query is non-zero, each source is checked to see if
2250 * it was recorded for a Group-Source query, and will be omitted if
2251 * it is not both in-mode and recorded.
2252 *
2253 * The function will attempt to allocate leading space in the packet
2254 * for the IPv6+ICMP headers to be prepended without fragmenting the chain.
2255 *
2256 * If successful the size of all data appended to the queue is returned,
2257 * otherwise an error code less than zero is returned, or zero if
2258 * no record(s) were appended.
2259 */
2260static int
2261mld_v2_enqueue_group_record(struct ifqueue *ifq, struct in6_multi *inm,
2262    const int is_state_change, const int is_group_query,
2263    const int is_source_query)
2264{
2265	struct mldv2_record	 mr;
2266	struct mldv2_record	*pmr;
2267	struct ifnet		*ifp;
2268	struct ip6_msource	*ims, *nims;
2269	struct mbuf		*m0, *m, *md;
2270	int			 error, is_filter_list_change;
2271	int			 minrec0len, m0srcs, msrcs, nbytes, off;
2272	int			 record_has_sources;
2273	int			 now;
2274	int			 type;
2275	uint8_t			 mode;
2276#ifdef KTR
2277	char			 ip6tbuf[INET6_ADDRSTRLEN];
2278#endif
2279
2280	IN6_MULTI_LOCK_ASSERT();
2281
2282	error = 0;
2283	ifp = inm->in6m_ifp;
2284	is_filter_list_change = 0;
2285	m = NULL;
2286	m0 = NULL;
2287	m0srcs = 0;
2288	msrcs = 0;
2289	nbytes = 0;
2290	nims = NULL;
2291	record_has_sources = 1;
2292	pmr = NULL;
2293	type = MLD_DO_NOTHING;
2294	mode = inm->in6m_st[1].iss_fmode;
2295
2296	/*
2297	 * If we did not transition out of ASM mode during t0->t1,
2298	 * and there are no source nodes to process, we can skip
2299	 * the generation of source records.
2300	 */
2301	if (inm->in6m_st[0].iss_asm > 0 && inm->in6m_st[1].iss_asm > 0 &&
2302	    inm->in6m_nsrc == 0)
2303		record_has_sources = 0;
2304
2305	if (is_state_change) {
2306		/*
2307		 * Queue a state change record.
2308		 * If the mode did not change, and there are non-ASM
2309		 * listeners or source filters present,
2310		 * we potentially need to issue two records for the group.
2311		 * If we are transitioning to MCAST_UNDEFINED, we need
2312		 * not send any sources.
2313		 * If there are ASM listeners, and there was no filter
2314		 * mode transition of any kind, do nothing.
2315		 */
2316		if (mode != inm->in6m_st[0].iss_fmode) {
2317			if (mode == MCAST_EXCLUDE) {
2318				CTR1(KTR_MLD, "%s: change to EXCLUDE",
2319				    __func__);
2320				type = MLD_CHANGE_TO_EXCLUDE_MODE;
2321			} else {
2322				CTR1(KTR_MLD, "%s: change to INCLUDE",
2323				    __func__);
2324				type = MLD_CHANGE_TO_INCLUDE_MODE;
2325				if (mode == MCAST_UNDEFINED)
2326					record_has_sources = 0;
2327			}
2328		} else {
2329			if (record_has_sources) {
2330				is_filter_list_change = 1;
2331			} else {
2332				type = MLD_DO_NOTHING;
2333			}
2334		}
2335	} else {
2336		/*
2337		 * Queue a current state record.
2338		 */
2339		if (mode == MCAST_EXCLUDE) {
2340			type = MLD_MODE_IS_EXCLUDE;
2341		} else if (mode == MCAST_INCLUDE) {
2342			type = MLD_MODE_IS_INCLUDE;
2343			KASSERT(inm->in6m_st[1].iss_asm == 0,
2344			    ("%s: inm %p is INCLUDE but ASM count is %d",
2345			     __func__, inm, inm->in6m_st[1].iss_asm));
2346		}
2347	}
2348
2349	/*
2350	 * Generate the filter list changes using a separate function.
2351	 */
2352	if (is_filter_list_change)
2353		return (mld_v2_enqueue_filter_change(ifq, inm));
2354
2355	if (type == MLD_DO_NOTHING) {
2356		CTR3(KTR_MLD, "%s: nothing to do for %s/%s",
2357		    __func__, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2358		    inm->in6m_ifp->if_xname);
2359		return (0);
2360	}
2361
2362	/*
2363	 * If any sources are present, we must be able to fit at least
2364	 * one in the trailing space of the tail packet's mbuf,
2365	 * ideally more.
2366	 */
2367	minrec0len = sizeof(struct mldv2_record);
2368	if (record_has_sources)
2369		minrec0len += sizeof(struct in6_addr);
2370
2371	CTR4(KTR_MLD, "%s: queueing %s for %s/%s", __func__,
2372	    mld_rec_type_to_str(type),
2373	    ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2374	    inm->in6m_ifp->if_xname);
2375
2376	/*
2377	 * Check if we have a packet in the tail of the queue for this
2378	 * group into which the first group record for this group will fit.
2379	 * Otherwise allocate a new packet.
2380	 * Always allocate leading space for IP6+RA+ICMPV6+REPORT.
2381	 * Note: Group records for G/GSR query responses MUST be sent
2382	 * in their own packet.
2383	 */
2384	m0 = ifq->ifq_tail;
2385	if (!is_group_query &&
2386	    m0 != NULL &&
2387	    (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <= MLD_V2_REPORT_MAXRECS) &&
2388	    (m0->m_pkthdr.len + minrec0len) <
2389	     (ifp->if_mtu - MLD_MTUSPACE)) {
2390		m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
2391			    sizeof(struct mldv2_record)) /
2392			    sizeof(struct in6_addr);
2393		m = m0;
2394		CTR1(KTR_MLD, "%s: use existing packet", __func__);
2395	} else {
2396		if (_IF_QFULL(ifq)) {
2397			CTR1(KTR_MLD, "%s: outbound queue full", __func__);
2398			return (-ENOMEM);
2399		}
2400		m = NULL;
2401		m0srcs = (ifp->if_mtu - MLD_MTUSPACE -
2402		    sizeof(struct mldv2_record)) / sizeof(struct in6_addr);
2403		if (!is_state_change && !is_group_query)
2404			m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2405		if (m == NULL)
2406			m = m_gethdr(M_DONTWAIT, MT_DATA);
2407		if (m == NULL)
2408			return (-ENOMEM);
2409
2410		mld_save_context(m, ifp);
2411
2412		CTR1(KTR_MLD, "%s: allocated first packet", __func__);
2413	}
2414
2415	/*
2416	 * Append group record.
2417	 * If we have sources, we don't know how many yet.
2418	 */
2419	mr.mr_type = type;
2420	mr.mr_datalen = 0;
2421	mr.mr_numsrc = 0;
2422	mr.mr_addr = inm->in6m_addr;
2423	in6_clearscope(&mr.mr_addr);
2424	if (!m_append(m, sizeof(struct mldv2_record), (void *)&mr)) {
2425		if (m != m0)
2426			m_freem(m);
2427		CTR1(KTR_MLD, "%s: m_append() failed.", __func__);
2428		return (-ENOMEM);
2429	}
2430	nbytes += sizeof(struct mldv2_record);
2431
2432	/*
2433	 * Append as many sources as will fit in the first packet.
2434	 * If we are appending to a new packet, the chain allocation
2435	 * may potentially use clusters; use m_getptr() in this case.
2436	 * If we are appending to an existing packet, we need to obtain
2437	 * a pointer to the group record after m_append(), in case a new
2438	 * mbuf was allocated.
2439	 * Only append sources which are in-mode at t1. If we are
2440	 * transitioning to MCAST_UNDEFINED state on the group, do not
2441	 * include source entries.
2442	 * Only report recorded sources in our filter set when responding
2443	 * to a group-source query.
2444	 */
2445	if (record_has_sources) {
2446		if (m == m0) {
2447			md = m_last(m);
2448			pmr = (struct mldv2_record *)(mtod(md, uint8_t *) +
2449			    md->m_len - nbytes);
2450		} else {
2451			md = m_getptr(m, 0, &off);
2452			pmr = (struct mldv2_record *)(mtod(md, uint8_t *) +
2453			    off);
2454		}
2455		msrcs = 0;
2456		RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs,
2457		    nims) {
2458			CTR2(KTR_MLD, "%s: visit node %s", __func__,
2459			    ip6_sprintf(ip6tbuf, &ims->im6s_addr));
2460			now = im6s_get_mode(inm, ims, 1);
2461			CTR2(KTR_MLD, "%s: node is %d", __func__, now);
2462			if ((now != mode) ||
2463			    (now == mode && mode == MCAST_UNDEFINED)) {
2464				CTR1(KTR_MLD, "%s: skip node", __func__);
2465				continue;
2466			}
2467			if (is_source_query && ims->im6s_stp == 0) {
2468				CTR1(KTR_MLD, "%s: skip unrecorded node",
2469				    __func__);
2470				continue;
2471			}
2472			CTR1(KTR_MLD, "%s: append node", __func__);
2473			if (!m_append(m, sizeof(struct in6_addr),
2474			    (void *)&ims->im6s_addr)) {
2475				if (m != m0)
2476					m_freem(m);
2477				CTR1(KTR_MLD, "%s: m_append() failed.",
2478				    __func__);
2479				return (-ENOMEM);
2480			}
2481			nbytes += sizeof(struct in6_addr);
2482			++msrcs;
2483			if (msrcs == m0srcs)
2484				break;
2485		}
2486		CTR2(KTR_MLD, "%s: msrcs is %d this packet", __func__,
2487		    msrcs);
2488		pmr->mr_numsrc = htons(msrcs);
2489		nbytes += (msrcs * sizeof(struct in6_addr));
2490	}
2491
2492	if (is_source_query && msrcs == 0) {
2493		CTR1(KTR_MLD, "%s: no recorded sources to report", __func__);
2494		if (m != m0)
2495			m_freem(m);
2496		return (0);
2497	}
2498
2499	/*
2500	 * We are good to go with first packet.
2501	 */
2502	if (m != m0) {
2503		CTR1(KTR_MLD, "%s: enqueueing first packet", __func__);
2504		m->m_pkthdr.PH_vt.vt_nrecs = 1;
2505		_IF_ENQUEUE(ifq, m);
2506	} else
2507		m->m_pkthdr.PH_vt.vt_nrecs++;
2508
2509	/*
2510	 * No further work needed if no source list in packet(s).
2511	 */
2512	if (!record_has_sources)
2513		return (nbytes);
2514
2515	/*
2516	 * Whilst sources remain to be announced, we need to allocate
2517	 * a new packet and fill out as many sources as will fit.
2518	 * Always try for a cluster first.
2519	 */
2520	while (nims != NULL) {
2521		if (_IF_QFULL(ifq)) {
2522			CTR1(KTR_MLD, "%s: outbound queue full", __func__);
2523			return (-ENOMEM);
2524		}
2525		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2526		if (m == NULL)
2527			m = m_gethdr(M_DONTWAIT, MT_DATA);
2528		if (m == NULL)
2529			return (-ENOMEM);
2530		mld_save_context(m, ifp);
2531		md = m_getptr(m, 0, &off);
2532		pmr = (struct mldv2_record *)(mtod(md, uint8_t *) + off);
2533		CTR1(KTR_MLD, "%s: allocated next packet", __func__);
2534
2535		if (!m_append(m, sizeof(struct mldv2_record), (void *)&mr)) {
2536			if (m != m0)
2537				m_freem(m);
2538			CTR1(KTR_MLD, "%s: m_append() failed.", __func__);
2539			return (-ENOMEM);
2540		}
2541		m->m_pkthdr.PH_vt.vt_nrecs = 1;
2542		nbytes += sizeof(struct mldv2_record);
2543
2544		m0srcs = (ifp->if_mtu - MLD_MTUSPACE -
2545		    sizeof(struct mldv2_record)) / sizeof(struct in6_addr);
2546
2547		msrcs = 0;
2548		RB_FOREACH_FROM(ims, ip6_msource_tree, nims) {
2549			CTR2(KTR_MLD, "%s: visit node %s",
2550			    __func__, ip6_sprintf(ip6tbuf, &ims->im6s_addr));
2551			now = im6s_get_mode(inm, ims, 1);
2552			if ((now != mode) ||
2553			    (now == mode && mode == MCAST_UNDEFINED)) {
2554				CTR1(KTR_MLD, "%s: skip node", __func__);
2555				continue;
2556			}
2557			if (is_source_query && ims->im6s_stp == 0) {
2558				CTR1(KTR_MLD, "%s: skip unrecorded node",
2559				    __func__);
2560				continue;
2561			}
2562			CTR1(KTR_MLD, "%s: append node", __func__);
2563			if (!m_append(m, sizeof(struct in6_addr),
2564			    (void *)&ims->im6s_addr)) {
2565				if (m != m0)
2566					m_freem(m);
2567				CTR1(KTR_MLD, "%s: m_append() failed.",
2568				    __func__);
2569				return (-ENOMEM);
2570			}
2571			++msrcs;
2572			if (msrcs == m0srcs)
2573				break;
2574		}
2575		pmr->mr_numsrc = htons(msrcs);
2576		nbytes += (msrcs * sizeof(struct in6_addr));
2577
2578		CTR1(KTR_MLD, "%s: enqueueing next packet", __func__);
2579		_IF_ENQUEUE(ifq, m);
2580	}
2581
2582	return (nbytes);
2583}
2584
2585/*
2586 * Type used to mark record pass completion.
2587 * We exploit the fact we can cast to this easily from the
2588 * current filter modes on each ip_msource node.
2589 */
2590typedef enum {
2591	REC_NONE = 0x00,	/* MCAST_UNDEFINED */
2592	REC_ALLOW = 0x01,	/* MCAST_INCLUDE */
2593	REC_BLOCK = 0x02,	/* MCAST_EXCLUDE */
2594	REC_FULL = REC_ALLOW | REC_BLOCK
2595} rectype_t;
2596
2597/*
2598 * Enqueue an MLDv2 filter list change to the given output queue.
2599 *
2600 * Source list filter state is held in an RB-tree. When the filter list
2601 * for a group is changed without changing its mode, we need to compute
2602 * the deltas between T0 and T1 for each source in the filter set,
2603 * and enqueue the appropriate ALLOW_NEW/BLOCK_OLD records.
2604 *
2605 * As we may potentially queue two record types, and the entire R-B tree
2606 * needs to be walked at once, we break this out into its own function
2607 * so we can generate a tightly packed queue of packets.
2608 *
2609 * XXX This could be written to only use one tree walk, although that makes
2610 * serializing into the mbuf chains a bit harder. For now we do two walks
2611 * which makes things easier on us, and it may or may not be harder on
2612 * the L2 cache.
2613 *
2614 * If successful the size of all data appended to the queue is returned,
2615 * otherwise an error code less than zero is returned, or zero if
2616 * no record(s) were appended.
2617 */
2618static int
2619mld_v2_enqueue_filter_change(struct ifqueue *ifq, struct in6_multi *inm)
2620{
2621	static const int MINRECLEN =
2622	    sizeof(struct mldv2_record) + sizeof(struct in6_addr);
2623	struct ifnet		*ifp;
2624	struct mldv2_record	 mr;
2625	struct mldv2_record	*pmr;
2626	struct ip6_msource	*ims, *nims;
2627	struct mbuf		*m, *m0, *md;
2628	int			 m0srcs, nbytes, npbytes, off, rsrcs, schanged;
2629	int			 nallow, nblock;
2630	uint8_t			 mode, now, then;
2631	rectype_t		 crt, drt, nrt;
2632#ifdef KTR
2633	char			 ip6tbuf[INET6_ADDRSTRLEN];
2634#endif
2635
2636	IN6_MULTI_LOCK_ASSERT();
2637
2638	if (inm->in6m_nsrc == 0 ||
2639	    (inm->in6m_st[0].iss_asm > 0 && inm->in6m_st[1].iss_asm > 0))
2640		return (0);
2641
2642	ifp = inm->in6m_ifp;			/* interface */
2643	mode = inm->in6m_st[1].iss_fmode;	/* filter mode at t1 */
2644	crt = REC_NONE;	/* current group record type */
2645	drt = REC_NONE;	/* mask of completed group record types */
2646	nrt = REC_NONE;	/* record type for current node */
2647	m0srcs = 0;	/* # source which will fit in current mbuf chain */
2648	npbytes = 0;	/* # of bytes appended this packet */
2649	nbytes = 0;	/* # of bytes appended to group's state-change queue */
2650	rsrcs = 0;	/* # sources encoded in current record */
2651	schanged = 0;	/* # nodes encoded in overall filter change */
2652	nallow = 0;	/* # of source entries in ALLOW_NEW */
2653	nblock = 0;	/* # of source entries in BLOCK_OLD */
2654	nims = NULL;	/* next tree node pointer */
2655
2656	/*
2657	 * For each possible filter record mode.
2658	 * The first kind of source we encounter tells us which
2659	 * is the first kind of record we start appending.
2660	 * If a node transitioned to UNDEFINED at t1, its mode is treated
2661	 * as the inverse of the group's filter mode.
2662	 */
2663	while (drt != REC_FULL) {
2664		do {
2665			m0 = ifq->ifq_tail;
2666			if (m0 != NULL &&
2667			    (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <=
2668			     MLD_V2_REPORT_MAXRECS) &&
2669			    (m0->m_pkthdr.len + MINRECLEN) <
2670			     (ifp->if_mtu - MLD_MTUSPACE)) {
2671				m = m0;
2672				m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
2673					    sizeof(struct mldv2_record)) /
2674					    sizeof(struct in6_addr);
2675				CTR1(KTR_MLD,
2676				    "%s: use previous packet", __func__);
2677			} else {
2678				m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2679				if (m == NULL)
2680					m = m_gethdr(M_DONTWAIT, MT_DATA);
2681				if (m == NULL) {
2682					CTR1(KTR_MLD,
2683					    "%s: m_get*() failed", __func__);
2684					return (-ENOMEM);
2685				}
2686				m->m_pkthdr.PH_vt.vt_nrecs = 0;
2687				mld_save_context(m, ifp);
2688				m0srcs = (ifp->if_mtu - MLD_MTUSPACE -
2689				    sizeof(struct mldv2_record)) /
2690				    sizeof(struct in6_addr);
2691				npbytes = 0;
2692				CTR1(KTR_MLD,
2693				    "%s: allocated new packet", __func__);
2694			}
2695			/*
2696			 * Append the MLD group record header to the
2697			 * current packet's data area.
2698			 * Recalculate pointer to free space for next
2699			 * group record, in case m_append() allocated
2700			 * a new mbuf or cluster.
2701			 */
2702			memset(&mr, 0, sizeof(mr));
2703			mr.mr_addr = inm->in6m_addr;
2704			in6_clearscope(&mr.mr_addr);
2705			if (!m_append(m, sizeof(mr), (void *)&mr)) {
2706				if (m != m0)
2707					m_freem(m);
2708				CTR1(KTR_MLD,
2709				    "%s: m_append() failed", __func__);
2710				return (-ENOMEM);
2711			}
2712			npbytes += sizeof(struct mldv2_record);
2713			if (m != m0) {
2714				/* new packet; offset in chain */
2715				md = m_getptr(m, npbytes -
2716				    sizeof(struct mldv2_record), &off);
2717				pmr = (struct mldv2_record *)(mtod(md,
2718				    uint8_t *) + off);
2719			} else {
2720				/* current packet; offset from last append */
2721				md = m_last(m);
2722				pmr = (struct mldv2_record *)(mtod(md,
2723				    uint8_t *) + md->m_len -
2724				    sizeof(struct mldv2_record));
2725			}
2726			/*
2727			 * Begin walking the tree for this record type
2728			 * pass, or continue from where we left off
2729			 * previously if we had to allocate a new packet.
2730			 * Only report deltas in-mode at t1.
2731			 * We need not report included sources as allowed
2732			 * if we are in inclusive mode on the group,
2733			 * however the converse is not true.
2734			 */
2735			rsrcs = 0;
2736			if (nims == NULL) {
2737				nims = RB_MIN(ip6_msource_tree,
2738				    &inm->in6m_srcs);
2739			}
2740			RB_FOREACH_FROM(ims, ip6_msource_tree, nims) {
2741				CTR2(KTR_MLD, "%s: visit node %s", __func__,
2742				    ip6_sprintf(ip6tbuf, &ims->im6s_addr));
2743				now = im6s_get_mode(inm, ims, 1);
2744				then = im6s_get_mode(inm, ims, 0);
2745				CTR3(KTR_MLD, "%s: mode: t0 %d, t1 %d",
2746				    __func__, then, now);
2747				if (now == then) {
2748					CTR1(KTR_MLD,
2749					    "%s: skip unchanged", __func__);
2750					continue;
2751				}
2752				if (mode == MCAST_EXCLUDE &&
2753				    now == MCAST_INCLUDE) {
2754					CTR1(KTR_MLD,
2755					    "%s: skip IN src on EX group",
2756					    __func__);
2757					continue;
2758				}
2759				nrt = (rectype_t)now;
2760				if (nrt == REC_NONE)
2761					nrt = (rectype_t)(~mode & REC_FULL);
2762				if (schanged++ == 0) {
2763					crt = nrt;
2764				} else if (crt != nrt)
2765					continue;
2766				if (!m_append(m, sizeof(struct in6_addr),
2767				    (void *)&ims->im6s_addr)) {
2768					if (m != m0)
2769						m_freem(m);
2770					CTR1(KTR_MLD,
2771					    "%s: m_append() failed", __func__);
2772					return (-ENOMEM);
2773				}
2774				nallow += !!(crt == REC_ALLOW);
2775				nblock += !!(crt == REC_BLOCK);
2776				if (++rsrcs == m0srcs)
2777					break;
2778			}
2779			/*
2780			 * If we did not append any tree nodes on this
2781			 * pass, back out of allocations.
2782			 */
2783			if (rsrcs == 0) {
2784				npbytes -= sizeof(struct mldv2_record);
2785				if (m != m0) {
2786					CTR1(KTR_MLD,
2787					    "%s: m_free(m)", __func__);
2788					m_freem(m);
2789				} else {
2790					CTR1(KTR_MLD,
2791					    "%s: m_adj(m, -mr)", __func__);
2792					m_adj(m, -((int)sizeof(
2793					    struct mldv2_record)));
2794				}
2795				continue;
2796			}
2797			npbytes += (rsrcs * sizeof(struct in6_addr));
2798			if (crt == REC_ALLOW)
2799				pmr->mr_type = MLD_ALLOW_NEW_SOURCES;
2800			else if (crt == REC_BLOCK)
2801				pmr->mr_type = MLD_BLOCK_OLD_SOURCES;
2802			pmr->mr_numsrc = htons(rsrcs);
2803			/*
2804			 * Count the new group record, and enqueue this
2805			 * packet if it wasn't already queued.
2806			 */
2807			m->m_pkthdr.PH_vt.vt_nrecs++;
2808			if (m != m0)
2809				_IF_ENQUEUE(ifq, m);
2810			nbytes += npbytes;
2811		} while (nims != NULL);
2812		drt |= crt;
2813		crt = (~crt & REC_FULL);
2814	}
2815
2816	CTR3(KTR_MLD, "%s: queued %d ALLOW_NEW, %d BLOCK_OLD", __func__,
2817	    nallow, nblock);
2818
2819	return (nbytes);
2820}
2821
2822static int
2823mld_v2_merge_state_changes(struct in6_multi *inm, struct ifqueue *ifscq)
2824{
2825	struct ifqueue	*gq;
2826	struct mbuf	*m;		/* pending state-change */
2827	struct mbuf	*m0;		/* copy of pending state-change */
2828	struct mbuf	*mt;		/* last state-change in packet */
2829	int		 docopy, domerge;
2830	u_int		 recslen;
2831
2832	docopy = 0;
2833	domerge = 0;
2834	recslen = 0;
2835
2836	IN6_MULTI_LOCK_ASSERT();
2837	MLD_LOCK_ASSERT();
2838
2839	/*
2840	 * If there are further pending retransmissions, make a writable
2841	 * copy of each queued state-change message before merging.
2842	 */
2843	if (inm->in6m_scrv > 0)
2844		docopy = 1;
2845
2846	gq = &inm->in6m_scq;
2847#ifdef KTR
2848	if (gq->ifq_head == NULL) {
2849		CTR2(KTR_MLD, "%s: WARNING: queue for inm %p is empty",
2850		    __func__, inm);
2851	}
2852#endif
2853
2854	m = gq->ifq_head;
2855	while (m != NULL) {
2856		/*
2857		 * Only merge the report into the current packet if
2858		 * there is sufficient space to do so; an MLDv2 report
2859		 * packet may only contain 65,535 group records.
2860		 * Always use a simple mbuf chain concatentation to do this,
2861		 * as large state changes for single groups may have
2862		 * allocated clusters.
2863		 */
2864		domerge = 0;
2865		mt = ifscq->ifq_tail;
2866		if (mt != NULL) {
2867			recslen = m_length(m, NULL);
2868
2869			if ((mt->m_pkthdr.PH_vt.vt_nrecs +
2870			    m->m_pkthdr.PH_vt.vt_nrecs <=
2871			    MLD_V2_REPORT_MAXRECS) &&
2872			    (mt->m_pkthdr.len + recslen <=
2873			    (inm->in6m_ifp->if_mtu - MLD_MTUSPACE)))
2874				domerge = 1;
2875		}
2876
2877		if (!domerge && _IF_QFULL(gq)) {
2878			CTR2(KTR_MLD,
2879			    "%s: outbound queue full, skipping whole packet %p",
2880			    __func__, m);
2881			mt = m->m_nextpkt;
2882			if (!docopy)
2883				m_freem(m);
2884			m = mt;
2885			continue;
2886		}
2887
2888		if (!docopy) {
2889			CTR2(KTR_MLD, "%s: dequeueing %p", __func__, m);
2890			_IF_DEQUEUE(gq, m0);
2891			m = m0->m_nextpkt;
2892		} else {
2893			CTR2(KTR_MLD, "%s: copying %p", __func__, m);
2894			m0 = m_dup(m, M_NOWAIT);
2895			if (m0 == NULL)
2896				return (ENOMEM);
2897			m0->m_nextpkt = NULL;
2898			m = m->m_nextpkt;
2899		}
2900
2901		if (!domerge) {
2902			CTR3(KTR_MLD, "%s: queueing %p to ifscq %p)",
2903			    __func__, m0, ifscq);
2904			_IF_ENQUEUE(ifscq, m0);
2905		} else {
2906			struct mbuf *mtl;	/* last mbuf of packet mt */
2907
2908			CTR3(KTR_MLD, "%s: merging %p with ifscq tail %p)",
2909			    __func__, m0, mt);
2910
2911			mtl = m_last(mt);
2912			m0->m_flags &= ~M_PKTHDR;
2913			mt->m_pkthdr.len += recslen;
2914			mt->m_pkthdr.PH_vt.vt_nrecs +=
2915			    m0->m_pkthdr.PH_vt.vt_nrecs;
2916
2917			mtl->m_next = m0;
2918		}
2919	}
2920
2921	return (0);
2922}
2923
2924/*
2925 * Respond to a pending MLDv2 General Query.
2926 */
2927static void
2928mld_v2_dispatch_general_query(struct mld_ifinfo *mli)
2929{
2930	struct ifmultiaddr	*ifma, *tifma;
2931	struct ifnet		*ifp;
2932	struct in6_multi	*inm;
2933	int			 retval;
2934
2935	IN6_MULTI_LOCK_ASSERT();
2936	MLD_LOCK_ASSERT();
2937
2938	KASSERT(mli->mli_version == MLD_VERSION_2,
2939	    ("%s: called when version %d", __func__, mli->mli_version));
2940
2941	ifp = mli->mli_ifp;
2942
2943	IF_ADDR_LOCK(ifp);
2944	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, tifma) {
2945		if (ifma->ifma_addr->sa_family != AF_INET6 ||
2946		    ifma->ifma_protospec == NULL)
2947			continue;
2948
2949		inm = (struct in6_multi *)ifma->ifma_protospec;
2950		KASSERT(ifp == inm->in6m_ifp,
2951		    ("%s: inconsistent ifp", __func__));
2952
2953		switch (inm->in6m_state) {
2954		case MLD_NOT_MEMBER:
2955		case MLD_SILENT_MEMBER:
2956			break;
2957		case MLD_REPORTING_MEMBER:
2958		case MLD_IDLE_MEMBER:
2959		case MLD_LAZY_MEMBER:
2960		case MLD_SLEEPING_MEMBER:
2961		case MLD_AWAKENING_MEMBER:
2962			inm->in6m_state = MLD_REPORTING_MEMBER;
2963			retval = mld_v2_enqueue_group_record(&mli->mli_gq,
2964			    inm, 0, 0, 0);
2965			CTR2(KTR_MLD, "%s: enqueue record = %d",
2966			    __func__, retval);
2967			break;
2968		case MLD_G_QUERY_PENDING_MEMBER:
2969		case MLD_SG_QUERY_PENDING_MEMBER:
2970		case MLD_LEAVING_MEMBER:
2971			break;
2972		}
2973	}
2974	IF_ADDR_UNLOCK(ifp);
2975
2976	mld_dispatch_queue(&mli->mli_gq, MLD_MAX_RESPONSE_BURST);
2977
2978	/*
2979	 * Slew transmission of bursts over 500ms intervals.
2980	 */
2981	if (mli->mli_gq.ifq_head != NULL) {
2982		mli->mli_v2_timer = 1 + MLD_RANDOM_DELAY(
2983		    MLD_RESPONSE_BURST_INTERVAL);
2984		V_interface_timers_running6 = 1;
2985	}
2986}
2987
2988/*
2989 * Transmit the next pending message in the output queue.
2990 *
2991 * VIMAGE: Needs to store/restore vnet pointer on a per-mbuf-chain basis.
2992 * MRT: Nothing needs to be done, as MLD traffic is always local to
2993 * a link and uses a link-scope multicast address.
2994 */
2995static void
2996mld_dispatch_packet(struct mbuf *m)
2997{
2998	struct ip6_moptions	 im6o;
2999	struct ifnet		*ifp;
3000	struct ifnet		*oifp;
3001	struct mbuf		*m0;
3002	struct mbuf		*md;
3003	struct ip6_hdr		*ip6;
3004	struct mld_hdr		*mld;
3005	int			 error;
3006	int			 off;
3007	int			 type;
3008	uint32_t		 ifindex;
3009
3010	CTR2(KTR_MLD, "%s: transmit %p", __func__, m);
3011
3012	/*
3013	 * Set VNET image pointer from enqueued mbuf chain
3014	 * before doing anything else. Whilst we use interface
3015	 * indexes to guard against interface detach, they are
3016	 * unique to each VIMAGE and must be retrieved.
3017	 */
3018	ifindex = mld_restore_context(m);
3019
3020	/*
3021	 * Check if the ifnet still exists. This limits the scope of
3022	 * any race in the absence of a global ifp lock for low cost
3023	 * (an array lookup).
3024	 */
3025	ifp = ifnet_byindex(ifindex);
3026	if (ifp == NULL) {
3027		CTR3(KTR_MLD, "%s: dropped %p as ifindex %u went away.",
3028		    __func__, m, ifindex);
3029		m_freem(m);
3030		IP6STAT_INC(ip6s_noroute);
3031		goto out;
3032	}
3033
3034	im6o.im6o_multicast_hlim  = 1;
3035	im6o.im6o_multicast_loop = (V_ip6_mrouter != NULL);
3036	im6o.im6o_multicast_ifp = ifp;
3037
3038	if (m->m_flags & M_MLDV1) {
3039		m0 = m;
3040	} else {
3041		m0 = mld_v2_encap_report(ifp, m);
3042		if (m0 == NULL) {
3043			CTR2(KTR_MLD, "%s: dropped %p", __func__, m);
3044			m_freem(m);
3045			IP6STAT_INC(ip6s_odropped);
3046			goto out;
3047		}
3048	}
3049
3050	mld_scrub_context(m0);
3051	m->m_flags &= ~(M_PROTOFLAGS);
3052	m0->m_pkthdr.rcvif = V_loif;
3053
3054	ip6 = mtod(m0, struct ip6_hdr *);
3055#if 0
3056	(void)in6_setscope(&ip6->ip6_dst, ifp, NULL);	/* XXX LOR */
3057#else
3058	/*
3059	 * XXX XXX Break some KPI rules to prevent an LOR which would
3060	 * occur if we called in6_setscope() at transmission.
3061	 * See comments at top of file.
3062	 */
3063	MLD_EMBEDSCOPE(&ip6->ip6_dst, ifp->if_index);
3064#endif
3065
3066	/*
3067	 * Retrieve the ICMPv6 type before handoff to ip6_output(),
3068	 * so we can bump the stats.
3069	 */
3070	md = m_getptr(m0, sizeof(struct ip6_hdr), &off);
3071	mld = (struct mld_hdr *)(mtod(md, uint8_t *) + off);
3072	type = mld->mld_type;
3073
3074	error = ip6_output(m0, &mld_po, NULL, IPV6_UNSPECSRC, &im6o,
3075	    &oifp, NULL);
3076	if (error) {
3077		CTR3(KTR_MLD, "%s: ip6_output(%p) = %d", __func__, m0, error);
3078		goto out;
3079	}
3080	ICMP6STAT_INC(icp6s_outhist[type]);
3081	if (oifp != NULL) {
3082		icmp6_ifstat_inc(oifp, ifs6_out_msg);
3083		switch (type) {
3084		case MLD_LISTENER_REPORT:
3085		case MLDV2_LISTENER_REPORT:
3086			icmp6_ifstat_inc(oifp, ifs6_out_mldreport);
3087			break;
3088		case MLD_LISTENER_DONE:
3089			icmp6_ifstat_inc(oifp, ifs6_out_mlddone);
3090			break;
3091		}
3092	}
3093out:
3094	return;
3095}
3096
3097/*
3098 * Encapsulate an MLDv2 report.
3099 *
3100 * KAME IPv6 requires that hop-by-hop options be passed separately,
3101 * and that the IPv6 header be prepended in a separate mbuf.
3102 *
3103 * Returns a pointer to the new mbuf chain head, or NULL if the
3104 * allocation failed.
3105 */
3106static struct mbuf *
3107mld_v2_encap_report(struct ifnet *ifp, struct mbuf *m)
3108{
3109	struct mbuf		*mh;
3110	struct mldv2_report	*mld;
3111	struct ip6_hdr		*ip6;
3112	struct in6_ifaddr	*ia;
3113	int			 mldreclen;
3114
3115	KASSERT(ifp != NULL, ("%s: null ifp", __func__));
3116	KASSERT((m->m_flags & M_PKTHDR),
3117	    ("%s: mbuf chain %p is !M_PKTHDR", __func__, m));
3118
3119	/*
3120	 * RFC3590: OK to send as :: or tentative during DAD.
3121	 */
3122	ia = in6ifa_ifpforlinklocal(ifp, IN6_IFF_NOTREADY|IN6_IFF_ANYCAST);
3123	if (ia == NULL)
3124		CTR1(KTR_MLD, "%s: warning: ia is NULL", __func__);
3125
3126	MGETHDR(mh, M_DONTWAIT, MT_HEADER);
3127	if (mh == NULL) {
3128		if (ia != NULL)
3129			ifa_free(&ia->ia_ifa);
3130		m_freem(m);
3131		return (NULL);
3132	}
3133	MH_ALIGN(mh, sizeof(struct ip6_hdr) + sizeof(struct mldv2_report));
3134
3135	mldreclen = m_length(m, NULL);
3136	CTR2(KTR_MLD, "%s: mldreclen is %d", __func__, mldreclen);
3137
3138	mh->m_len = sizeof(struct ip6_hdr) + sizeof(struct mldv2_report);
3139	mh->m_pkthdr.len = sizeof(struct ip6_hdr) +
3140	    sizeof(struct mldv2_report) + mldreclen;
3141
3142	ip6 = mtod(mh, struct ip6_hdr *);
3143	ip6->ip6_flow = 0;
3144	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
3145	ip6->ip6_vfc |= IPV6_VERSION;
3146	ip6->ip6_nxt = IPPROTO_ICMPV6;
3147	ip6->ip6_src = ia ? ia->ia_addr.sin6_addr : in6addr_any;
3148	if (ia != NULL)
3149		ifa_free(&ia->ia_ifa);
3150	ip6->ip6_dst = in6addr_linklocal_allv2routers;
3151	/* scope ID will be set in netisr */
3152
3153	mld = (struct mldv2_report *)(ip6 + 1);
3154	mld->mld_type = MLDV2_LISTENER_REPORT;
3155	mld->mld_code = 0;
3156	mld->mld_cksum = 0;
3157	mld->mld_v2_reserved = 0;
3158	mld->mld_v2_numrecs = htons(m->m_pkthdr.PH_vt.vt_nrecs);
3159	m->m_pkthdr.PH_vt.vt_nrecs = 0;
3160
3161	mh->m_next = m;
3162	mld->mld_cksum = in6_cksum(mh, IPPROTO_ICMPV6,
3163	    sizeof(struct ip6_hdr), sizeof(struct mldv2_report) + mldreclen);
3164	return (mh);
3165}
3166
3167#ifdef KTR
3168static char *
3169mld_rec_type_to_str(const int type)
3170{
3171
3172	switch (type) {
3173		case MLD_CHANGE_TO_EXCLUDE_MODE:
3174			return "TO_EX";
3175			break;
3176		case MLD_CHANGE_TO_INCLUDE_MODE:
3177			return "TO_IN";
3178			break;
3179		case MLD_MODE_IS_EXCLUDE:
3180			return "MODE_EX";
3181			break;
3182		case MLD_MODE_IS_INCLUDE:
3183			return "MODE_IN";
3184			break;
3185		case MLD_ALLOW_NEW_SOURCES:
3186			return "ALLOW_NEW";
3187			break;
3188		case MLD_BLOCK_OLD_SOURCES:
3189			return "BLOCK_OLD";
3190			break;
3191		default:
3192			break;
3193	}
3194	return "unknown";
3195}
3196#endif
3197
3198static void
3199mld_init(void *unused __unused)
3200{
3201
3202	CTR1(KTR_MLD, "%s: initializing", __func__);
3203	MLD_LOCK_INIT();
3204
3205	ip6_initpktopts(&mld_po);
3206	mld_po.ip6po_hlim = 1;
3207	mld_po.ip6po_hbh = &mld_ra.hbh;
3208	mld_po.ip6po_prefer_tempaddr = IP6PO_TEMPADDR_NOTPREFER;
3209	mld_po.ip6po_flags = IP6PO_DONTFRAG;
3210}
3211SYSINIT(mld_init, SI_SUB_PSEUDO, SI_ORDER_MIDDLE, mld_init, NULL);
3212
3213static void
3214mld_uninit(void *unused __unused)
3215{
3216
3217	CTR1(KTR_MLD, "%s: tearing down", __func__);
3218	MLD_LOCK_DESTROY();
3219}
3220SYSUNINIT(mld_uninit, SI_SUB_PSEUDO, SI_ORDER_MIDDLE, mld_uninit, NULL);
3221
3222static void
3223vnet_mld_init(const void *unused __unused)
3224{
3225
3226	CTR1(KTR_MLD, "%s: initializing", __func__);
3227
3228	LIST_INIT(&V_mli_head);
3229}
3230VNET_SYSINIT(vnet_mld_init, SI_SUB_PSEUDO, SI_ORDER_ANY, vnet_mld_init,
3231    NULL);
3232
3233static void
3234vnet_mld_uninit(const void *unused __unused)
3235{
3236
3237	CTR1(KTR_MLD, "%s: tearing down", __func__);
3238
3239	KASSERT(LIST_EMPTY(&V_mli_head),
3240	    ("%s: mli list not empty; ifnets not detached?", __func__));
3241}
3242VNET_SYSUNINIT(vnet_mld_uninit, SI_SUB_PSEUDO, SI_ORDER_ANY, vnet_mld_uninit,
3243    NULL);
3244
3245static int
3246mld_modevent(module_t mod, int type, void *unused __unused)
3247{
3248
3249    switch (type) {
3250    case MOD_LOAD:
3251    case MOD_UNLOAD:
3252	break;
3253    default:
3254	return (EOPNOTSUPP);
3255    }
3256    return (0);
3257}
3258
3259static moduledata_t mld_mod = {
3260    "mld",
3261    mld_modevent,
3262    0
3263};
3264DECLARE_MODULE(mld, mld_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
3265