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