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