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