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