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