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