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