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