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