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