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