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