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