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