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