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