]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/mld6.c
cdn-patch: offer option to mount /etc/keys before attaching geli devices
[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 *m, int off, int icmp6len)
1256 {
1257         struct ifnet    *ifp;
1258         struct ip6_hdr  *ip6;
1259         struct mld_hdr  *mld;
1260         int              mldlen;
1261
1262         CTR3(KTR_MLD, "%s: called w/mbuf (%p,%d)", __func__, m, off);
1263
1264         ifp = m->m_pkthdr.rcvif;
1265
1266         ip6 = mtod(m, struct ip6_hdr *);
1267
1268         /* Pullup to appropriate size. */
1269         mld = (struct mld_hdr *)(mtod(m, uint8_t *) + off);
1270         if (mld->mld_type == MLD_LISTENER_QUERY &&
1271             icmp6len >= sizeof(struct mldv2_query)) {
1272                 mldlen = sizeof(struct mldv2_query);
1273         } else {
1274                 mldlen = sizeof(struct mld_hdr);
1275         }
1276         IP6_EXTHDR_GET(mld, struct mld_hdr *, m, off, mldlen);
1277         if (mld == NULL) {
1278                 ICMP6STAT_INC(icp6s_badlen);
1279                 return (IPPROTO_DONE);
1280         }
1281
1282         /*
1283          * Userland needs to see all of this traffic for implementing
1284          * the endpoint discovery portion of multicast routing.
1285          */
1286         switch (mld->mld_type) {
1287         case MLD_LISTENER_QUERY:
1288                 icmp6_ifstat_inc(ifp, ifs6_in_mldquery);
1289                 if (icmp6len == sizeof(struct mld_hdr)) {
1290                         if (mld_v1_input_query(ifp, ip6, mld) != 0)
1291                                 return (0);
1292                 } else if (icmp6len >= sizeof(struct mldv2_query)) {
1293                         if (mld_v2_input_query(ifp, ip6, m,
1294                             (struct mldv2_query *)mld, off, icmp6len) != 0)
1295                                 return (0);
1296                 }
1297                 break;
1298         case MLD_LISTENER_REPORT:
1299                 icmp6_ifstat_inc(ifp, ifs6_in_mldreport);
1300                 if (mld_v1_input_report(ifp, ip6, mld) != 0)
1301                         return (0);
1302                 break;
1303         case MLDV2_LISTENER_REPORT:
1304                 icmp6_ifstat_inc(ifp, ifs6_in_mldreport);
1305                 break;
1306         case MLD_LISTENER_DONE:
1307                 icmp6_ifstat_inc(ifp, ifs6_in_mlddone);
1308                 break;
1309         default:
1310                 break;
1311         }
1312
1313         return (0);
1314 }
1315
1316 /*
1317  * Fast timeout handler (global).
1318  * VIMAGE: Timeout handlers are expected to service all vimages.
1319  */
1320 void
1321 mld_fasttimo(void)
1322 {
1323         struct in6_multi_head inmh;
1324         VNET_ITERATOR_DECL(vnet_iter);
1325
1326         SLIST_INIT(&inmh);
1327         
1328         VNET_LIST_RLOCK_NOSLEEP();
1329         VNET_FOREACH(vnet_iter) {
1330                 CURVNET_SET(vnet_iter);
1331                 mld_fasttimo_vnet(&inmh);
1332                 CURVNET_RESTORE();
1333         }
1334         VNET_LIST_RUNLOCK_NOSLEEP();
1335         in6m_release_list_deferred(&inmh);
1336 }
1337
1338 /*
1339  * Fast timeout handler (per-vnet).
1340  *
1341  * VIMAGE: Assume caller has set up our curvnet.
1342  */
1343 static void
1344 mld_fasttimo_vnet(struct in6_multi_head *inmh)
1345 {
1346         struct epoch_tracker     et;
1347         struct mbufq             scq;   /* State-change packets */
1348         struct mbufq             qrq;   /* Query response packets */
1349         struct ifnet            *ifp;
1350         struct mld_ifsoftc      *mli;
1351         struct ifmultiaddr      *ifma;
1352         struct in6_multi        *inm;
1353         int                      uri_fasthz;
1354
1355         uri_fasthz = 0;
1356
1357         /*
1358          * Quick check to see if any work needs to be done, in order to
1359          * minimize the overhead of fasttimo processing.
1360          * SMPng: XXX Unlocked reads.
1361          */
1362         if (!V_current_state_timers_running6 &&
1363             !V_interface_timers_running6 &&
1364             !V_state_change_timers_running6)
1365                 return;
1366
1367         IN6_MULTI_LIST_LOCK();
1368         MLD_LOCK();
1369
1370         /*
1371          * MLDv2 General Query response timer processing.
1372          */
1373         if (V_interface_timers_running6) {
1374                 CTR1(KTR_MLD, "%s: interface timers running", __func__);
1375
1376                 V_interface_timers_running6 = 0;
1377                 LIST_FOREACH(mli, &V_mli_head, mli_link) {
1378                         if (mli->mli_v2_timer == 0) {
1379                                 /* Do nothing. */
1380                         } else if (--mli->mli_v2_timer == 0) {
1381                                 mld_v2_dispatch_general_query(mli);
1382                         } else {
1383                                 V_interface_timers_running6 = 1;
1384                         }
1385                 }
1386         }
1387
1388         if (!V_current_state_timers_running6 &&
1389             !V_state_change_timers_running6)
1390                 goto out_locked;
1391
1392         V_current_state_timers_running6 = 0;
1393         V_state_change_timers_running6 = 0;
1394
1395         CTR1(KTR_MLD, "%s: state change timers running", __func__);
1396
1397         /*
1398          * MLD host report and state-change timer processing.
1399          * Note: Processing a v2 group timer may remove a node.
1400          */
1401         LIST_FOREACH(mli, &V_mli_head, mli_link) {
1402                 ifp = mli->mli_ifp;
1403
1404                 if (mli->mli_version == MLD_VERSION_2) {
1405                         uri_fasthz = MLD_RANDOM_DELAY(mli->mli_uri *
1406                             PR_FASTHZ);
1407                         mbufq_init(&qrq, MLD_MAX_G_GS_PACKETS);
1408                         mbufq_init(&scq, MLD_MAX_STATE_CHANGE_PACKETS);
1409                 }
1410
1411                 IF_ADDR_WLOCK(ifp);
1412                 NET_EPOCH_ENTER_ET(et);
1413                 CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1414                         inm = in6m_ifmultiaddr_get_inm(ifma);
1415                         if (inm == NULL)
1416                                 continue;
1417                         switch (mli->mli_version) {
1418                         case MLD_VERSION_1:
1419                                 mld_v1_process_group_timer(inmh, inm);
1420                                 break;
1421                         case MLD_VERSION_2:
1422                                 mld_v2_process_group_timers(inmh, &qrq,
1423                                     &scq, inm, uri_fasthz);
1424                                 break;
1425                         }
1426                 }
1427                 IF_ADDR_WUNLOCK(ifp);
1428
1429                 switch (mli->mli_version) {
1430                 case MLD_VERSION_1:
1431                         /*
1432                          * Transmit reports for this lifecycle.  This
1433                          * is done while not holding IF_ADDR_LOCK
1434                          * since this can call
1435                          * in6ifa_ifpforlinklocal() which locks
1436                          * IF_ADDR_LOCK internally as well as
1437                          * ip6_output() to transmit a packet.
1438                          */
1439                         while ((inm = SLIST_FIRST(inmh)) != NULL) {
1440                                 SLIST_REMOVE_HEAD(inmh, in6m_defer);
1441                                 (void)mld_v1_transmit_report(inm,
1442                                     MLD_LISTENER_REPORT);
1443                         }
1444                         break;
1445                 case MLD_VERSION_2:
1446                         mld_dispatch_queue(&qrq, 0);
1447                         mld_dispatch_queue(&scq, 0);
1448                         break;
1449                 }
1450                 NET_EPOCH_EXIT_ET(et);
1451         }
1452
1453 out_locked:
1454         MLD_UNLOCK();
1455         IN6_MULTI_LIST_UNLOCK();
1456 }
1457
1458 /*
1459  * Update host report group timer.
1460  * Will update the global pending timer flags.
1461  */
1462 static void
1463 mld_v1_process_group_timer(struct in6_multi_head *inmh, struct in6_multi *inm)
1464 {
1465         int report_timer_expired;
1466
1467         IN6_MULTI_LIST_LOCK_ASSERT();
1468         MLD_LOCK_ASSERT();
1469
1470         if (inm->in6m_timer == 0) {
1471                 report_timer_expired = 0;
1472         } else if (--inm->in6m_timer == 0) {
1473                 report_timer_expired = 1;
1474         } else {
1475                 V_current_state_timers_running6 = 1;
1476                 return;
1477         }
1478
1479         switch (inm->in6m_state) {
1480         case MLD_NOT_MEMBER:
1481         case MLD_SILENT_MEMBER:
1482         case MLD_IDLE_MEMBER:
1483         case MLD_LAZY_MEMBER:
1484         case MLD_SLEEPING_MEMBER:
1485         case MLD_AWAKENING_MEMBER:
1486                 break;
1487         case MLD_REPORTING_MEMBER:
1488                 if (report_timer_expired) {
1489                         inm->in6m_state = MLD_IDLE_MEMBER;
1490                         SLIST_INSERT_HEAD(inmh, inm, in6m_defer);
1491                 }
1492                 break;
1493         case MLD_G_QUERY_PENDING_MEMBER:
1494         case MLD_SG_QUERY_PENDING_MEMBER:
1495         case MLD_LEAVING_MEMBER:
1496                 break;
1497         }
1498 }
1499
1500 /*
1501  * Update a group's timers for MLDv2.
1502  * Will update the global pending timer flags.
1503  * Note: Unlocked read from mli.
1504  */
1505 static void
1506 mld_v2_process_group_timers(struct in6_multi_head *inmh,
1507     struct mbufq *qrq, struct mbufq *scq,
1508     struct in6_multi *inm, const int uri_fasthz)
1509 {
1510         int query_response_timer_expired;
1511         int state_change_retransmit_timer_expired;
1512 #ifdef KTR
1513         char ip6tbuf[INET6_ADDRSTRLEN];
1514 #endif
1515
1516         IN6_MULTI_LIST_LOCK_ASSERT();
1517         MLD_LOCK_ASSERT();
1518
1519         query_response_timer_expired = 0;
1520         state_change_retransmit_timer_expired = 0;
1521
1522         /*
1523          * During a transition from compatibility mode back to MLDv2,
1524          * a group record in REPORTING state may still have its group
1525          * timer active. This is a no-op in this function; it is easier
1526          * to deal with it here than to complicate the slow-timeout path.
1527          */
1528         if (inm->in6m_timer == 0) {
1529                 query_response_timer_expired = 0;
1530         } else if (--inm->in6m_timer == 0) {
1531                 query_response_timer_expired = 1;
1532         } else {
1533                 V_current_state_timers_running6 = 1;
1534         }
1535
1536         if (inm->in6m_sctimer == 0) {
1537                 state_change_retransmit_timer_expired = 0;
1538         } else if (--inm->in6m_sctimer == 0) {
1539                 state_change_retransmit_timer_expired = 1;
1540         } else {
1541                 V_state_change_timers_running6 = 1;
1542         }
1543
1544         /* We are in fasttimo, so be quick about it. */
1545         if (!state_change_retransmit_timer_expired &&
1546             !query_response_timer_expired)
1547                 return;
1548
1549         switch (inm->in6m_state) {
1550         case MLD_NOT_MEMBER:
1551         case MLD_SILENT_MEMBER:
1552         case MLD_SLEEPING_MEMBER:
1553         case MLD_LAZY_MEMBER:
1554         case MLD_AWAKENING_MEMBER:
1555         case MLD_IDLE_MEMBER:
1556                 break;
1557         case MLD_G_QUERY_PENDING_MEMBER:
1558         case MLD_SG_QUERY_PENDING_MEMBER:
1559                 /*
1560                  * Respond to a previously pending Group-Specific
1561                  * or Group-and-Source-Specific query by enqueueing
1562                  * the appropriate Current-State report for
1563                  * immediate transmission.
1564                  */
1565                 if (query_response_timer_expired) {
1566                         int retval;
1567
1568                         retval = mld_v2_enqueue_group_record(qrq, inm, 0, 1,
1569                             (inm->in6m_state == MLD_SG_QUERY_PENDING_MEMBER),
1570                             0);
1571                         CTR2(KTR_MLD, "%s: enqueue record = %d",
1572                             __func__, retval);
1573                         inm->in6m_state = MLD_REPORTING_MEMBER;
1574                         in6m_clear_recorded(inm);
1575                 }
1576                 /* FALLTHROUGH */
1577         case MLD_REPORTING_MEMBER:
1578         case MLD_LEAVING_MEMBER:
1579                 if (state_change_retransmit_timer_expired) {
1580                         /*
1581                          * State-change retransmission timer fired.
1582                          * If there are any further pending retransmissions,
1583                          * set the global pending state-change flag, and
1584                          * reset the timer.
1585                          */
1586                         if (--inm->in6m_scrv > 0) {
1587                                 inm->in6m_sctimer = uri_fasthz;
1588                                 V_state_change_timers_running6 = 1;
1589                         }
1590                         /*
1591                          * Retransmit the previously computed state-change
1592                          * report. If there are no further pending
1593                          * retransmissions, the mbuf queue will be consumed.
1594                          * Update T0 state to T1 as we have now sent
1595                          * a state-change.
1596                          */
1597                         (void)mld_v2_merge_state_changes(inm, scq);
1598
1599                         in6m_commit(inm);
1600                         CTR3(KTR_MLD, "%s: T1 -> T0 for %s/%s", __func__,
1601                             ip6_sprintf(ip6tbuf, &inm->in6m_addr),
1602                             if_name(inm->in6m_ifp));
1603
1604                         /*
1605                          * If we are leaving the group for good, make sure
1606                          * we release MLD's reference to it.
1607                          * This release must be deferred using a SLIST,
1608                          * as we are called from a loop which traverses
1609                          * the in_ifmultiaddr TAILQ.
1610                          */
1611                         if (inm->in6m_state == MLD_LEAVING_MEMBER &&
1612                             inm->in6m_scrv == 0) {
1613                                 inm->in6m_state = MLD_NOT_MEMBER;
1614                                 in6m_disconnect_locked(inmh, inm);
1615                                 in6m_rele_locked(inmh, inm);
1616                         }
1617                 }
1618                 break;
1619         }
1620 }
1621
1622 /*
1623  * Switch to a different version on the given interface,
1624  * as per Section 9.12.
1625  */
1626 static void
1627 mld_set_version(struct mld_ifsoftc *mli, const int version)
1628 {
1629         int old_version_timer;
1630
1631         MLD_LOCK_ASSERT();
1632
1633         CTR4(KTR_MLD, "%s: switching to v%d on ifp %p(%s)", __func__,
1634             version, mli->mli_ifp, if_name(mli->mli_ifp));
1635
1636         if (version == MLD_VERSION_1) {
1637                 /*
1638                  * Compute the "Older Version Querier Present" timer as per
1639                  * Section 9.12.
1640                  */
1641                 old_version_timer = (mli->mli_rv * mli->mli_qi) + mli->mli_qri;
1642                 old_version_timer *= PR_SLOWHZ;
1643                 mli->mli_v1_timer = old_version_timer;
1644         }
1645
1646         if (mli->mli_v1_timer > 0 && mli->mli_version != MLD_VERSION_1) {
1647                 mli->mli_version = MLD_VERSION_1;
1648                 mld_v2_cancel_link_timers(mli);
1649         }
1650 }
1651
1652 /*
1653  * Cancel pending MLDv2 timers for the given link and all groups
1654  * joined on it; state-change, general-query, and group-query timers.
1655  */
1656 static void
1657 mld_v2_cancel_link_timers(struct mld_ifsoftc *mli)
1658 {
1659         struct epoch_tracker     et;
1660         struct in6_multi_head    inmh;
1661         struct ifmultiaddr      *ifma;
1662         struct ifnet            *ifp;
1663         struct in6_multi        *inm;
1664
1665         CTR3(KTR_MLD, "%s: cancel v2 timers on ifp %p(%s)", __func__,
1666             mli->mli_ifp, if_name(mli->mli_ifp));
1667
1668         SLIST_INIT(&inmh);
1669         IN6_MULTI_LIST_LOCK_ASSERT();
1670         MLD_LOCK_ASSERT();
1671
1672         /*
1673          * Fast-track this potentially expensive operation
1674          * by checking all the global 'timer pending' flags.
1675          */
1676         if (!V_interface_timers_running6 &&
1677             !V_state_change_timers_running6 &&
1678             !V_current_state_timers_running6)
1679                 return;
1680
1681         mli->mli_v2_timer = 0;
1682
1683         ifp = mli->mli_ifp;
1684
1685         IF_ADDR_WLOCK(ifp);
1686         NET_EPOCH_ENTER_ET(et);
1687         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1688                 inm = in6m_ifmultiaddr_get_inm(ifma);
1689                 if (inm == NULL)
1690                         continue;
1691                 switch (inm->in6m_state) {
1692                 case MLD_NOT_MEMBER:
1693                 case MLD_SILENT_MEMBER:
1694                 case MLD_IDLE_MEMBER:
1695                 case MLD_LAZY_MEMBER:
1696                 case MLD_SLEEPING_MEMBER:
1697                 case MLD_AWAKENING_MEMBER:
1698                         break;
1699                 case MLD_LEAVING_MEMBER:
1700                         /*
1701                          * If we are leaving the group and switching
1702                          * version, we need to release the final
1703                          * reference held for issuing the INCLUDE {}.
1704                          */
1705                         if (inm->in6m_refcount == 1)
1706                                 in6m_disconnect_locked(&inmh, inm);
1707                         in6m_rele_locked(&inmh, inm);
1708                         /* FALLTHROUGH */
1709                 case MLD_G_QUERY_PENDING_MEMBER:
1710                 case MLD_SG_QUERY_PENDING_MEMBER:
1711                         in6m_clear_recorded(inm);
1712                         /* FALLTHROUGH */
1713                 case MLD_REPORTING_MEMBER:
1714                         inm->in6m_sctimer = 0;
1715                         inm->in6m_timer = 0;
1716                         inm->in6m_state = MLD_REPORTING_MEMBER;
1717                         /*
1718                          * Free any pending MLDv2 state-change records.
1719                          */
1720                         mbufq_drain(&inm->in6m_scq);
1721                         break;
1722                 }
1723         }
1724         NET_EPOCH_EXIT_ET(et);
1725         IF_ADDR_WUNLOCK(ifp);
1726         in6m_release_list_deferred(&inmh);
1727 }
1728
1729 /*
1730  * Global slowtimo handler.
1731  * VIMAGE: Timeout handlers are expected to service all vimages.
1732  */
1733 void
1734 mld_slowtimo(void)
1735 {
1736         VNET_ITERATOR_DECL(vnet_iter);
1737
1738         VNET_LIST_RLOCK_NOSLEEP();
1739         VNET_FOREACH(vnet_iter) {
1740                 CURVNET_SET(vnet_iter);
1741                 mld_slowtimo_vnet();
1742                 CURVNET_RESTORE();
1743         }
1744         VNET_LIST_RUNLOCK_NOSLEEP();
1745 }
1746
1747 /*
1748  * Per-vnet slowtimo handler.
1749  */
1750 static void
1751 mld_slowtimo_vnet(void)
1752 {
1753         struct mld_ifsoftc *mli;
1754
1755         MLD_LOCK();
1756
1757         LIST_FOREACH(mli, &V_mli_head, mli_link) {
1758                 mld_v1_process_querier_timers(mli);
1759         }
1760
1761         MLD_UNLOCK();
1762 }
1763
1764 /*
1765  * Update the Older Version Querier Present timers for a link.
1766  * See Section 9.12 of RFC 3810.
1767  */
1768 static void
1769 mld_v1_process_querier_timers(struct mld_ifsoftc *mli)
1770 {
1771
1772         MLD_LOCK_ASSERT();
1773
1774         if (mli->mli_version != MLD_VERSION_2 && --mli->mli_v1_timer == 0) {
1775                 /*
1776                  * MLDv1 Querier Present timer expired; revert to MLDv2.
1777                  */
1778                 CTR5(KTR_MLD,
1779                     "%s: transition from v%d -> v%d on %p(%s)",
1780                     __func__, mli->mli_version, MLD_VERSION_2,
1781                     mli->mli_ifp, if_name(mli->mli_ifp));
1782                 mli->mli_version = MLD_VERSION_2;
1783         }
1784 }
1785
1786 /*
1787  * Transmit an MLDv1 report immediately.
1788  */
1789 static int
1790 mld_v1_transmit_report(struct in6_multi *in6m, const int type)
1791 {
1792         struct ifnet            *ifp;
1793         struct in6_ifaddr       *ia;
1794         struct ip6_hdr          *ip6;
1795         struct mbuf             *mh, *md;
1796         struct mld_hdr          *mld;
1797
1798         IN6_MULTI_LIST_LOCK_ASSERT();
1799         MLD_LOCK_ASSERT();
1800         
1801         ifp = in6m->in6m_ifp;
1802         /* in process of being freed */
1803         if (ifp == NULL)
1804                 return (0);
1805         ia = in6ifa_ifpforlinklocal(ifp, IN6_IFF_NOTREADY|IN6_IFF_ANYCAST);
1806         /* ia may be NULL if link-local address is tentative. */
1807
1808         mh = m_gethdr(M_NOWAIT, MT_DATA);
1809         if (mh == NULL) {
1810                 if (ia != NULL)
1811                         ifa_free(&ia->ia_ifa);
1812                 return (ENOMEM);
1813         }
1814         md = m_get(M_NOWAIT, MT_DATA);
1815         if (md == NULL) {
1816                 m_free(mh);
1817                 if (ia != NULL)
1818                         ifa_free(&ia->ia_ifa);
1819                 return (ENOMEM);
1820         }
1821         mh->m_next = md;
1822
1823         /*
1824          * FUTURE: Consider increasing alignment by ETHER_HDR_LEN, so
1825          * that ether_output() does not need to allocate another mbuf
1826          * for the header in the most common case.
1827          */
1828         M_ALIGN(mh, sizeof(struct ip6_hdr));
1829         mh->m_pkthdr.len = sizeof(struct ip6_hdr) + sizeof(struct mld_hdr);
1830         mh->m_len = sizeof(struct ip6_hdr);
1831
1832         ip6 = mtod(mh, struct ip6_hdr *);
1833         ip6->ip6_flow = 0;
1834         ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
1835         ip6->ip6_vfc |= IPV6_VERSION;
1836         ip6->ip6_nxt = IPPROTO_ICMPV6;
1837         ip6->ip6_src = ia ? ia->ia_addr.sin6_addr : in6addr_any;
1838         ip6->ip6_dst = in6m->in6m_addr;
1839
1840         md->m_len = sizeof(struct mld_hdr);
1841         mld = mtod(md, struct mld_hdr *);
1842         mld->mld_type = type;
1843         mld->mld_code = 0;
1844         mld->mld_cksum = 0;
1845         mld->mld_maxdelay = 0;
1846         mld->mld_reserved = 0;
1847         mld->mld_addr = in6m->in6m_addr;
1848         in6_clearscope(&mld->mld_addr);
1849         mld->mld_cksum = in6_cksum(mh, IPPROTO_ICMPV6,
1850             sizeof(struct ip6_hdr), sizeof(struct mld_hdr));
1851
1852         mld_save_context(mh, ifp);
1853         mh->m_flags |= M_MLDV1;
1854
1855         mld_dispatch_packet(mh);
1856
1857         if (ia != NULL)
1858                 ifa_free(&ia->ia_ifa);
1859         return (0);
1860 }
1861
1862 /*
1863  * Process a state change from the upper layer for the given IPv6 group.
1864  *
1865  * Each socket holds a reference on the in_multi in its own ip_moptions.
1866  * The socket layer will have made the necessary updates to.the group
1867  * state, it is now up to MLD to issue a state change report if there
1868  * has been any change between T0 (when the last state-change was issued)
1869  * and T1 (now).
1870  *
1871  * We use the MLDv2 state machine at group level. The MLd module
1872  * however makes the decision as to which MLD protocol version to speak.
1873  * A state change *from* INCLUDE {} always means an initial join.
1874  * A state change *to* INCLUDE {} always means a final leave.
1875  *
1876  * If delay is non-zero, and the state change is an initial multicast
1877  * join, the state change report will be delayed by 'delay' ticks
1878  * in units of PR_FASTHZ if MLDv1 is active on the link; otherwise
1879  * the initial MLDv2 state change report will be delayed by whichever
1880  * is sooner, a pending state-change timer or delay itself.
1881  *
1882  * VIMAGE: curvnet should have been set by caller, as this routine
1883  * is called from the socket option handlers.
1884  */
1885 int
1886 mld_change_state(struct in6_multi *inm, const int delay)
1887 {
1888         struct mld_ifsoftc *mli;
1889         struct ifnet *ifp;
1890         int error;
1891
1892         IN6_MULTI_LIST_LOCK_ASSERT();
1893
1894         error = 0;
1895
1896         /*
1897          * Check if the in6_multi has already been disconnected.
1898          */
1899         if (inm->in6m_ifp == NULL) {
1900                 CTR1(KTR_MLD, "%s: inm is disconnected", __func__);
1901                 return (0);
1902         }
1903
1904         /*
1905          * Try to detect if the upper layer just asked us to change state
1906          * for an interface which has now gone away.
1907          */
1908         KASSERT(inm->in6m_ifma != NULL, ("%s: no ifma", __func__));
1909         ifp = inm->in6m_ifma->ifma_ifp;
1910         if (ifp == NULL)
1911                 return (0);
1912         /*
1913          * Sanity check that netinet6's notion of ifp is the
1914          * same as net's.
1915          */
1916         KASSERT(inm->in6m_ifp == ifp, ("%s: bad ifp", __func__));
1917
1918         MLD_LOCK();
1919         mli = MLD_IFINFO(ifp);
1920         KASSERT(mli != NULL, ("%s: no mld_ifsoftc for ifp %p", __func__, ifp));
1921
1922         /*
1923          * If we detect a state transition to or from MCAST_UNDEFINED
1924          * for this group, then we are starting or finishing an MLD
1925          * life cycle for this group.
1926          */
1927         if (inm->in6m_st[1].iss_fmode != inm->in6m_st[0].iss_fmode) {
1928                 CTR3(KTR_MLD, "%s: inm transition %d -> %d", __func__,
1929                     inm->in6m_st[0].iss_fmode, inm->in6m_st[1].iss_fmode);
1930                 if (inm->in6m_st[0].iss_fmode == MCAST_UNDEFINED) {
1931                         CTR1(KTR_MLD, "%s: initial join", __func__);
1932                         error = mld_initial_join(inm, mli, delay);
1933                         goto out_locked;
1934                 } else if (inm->in6m_st[1].iss_fmode == MCAST_UNDEFINED) {
1935                         CTR1(KTR_MLD, "%s: final leave", __func__);
1936                         mld_final_leave(inm, mli);
1937                         goto out_locked;
1938                 }
1939         } else {
1940                 CTR1(KTR_MLD, "%s: filter set change", __func__);
1941         }
1942
1943         error = mld_handle_state_change(inm, mli);
1944
1945 out_locked:
1946         MLD_UNLOCK();
1947         return (error);
1948 }
1949
1950 /*
1951  * Perform the initial join for an MLD group.
1952  *
1953  * When joining a group:
1954  *  If the group should have its MLD traffic suppressed, do nothing.
1955  *  MLDv1 starts sending MLDv1 host membership reports.
1956  *  MLDv2 will schedule an MLDv2 state-change report containing the
1957  *  initial state of the membership.
1958  *
1959  * If the delay argument is non-zero, then we must delay sending the
1960  * initial state change for delay ticks (in units of PR_FASTHZ).
1961  */
1962 static int
1963 mld_initial_join(struct in6_multi *inm, struct mld_ifsoftc *mli,
1964     const int delay)
1965 {
1966         struct ifnet            *ifp;
1967         struct mbufq            *mq;
1968         int                      error, retval, syncstates;
1969         int                      odelay;
1970 #ifdef KTR
1971         char                     ip6tbuf[INET6_ADDRSTRLEN];
1972 #endif
1973
1974         CTR4(KTR_MLD, "%s: initial join %s on ifp %p(%s)",
1975             __func__, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
1976             inm->in6m_ifp, if_name(inm->in6m_ifp));
1977
1978         error = 0;
1979         syncstates = 1;
1980
1981         ifp = inm->in6m_ifp;
1982
1983         IN6_MULTI_LIST_LOCK_ASSERT();
1984         MLD_LOCK_ASSERT();
1985
1986         KASSERT(mli && mli->mli_ifp == ifp, ("%s: inconsistent ifp", __func__));
1987
1988         /*
1989          * Groups joined on loopback or marked as 'not reported',
1990          * enter the MLD_SILENT_MEMBER state and
1991          * are never reported in any protocol exchanges.
1992          * All other groups enter the appropriate state machine
1993          * for the version in use on this link.
1994          * A link marked as MLIF_SILENT causes MLD to be completely
1995          * disabled for the link.
1996          */
1997         if ((ifp->if_flags & IFF_LOOPBACK) ||
1998             (mli->mli_flags & MLIF_SILENT) ||
1999             !mld_is_addr_reported(&inm->in6m_addr)) {
2000                 CTR1(KTR_MLD,
2001 "%s: not kicking state machine for silent group", __func__);
2002                 inm->in6m_state = MLD_SILENT_MEMBER;
2003                 inm->in6m_timer = 0;
2004         } else {
2005                 /*
2006                  * Deal with overlapping in_multi lifecycle.
2007                  * If this group was LEAVING, then make sure
2008                  * we drop the reference we picked up to keep the
2009                  * group around for the final INCLUDE {} enqueue.
2010                  */
2011                 if (mli->mli_version == MLD_VERSION_2 &&
2012                     inm->in6m_state == MLD_LEAVING_MEMBER) {
2013                         inm->in6m_refcount--;
2014                         MPASS(inm->in6m_refcount > 0);
2015                 }
2016                 inm->in6m_state = MLD_REPORTING_MEMBER;
2017
2018                 switch (mli->mli_version) {
2019                 case MLD_VERSION_1:
2020                         /*
2021                          * If a delay was provided, only use it if
2022                          * it is greater than the delay normally
2023                          * used for an MLDv1 state change report,
2024                          * and delay sending the initial MLDv1 report
2025                          * by not transitioning to the IDLE state.
2026                          */
2027                         odelay = MLD_RANDOM_DELAY(MLD_V1_MAX_RI * PR_FASTHZ);
2028                         if (delay) {
2029                                 inm->in6m_timer = max(delay, odelay);
2030                                 V_current_state_timers_running6 = 1;
2031                         } else {
2032                                 inm->in6m_state = MLD_IDLE_MEMBER;
2033                                 error = mld_v1_transmit_report(inm,
2034                                      MLD_LISTENER_REPORT);
2035                                 if (error == 0) {
2036                                         inm->in6m_timer = odelay;
2037                                         V_current_state_timers_running6 = 1;
2038                                 }
2039                         }
2040                         break;
2041
2042                 case MLD_VERSION_2:
2043                         /*
2044                          * Defer update of T0 to T1, until the first copy
2045                          * of the state change has been transmitted.
2046                          */
2047                         syncstates = 0;
2048
2049                         /*
2050                          * Immediately enqueue a State-Change Report for
2051                          * this interface, freeing any previous reports.
2052                          * Don't kick the timers if there is nothing to do,
2053                          * or if an error occurred.
2054                          */
2055                         mq = &inm->in6m_scq;
2056                         mbufq_drain(mq);
2057                         retval = mld_v2_enqueue_group_record(mq, inm, 1,
2058                             0, 0, (mli->mli_flags & MLIF_USEALLOW));
2059                         CTR2(KTR_MLD, "%s: enqueue record = %d",
2060                             __func__, retval);
2061                         if (retval <= 0) {
2062                                 error = retval * -1;
2063                                 break;
2064                         }
2065
2066                         /*
2067                          * Schedule transmission of pending state-change
2068                          * report up to RV times for this link. The timer
2069                          * will fire at the next mld_fasttimo (~200ms),
2070                          * giving us an opportunity to merge the reports.
2071                          *
2072                          * If a delay was provided to this function, only
2073                          * use this delay if sooner than the existing one.
2074                          */
2075                         KASSERT(mli->mli_rv > 1,
2076                            ("%s: invalid robustness %d", __func__,
2077                             mli->mli_rv));
2078                         inm->in6m_scrv = mli->mli_rv;
2079                         if (delay) {
2080                                 if (inm->in6m_sctimer > 1) {
2081                                         inm->in6m_sctimer =
2082                                             min(inm->in6m_sctimer, delay);
2083                                 } else
2084                                         inm->in6m_sctimer = delay;
2085                         } else
2086                                 inm->in6m_sctimer = 1;
2087                         V_state_change_timers_running6 = 1;
2088
2089                         error = 0;
2090                         break;
2091                 }
2092         }
2093
2094         /*
2095          * Only update the T0 state if state change is atomic,
2096          * i.e. we don't need to wait for a timer to fire before we
2097          * can consider the state change to have been communicated.
2098          */
2099         if (syncstates) {
2100                 in6m_commit(inm);
2101                 CTR3(KTR_MLD, "%s: T1 -> T0 for %s/%s", __func__,
2102                     ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2103                     if_name(inm->in6m_ifp));
2104         }
2105
2106         return (error);
2107 }
2108
2109 /*
2110  * Issue an intermediate state change during the life-cycle.
2111  */
2112 static int
2113 mld_handle_state_change(struct in6_multi *inm, struct mld_ifsoftc *mli)
2114 {
2115         struct ifnet            *ifp;
2116         int                      retval;
2117 #ifdef KTR
2118         char                     ip6tbuf[INET6_ADDRSTRLEN];
2119 #endif
2120
2121         CTR4(KTR_MLD, "%s: state change for %s on ifp %p(%s)",
2122             __func__, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2123             inm->in6m_ifp, if_name(inm->in6m_ifp));
2124
2125         ifp = inm->in6m_ifp;
2126
2127         IN6_MULTI_LIST_LOCK_ASSERT();
2128         MLD_LOCK_ASSERT();
2129
2130         KASSERT(mli && mli->mli_ifp == ifp,
2131             ("%s: inconsistent ifp", __func__));
2132
2133         if ((ifp->if_flags & IFF_LOOPBACK) ||
2134             (mli->mli_flags & MLIF_SILENT) ||
2135             !mld_is_addr_reported(&inm->in6m_addr) ||
2136             (mli->mli_version != MLD_VERSION_2)) {
2137                 if (!mld_is_addr_reported(&inm->in6m_addr)) {
2138                         CTR1(KTR_MLD,
2139 "%s: not kicking state machine for silent group", __func__);
2140                 }
2141                 CTR1(KTR_MLD, "%s: nothing to do", __func__);
2142                 in6m_commit(inm);
2143                 CTR3(KTR_MLD, "%s: T1 -> T0 for %s/%s", __func__,
2144                     ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2145                     if_name(inm->in6m_ifp));
2146                 return (0);
2147         }
2148
2149         mbufq_drain(&inm->in6m_scq);
2150
2151         retval = mld_v2_enqueue_group_record(&inm->in6m_scq, inm, 1, 0, 0,
2152             (mli->mli_flags & MLIF_USEALLOW));
2153         CTR2(KTR_MLD, "%s: enqueue record = %d", __func__, retval);
2154         if (retval <= 0)
2155                 return (-retval);
2156
2157         /*
2158          * If record(s) were enqueued, start the state-change
2159          * report timer for this group.
2160          */
2161         inm->in6m_scrv = mli->mli_rv;
2162         inm->in6m_sctimer = 1;
2163         V_state_change_timers_running6 = 1;
2164
2165         return (0);
2166 }
2167
2168 /*
2169  * Perform the final leave for a multicast address.
2170  *
2171  * When leaving a group:
2172  *  MLDv1 sends a DONE message, if and only if we are the reporter.
2173  *  MLDv2 enqueues a state-change report containing a transition
2174  *  to INCLUDE {} for immediate transmission.
2175  */
2176 static void
2177 mld_final_leave(struct in6_multi *inm, struct mld_ifsoftc *mli)
2178 {
2179         int syncstates;
2180 #ifdef KTR
2181         char ip6tbuf[INET6_ADDRSTRLEN];
2182 #endif
2183
2184         syncstates = 1;
2185
2186         CTR4(KTR_MLD, "%s: final leave %s on ifp %p(%s)",
2187             __func__, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2188             inm->in6m_ifp, if_name(inm->in6m_ifp));
2189
2190         IN6_MULTI_LIST_LOCK_ASSERT();
2191         MLD_LOCK_ASSERT();
2192
2193         switch (inm->in6m_state) {
2194         case MLD_NOT_MEMBER:
2195         case MLD_SILENT_MEMBER:
2196         case MLD_LEAVING_MEMBER:
2197                 /* Already leaving or left; do nothing. */
2198                 CTR1(KTR_MLD,
2199 "%s: not kicking state machine for silent group", __func__);
2200                 break;
2201         case MLD_REPORTING_MEMBER:
2202         case MLD_IDLE_MEMBER:
2203         case MLD_G_QUERY_PENDING_MEMBER:
2204         case MLD_SG_QUERY_PENDING_MEMBER:
2205                 if (mli->mli_version == MLD_VERSION_1) {
2206 #ifdef INVARIANTS
2207                         if (inm->in6m_state == MLD_G_QUERY_PENDING_MEMBER ||
2208                             inm->in6m_state == MLD_SG_QUERY_PENDING_MEMBER)
2209                         panic("%s: MLDv2 state reached, not MLDv2 mode",
2210                              __func__);
2211 #endif
2212                         mld_v1_transmit_report(inm, MLD_LISTENER_DONE);
2213                         inm->in6m_state = MLD_NOT_MEMBER;
2214                         V_current_state_timers_running6 = 1;
2215                 } else if (mli->mli_version == MLD_VERSION_2) {
2216                         /*
2217                          * Stop group timer and all pending reports.
2218                          * Immediately enqueue a state-change report
2219                          * TO_IN {} to be sent on the next fast timeout,
2220                          * giving us an opportunity to merge reports.
2221                          */
2222                         mbufq_drain(&inm->in6m_scq);
2223                         inm->in6m_timer = 0;
2224                         inm->in6m_scrv = mli->mli_rv;
2225                         CTR4(KTR_MLD, "%s: Leaving %s/%s with %d "
2226                             "pending retransmissions.", __func__,
2227                             ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2228                             if_name(inm->in6m_ifp), inm->in6m_scrv);
2229                         if (inm->in6m_scrv == 0) {
2230                                 inm->in6m_state = MLD_NOT_MEMBER;
2231                                 inm->in6m_sctimer = 0;
2232                         } else {
2233                                 int retval;
2234
2235                                 in6m_acquire_locked(inm);
2236
2237                                 retval = mld_v2_enqueue_group_record(
2238                                     &inm->in6m_scq, inm, 1, 0, 0,
2239                                     (mli->mli_flags & MLIF_USEALLOW));
2240                                 KASSERT(retval != 0,
2241                                     ("%s: enqueue record = %d", __func__,
2242                                      retval));
2243
2244                                 inm->in6m_state = MLD_LEAVING_MEMBER;
2245                                 inm->in6m_sctimer = 1;
2246                                 V_state_change_timers_running6 = 1;
2247                                 syncstates = 0;
2248                         }
2249                         break;
2250                 }
2251                 break;
2252         case MLD_LAZY_MEMBER:
2253         case MLD_SLEEPING_MEMBER:
2254         case MLD_AWAKENING_MEMBER:
2255                 /* Our reports are suppressed; do nothing. */
2256                 break;
2257         }
2258
2259         if (syncstates) {
2260                 in6m_commit(inm);
2261                 CTR3(KTR_MLD, "%s: T1 -> T0 for %s/%s", __func__,
2262                     ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2263                     if_name(inm->in6m_ifp));
2264                 inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
2265                 CTR3(KTR_MLD, "%s: T1 now MCAST_UNDEFINED for %p/%s",
2266                     __func__, &inm->in6m_addr, if_name(inm->in6m_ifp));
2267         }
2268 }
2269
2270 /*
2271  * Enqueue an MLDv2 group record to the given output queue.
2272  *
2273  * If is_state_change is zero, a current-state record is appended.
2274  * If is_state_change is non-zero, a state-change report is appended.
2275  *
2276  * If is_group_query is non-zero, an mbuf packet chain is allocated.
2277  * If is_group_query is zero, and if there is a packet with free space
2278  * at the tail of the queue, it will be appended to providing there
2279  * is enough free space.
2280  * Otherwise a new mbuf packet chain is allocated.
2281  *
2282  * If is_source_query is non-zero, each source is checked to see if
2283  * it was recorded for a Group-Source query, and will be omitted if
2284  * it is not both in-mode and recorded.
2285  *
2286  * If use_block_allow is non-zero, state change reports for initial join
2287  * and final leave, on an inclusive mode group with a source list, will be
2288  * rewritten to use the ALLOW_NEW and BLOCK_OLD record types, respectively.
2289  *
2290  * The function will attempt to allocate leading space in the packet
2291  * for the IPv6+ICMP headers to be prepended without fragmenting the chain.
2292  *
2293  * If successful the size of all data appended to the queue is returned,
2294  * otherwise an error code less than zero is returned, or zero if
2295  * no record(s) were appended.
2296  */
2297 static int
2298 mld_v2_enqueue_group_record(struct mbufq *mq, struct in6_multi *inm,
2299     const int is_state_change, const int is_group_query,
2300     const int is_source_query, const int use_block_allow)
2301 {
2302         struct mldv2_record      mr;
2303         struct mldv2_record     *pmr;
2304         struct ifnet            *ifp;
2305         struct ip6_msource      *ims, *nims;
2306         struct mbuf             *m0, *m, *md;
2307         int                      is_filter_list_change;
2308         int                      minrec0len, m0srcs, msrcs, nbytes, off;
2309         int                      record_has_sources;
2310         int                      now;
2311         int                      type;
2312         uint8_t                  mode;
2313 #ifdef KTR
2314         char                     ip6tbuf[INET6_ADDRSTRLEN];
2315 #endif
2316
2317         IN6_MULTI_LIST_LOCK_ASSERT();
2318
2319         ifp = inm->in6m_ifp;
2320         is_filter_list_change = 0;
2321         m = NULL;
2322         m0 = NULL;
2323         m0srcs = 0;
2324         msrcs = 0;
2325         nbytes = 0;
2326         nims = NULL;
2327         record_has_sources = 1;
2328         pmr = NULL;
2329         type = MLD_DO_NOTHING;
2330         mode = inm->in6m_st[1].iss_fmode;
2331
2332         /*
2333          * If we did not transition out of ASM mode during t0->t1,
2334          * and there are no source nodes to process, we can skip
2335          * the generation of source records.
2336          */
2337         if (inm->in6m_st[0].iss_asm > 0 && inm->in6m_st[1].iss_asm > 0 &&
2338             inm->in6m_nsrc == 0)
2339                 record_has_sources = 0;
2340
2341         if (is_state_change) {
2342                 /*
2343                  * Queue a state change record.
2344                  * If the mode did not change, and there are non-ASM
2345                  * listeners or source filters present,
2346                  * we potentially need to issue two records for the group.
2347                  * If there are ASM listeners, and there was no filter
2348                  * mode transition of any kind, do nothing.
2349                  *
2350                  * If we are transitioning to MCAST_UNDEFINED, we need
2351                  * not send any sources. A transition to/from this state is
2352                  * considered inclusive with some special treatment.
2353                  *
2354                  * If we are rewriting initial joins/leaves to use
2355                  * ALLOW/BLOCK, and the group's membership is inclusive,
2356                  * we need to send sources in all cases.
2357                  */
2358                 if (mode != inm->in6m_st[0].iss_fmode) {
2359                         if (mode == MCAST_EXCLUDE) {
2360                                 CTR1(KTR_MLD, "%s: change to EXCLUDE",
2361                                     __func__);
2362                                 type = MLD_CHANGE_TO_EXCLUDE_MODE;
2363                         } else {
2364                                 CTR1(KTR_MLD, "%s: change to INCLUDE",
2365                                     __func__);
2366                                 if (use_block_allow) {
2367                                         /*
2368                                          * XXX
2369                                          * Here we're interested in state
2370                                          * edges either direction between
2371                                          * MCAST_UNDEFINED and MCAST_INCLUDE.
2372                                          * Perhaps we should just check
2373                                          * the group state, rather than
2374                                          * the filter mode.
2375                                          */
2376                                         if (mode == MCAST_UNDEFINED) {
2377                                                 type = MLD_BLOCK_OLD_SOURCES;
2378                                         } else {
2379                                                 type = MLD_ALLOW_NEW_SOURCES;
2380                                         }
2381                                 } else {
2382                                         type = MLD_CHANGE_TO_INCLUDE_MODE;
2383                                         if (mode == MCAST_UNDEFINED)
2384                                                 record_has_sources = 0;
2385                                 }
2386                         }
2387                 } else {
2388                         if (record_has_sources) {
2389                                 is_filter_list_change = 1;
2390                         } else {
2391                                 type = MLD_DO_NOTHING;
2392                         }
2393                 }
2394         } else {
2395                 /*
2396                  * Queue a current state record.
2397                  */
2398                 if (mode == MCAST_EXCLUDE) {
2399                         type = MLD_MODE_IS_EXCLUDE;
2400                 } else if (mode == MCAST_INCLUDE) {
2401                         type = MLD_MODE_IS_INCLUDE;
2402                         KASSERT(inm->in6m_st[1].iss_asm == 0,
2403                             ("%s: inm %p is INCLUDE but ASM count is %d",
2404                              __func__, inm, inm->in6m_st[1].iss_asm));
2405                 }
2406         }
2407
2408         /*
2409          * Generate the filter list changes using a separate function.
2410          */
2411         if (is_filter_list_change)
2412                 return (mld_v2_enqueue_filter_change(mq, inm));
2413
2414         if (type == MLD_DO_NOTHING) {
2415                 CTR3(KTR_MLD, "%s: nothing to do for %s/%s",
2416                     __func__, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2417                     if_name(inm->in6m_ifp));
2418                 return (0);
2419         }
2420
2421         /*
2422          * If any sources are present, we must be able to fit at least
2423          * one in the trailing space of the tail packet's mbuf,
2424          * ideally more.
2425          */
2426         minrec0len = sizeof(struct mldv2_record);
2427         if (record_has_sources)
2428                 minrec0len += sizeof(struct in6_addr);
2429
2430         CTR4(KTR_MLD, "%s: queueing %s for %s/%s", __func__,
2431             mld_rec_type_to_str(type),
2432             ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2433             if_name(inm->in6m_ifp));
2434
2435         /*
2436          * Check if we have a packet in the tail of the queue for this
2437          * group into which the first group record for this group will fit.
2438          * Otherwise allocate a new packet.
2439          * Always allocate leading space for IP6+RA+ICMPV6+REPORT.
2440          * Note: Group records for G/GSR query responses MUST be sent
2441          * in their own packet.
2442          */
2443         m0 = mbufq_last(mq);
2444         if (!is_group_query &&
2445             m0 != NULL &&
2446             (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <= MLD_V2_REPORT_MAXRECS) &&
2447             (m0->m_pkthdr.len + minrec0len) <
2448              (ifp->if_mtu - MLD_MTUSPACE)) {
2449                 m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
2450                             sizeof(struct mldv2_record)) /
2451                             sizeof(struct in6_addr);
2452                 m = m0;
2453                 CTR1(KTR_MLD, "%s: use existing packet", __func__);
2454         } else {
2455                 if (mbufq_full(mq)) {
2456                         CTR1(KTR_MLD, "%s: outbound queue full", __func__);
2457                         return (-ENOMEM);
2458                 }
2459                 m = NULL;
2460                 m0srcs = (ifp->if_mtu - MLD_MTUSPACE -
2461                     sizeof(struct mldv2_record)) / sizeof(struct in6_addr);
2462                 if (!is_state_change && !is_group_query)
2463                         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2464                 if (m == NULL)
2465                         m = m_gethdr(M_NOWAIT, MT_DATA);
2466                 if (m == NULL)
2467                         return (-ENOMEM);
2468
2469                 mld_save_context(m, ifp);
2470
2471                 CTR1(KTR_MLD, "%s: allocated first packet", __func__);
2472         }
2473
2474         /*
2475          * Append group record.
2476          * If we have sources, we don't know how many yet.
2477          */
2478         mr.mr_type = type;
2479         mr.mr_datalen = 0;
2480         mr.mr_numsrc = 0;
2481         mr.mr_addr = inm->in6m_addr;
2482         in6_clearscope(&mr.mr_addr);
2483         if (!m_append(m, sizeof(struct mldv2_record), (void *)&mr)) {
2484                 if (m != m0)
2485                         m_freem(m);
2486                 CTR1(KTR_MLD, "%s: m_append() failed.", __func__);
2487                 return (-ENOMEM);
2488         }
2489         nbytes += sizeof(struct mldv2_record);
2490
2491         /*
2492          * Append as many sources as will fit in the first packet.
2493          * If we are appending to a new packet, the chain allocation
2494          * may potentially use clusters; use m_getptr() in this case.
2495          * If we are appending to an existing packet, we need to obtain
2496          * a pointer to the group record after m_append(), in case a new
2497          * mbuf was allocated.
2498          *
2499          * Only append sources which are in-mode at t1. If we are
2500          * transitioning to MCAST_UNDEFINED state on the group, and
2501          * use_block_allow is zero, do not include source entries.
2502          * Otherwise, we need to include this source in the report.
2503          *
2504          * Only report recorded sources in our filter set when responding
2505          * to a group-source query.
2506          */
2507         if (record_has_sources) {
2508                 if (m == m0) {
2509                         md = m_last(m);
2510                         pmr = (struct mldv2_record *)(mtod(md, uint8_t *) +
2511                             md->m_len - nbytes);
2512                 } else {
2513                         md = m_getptr(m, 0, &off);
2514                         pmr = (struct mldv2_record *)(mtod(md, uint8_t *) +
2515                             off);
2516                 }
2517                 msrcs = 0;
2518                 RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs,
2519                     nims) {
2520                         CTR2(KTR_MLD, "%s: visit node %s", __func__,
2521                             ip6_sprintf(ip6tbuf, &ims->im6s_addr));
2522                         now = im6s_get_mode(inm, ims, 1);
2523                         CTR2(KTR_MLD, "%s: node is %d", __func__, now);
2524                         if ((now != mode) ||
2525                             (now == mode &&
2526                              (!use_block_allow && mode == MCAST_UNDEFINED))) {
2527                                 CTR1(KTR_MLD, "%s: skip node", __func__);
2528                                 continue;
2529                         }
2530                         if (is_source_query && ims->im6s_stp == 0) {
2531                                 CTR1(KTR_MLD, "%s: skip unrecorded node",
2532                                     __func__);
2533                                 continue;
2534                         }
2535                         CTR1(KTR_MLD, "%s: append node", __func__);
2536                         if (!m_append(m, sizeof(struct in6_addr),
2537                             (void *)&ims->im6s_addr)) {
2538                                 if (m != m0)
2539                                         m_freem(m);
2540                                 CTR1(KTR_MLD, "%s: m_append() failed.",
2541                                     __func__);
2542                                 return (-ENOMEM);
2543                         }
2544                         nbytes += sizeof(struct in6_addr);
2545                         ++msrcs;
2546                         if (msrcs == m0srcs)
2547                                 break;
2548                 }
2549                 CTR2(KTR_MLD, "%s: msrcs is %d this packet", __func__,
2550                     msrcs);
2551                 pmr->mr_numsrc = htons(msrcs);
2552                 nbytes += (msrcs * sizeof(struct in6_addr));
2553         }
2554
2555         if (is_source_query && msrcs == 0) {
2556                 CTR1(KTR_MLD, "%s: no recorded sources to report", __func__);
2557                 if (m != m0)
2558                         m_freem(m);
2559                 return (0);
2560         }
2561
2562         /*
2563          * We are good to go with first packet.
2564          */
2565         if (m != m0) {
2566                 CTR1(KTR_MLD, "%s: enqueueing first packet", __func__);
2567                 m->m_pkthdr.PH_vt.vt_nrecs = 1;
2568                 mbufq_enqueue(mq, m);
2569         } else
2570                 m->m_pkthdr.PH_vt.vt_nrecs++;
2571
2572         /*
2573          * No further work needed if no source list in packet(s).
2574          */
2575         if (!record_has_sources)
2576                 return (nbytes);
2577
2578         /*
2579          * Whilst sources remain to be announced, we need to allocate
2580          * a new packet and fill out as many sources as will fit.
2581          * Always try for a cluster first.
2582          */
2583         while (nims != NULL) {
2584                 if (mbufq_full(mq)) {
2585                         CTR1(KTR_MLD, "%s: outbound queue full", __func__);
2586                         return (-ENOMEM);
2587                 }
2588                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2589                 if (m == NULL)
2590                         m = m_gethdr(M_NOWAIT, MT_DATA);
2591                 if (m == NULL)
2592                         return (-ENOMEM);
2593                 mld_save_context(m, ifp);
2594                 md = m_getptr(m, 0, &off);
2595                 pmr = (struct mldv2_record *)(mtod(md, uint8_t *) + off);
2596                 CTR1(KTR_MLD, "%s: allocated next packet", __func__);
2597
2598                 if (!m_append(m, sizeof(struct mldv2_record), (void *)&mr)) {
2599                         if (m != m0)
2600                                 m_freem(m);
2601                         CTR1(KTR_MLD, "%s: m_append() failed.", __func__);
2602                         return (-ENOMEM);
2603                 }
2604                 m->m_pkthdr.PH_vt.vt_nrecs = 1;
2605                 nbytes += sizeof(struct mldv2_record);
2606
2607                 m0srcs = (ifp->if_mtu - MLD_MTUSPACE -
2608                     sizeof(struct mldv2_record)) / sizeof(struct in6_addr);
2609
2610                 msrcs = 0;
2611                 RB_FOREACH_FROM(ims, ip6_msource_tree, nims) {
2612                         CTR2(KTR_MLD, "%s: visit node %s",
2613                             __func__, ip6_sprintf(ip6tbuf, &ims->im6s_addr));
2614                         now = im6s_get_mode(inm, ims, 1);
2615                         if ((now != mode) ||
2616                             (now == mode &&
2617                              (!use_block_allow && mode == MCAST_UNDEFINED))) {
2618                                 CTR1(KTR_MLD, "%s: skip node", __func__);
2619                                 continue;
2620                         }
2621                         if (is_source_query && ims->im6s_stp == 0) {
2622                                 CTR1(KTR_MLD, "%s: skip unrecorded node",
2623                                     __func__);
2624                                 continue;
2625                         }
2626                         CTR1(KTR_MLD, "%s: append node", __func__);
2627                         if (!m_append(m, sizeof(struct in6_addr),
2628                             (void *)&ims->im6s_addr)) {
2629                                 if (m != m0)
2630                                         m_freem(m);
2631                                 CTR1(KTR_MLD, "%s: m_append() failed.",
2632                                     __func__);
2633                                 return (-ENOMEM);
2634                         }
2635                         ++msrcs;
2636                         if (msrcs == m0srcs)
2637                                 break;
2638                 }
2639                 pmr->mr_numsrc = htons(msrcs);
2640                 nbytes += (msrcs * sizeof(struct in6_addr));
2641
2642                 CTR1(KTR_MLD, "%s: enqueueing next packet", __func__);
2643                 mbufq_enqueue(mq, m);
2644         }
2645
2646         return (nbytes);
2647 }
2648
2649 /*
2650  * Type used to mark record pass completion.
2651  * We exploit the fact we can cast to this easily from the
2652  * current filter modes on each ip_msource node.
2653  */
2654 typedef enum {
2655         REC_NONE = 0x00,        /* MCAST_UNDEFINED */
2656         REC_ALLOW = 0x01,       /* MCAST_INCLUDE */
2657         REC_BLOCK = 0x02,       /* MCAST_EXCLUDE */
2658         REC_FULL = REC_ALLOW | REC_BLOCK
2659 } rectype_t;
2660
2661 /*
2662  * Enqueue an MLDv2 filter list change to the given output queue.
2663  *
2664  * Source list filter state is held in an RB-tree. When the filter list
2665  * for a group is changed without changing its mode, we need to compute
2666  * the deltas between T0 and T1 for each source in the filter set,
2667  * and enqueue the appropriate ALLOW_NEW/BLOCK_OLD records.
2668  *
2669  * As we may potentially queue two record types, and the entire R-B tree
2670  * needs to be walked at once, we break this out into its own function
2671  * so we can generate a tightly packed queue of packets.
2672  *
2673  * XXX This could be written to only use one tree walk, although that makes
2674  * serializing into the mbuf chains a bit harder. For now we do two walks
2675  * which makes things easier on us, and it may or may not be harder on
2676  * the L2 cache.
2677  *
2678  * If successful the size of all data appended to the queue is returned,
2679  * otherwise an error code less than zero is returned, or zero if
2680  * no record(s) were appended.
2681  */
2682 static int
2683 mld_v2_enqueue_filter_change(struct mbufq *mq, struct in6_multi *inm)
2684 {
2685         static const int MINRECLEN =
2686             sizeof(struct mldv2_record) + sizeof(struct in6_addr);
2687         struct ifnet            *ifp;
2688         struct mldv2_record      mr;
2689         struct mldv2_record     *pmr;
2690         struct ip6_msource      *ims, *nims;
2691         struct mbuf             *m, *m0, *md;
2692         int                      m0srcs, nbytes, npbytes, off, rsrcs, schanged;
2693         int                      nallow, nblock;
2694         uint8_t                  mode, now, then;
2695         rectype_t                crt, drt, nrt;
2696 #ifdef KTR
2697         char                     ip6tbuf[INET6_ADDRSTRLEN];
2698 #endif
2699
2700         IN6_MULTI_LIST_LOCK_ASSERT();
2701
2702         if (inm->in6m_nsrc == 0 ||
2703             (inm->in6m_st[0].iss_asm > 0 && inm->in6m_st[1].iss_asm > 0))
2704                 return (0);
2705
2706         ifp = inm->in6m_ifp;                    /* interface */
2707         mode = inm->in6m_st[1].iss_fmode;       /* filter mode at t1 */
2708         crt = REC_NONE; /* current group record type */
2709         drt = REC_NONE; /* mask of completed group record types */
2710         nrt = REC_NONE; /* record type for current node */
2711         m0srcs = 0;     /* # source which will fit in current mbuf chain */
2712         npbytes = 0;    /* # of bytes appended this packet */
2713         nbytes = 0;     /* # of bytes appended to group's state-change queue */
2714         rsrcs = 0;      /* # sources encoded in current record */
2715         schanged = 0;   /* # nodes encoded in overall filter change */
2716         nallow = 0;     /* # of source entries in ALLOW_NEW */
2717         nblock = 0;     /* # of source entries in BLOCK_OLD */
2718         nims = NULL;    /* next tree node pointer */
2719
2720         /*
2721          * For each possible filter record mode.
2722          * The first kind of source we encounter tells us which
2723          * is the first kind of record we start appending.
2724          * If a node transitioned to UNDEFINED at t1, its mode is treated
2725          * as the inverse of the group's filter mode.
2726          */
2727         while (drt != REC_FULL) {
2728                 do {
2729                         m0 = mbufq_last(mq);
2730                         if (m0 != NULL &&
2731                             (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <=
2732                              MLD_V2_REPORT_MAXRECS) &&
2733                             (m0->m_pkthdr.len + MINRECLEN) <
2734                              (ifp->if_mtu - MLD_MTUSPACE)) {
2735                                 m = m0;
2736                                 m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
2737                                             sizeof(struct mldv2_record)) /
2738                                             sizeof(struct in6_addr);
2739                                 CTR1(KTR_MLD,
2740                                     "%s: use previous packet", __func__);
2741                         } else {
2742                                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2743                                 if (m == NULL)
2744                                         m = m_gethdr(M_NOWAIT, MT_DATA);
2745                                 if (m == NULL) {
2746                                         CTR1(KTR_MLD,
2747                                             "%s: m_get*() failed", __func__);
2748                                         return (-ENOMEM);
2749                                 }
2750                                 m->m_pkthdr.PH_vt.vt_nrecs = 0;
2751                                 mld_save_context(m, ifp);
2752                                 m0srcs = (ifp->if_mtu - MLD_MTUSPACE -
2753                                     sizeof(struct mldv2_record)) /
2754                                     sizeof(struct in6_addr);
2755                                 npbytes = 0;
2756                                 CTR1(KTR_MLD,
2757                                     "%s: allocated new packet", __func__);
2758                         }
2759                         /*
2760                          * Append the MLD group record header to the
2761                          * current packet's data area.
2762                          * Recalculate pointer to free space for next
2763                          * group record, in case m_append() allocated
2764                          * a new mbuf or cluster.
2765                          */
2766                         memset(&mr, 0, sizeof(mr));
2767                         mr.mr_addr = inm->in6m_addr;
2768                         in6_clearscope(&mr.mr_addr);
2769                         if (!m_append(m, sizeof(mr), (void *)&mr)) {
2770                                 if (m != m0)
2771                                         m_freem(m);
2772                                 CTR1(KTR_MLD,
2773                                     "%s: m_append() failed", __func__);
2774                                 return (-ENOMEM);
2775                         }
2776                         npbytes += sizeof(struct mldv2_record);
2777                         if (m != m0) {
2778                                 /* new packet; offset in chain */
2779                                 md = m_getptr(m, npbytes -
2780                                     sizeof(struct mldv2_record), &off);
2781                                 pmr = (struct mldv2_record *)(mtod(md,
2782                                     uint8_t *) + off);
2783                         } else {
2784                                 /* current packet; offset from last append */
2785                                 md = m_last(m);
2786                                 pmr = (struct mldv2_record *)(mtod(md,
2787                                     uint8_t *) + md->m_len -
2788                                     sizeof(struct mldv2_record));
2789                         }
2790                         /*
2791                          * Begin walking the tree for this record type
2792                          * pass, or continue from where we left off
2793                          * previously if we had to allocate a new packet.
2794                          * Only report deltas in-mode at t1.
2795                          * We need not report included sources as allowed
2796                          * if we are in inclusive mode on the group,
2797                          * however the converse is not true.
2798                          */
2799                         rsrcs = 0;
2800                         if (nims == NULL) {
2801                                 nims = RB_MIN(ip6_msource_tree,
2802                                     &inm->in6m_srcs);
2803                         }
2804                         RB_FOREACH_FROM(ims, ip6_msource_tree, nims) {
2805                                 CTR2(KTR_MLD, "%s: visit node %s", __func__,
2806                                     ip6_sprintf(ip6tbuf, &ims->im6s_addr));
2807                                 now = im6s_get_mode(inm, ims, 1);
2808                                 then = im6s_get_mode(inm, ims, 0);
2809                                 CTR3(KTR_MLD, "%s: mode: t0 %d, t1 %d",
2810                                     __func__, then, now);
2811                                 if (now == then) {
2812                                         CTR1(KTR_MLD,
2813                                             "%s: skip unchanged", __func__);
2814                                         continue;
2815                                 }
2816                                 if (mode == MCAST_EXCLUDE &&
2817                                     now == MCAST_INCLUDE) {
2818                                         CTR1(KTR_MLD,
2819                                             "%s: skip IN src on EX group",
2820                                             __func__);
2821                                         continue;
2822                                 }
2823                                 nrt = (rectype_t)now;
2824                                 if (nrt == REC_NONE)
2825                                         nrt = (rectype_t)(~mode & REC_FULL);
2826                                 if (schanged++ == 0) {
2827                                         crt = nrt;
2828                                 } else if (crt != nrt)
2829                                         continue;
2830                                 if (!m_append(m, sizeof(struct in6_addr),
2831                                     (void *)&ims->im6s_addr)) {
2832                                         if (m != m0)
2833                                                 m_freem(m);
2834                                         CTR1(KTR_MLD,
2835                                             "%s: m_append() failed", __func__);
2836                                         return (-ENOMEM);
2837                                 }
2838                                 nallow += !!(crt == REC_ALLOW);
2839                                 nblock += !!(crt == REC_BLOCK);
2840                                 if (++rsrcs == m0srcs)
2841                                         break;
2842                         }
2843                         /*
2844                          * If we did not append any tree nodes on this
2845                          * pass, back out of allocations.
2846                          */
2847                         if (rsrcs == 0) {
2848                                 npbytes -= sizeof(struct mldv2_record);
2849                                 if (m != m0) {
2850                                         CTR1(KTR_MLD,
2851                                             "%s: m_free(m)", __func__);
2852                                         m_freem(m);
2853                                 } else {
2854                                         CTR1(KTR_MLD,
2855                                             "%s: m_adj(m, -mr)", __func__);
2856                                         m_adj(m, -((int)sizeof(
2857                                             struct mldv2_record)));
2858                                 }
2859                                 continue;
2860                         }
2861                         npbytes += (rsrcs * sizeof(struct in6_addr));
2862                         if (crt == REC_ALLOW)
2863                                 pmr->mr_type = MLD_ALLOW_NEW_SOURCES;
2864                         else if (crt == REC_BLOCK)
2865                                 pmr->mr_type = MLD_BLOCK_OLD_SOURCES;
2866                         pmr->mr_numsrc = htons(rsrcs);
2867                         /*
2868                          * Count the new group record, and enqueue this
2869                          * packet if it wasn't already queued.
2870                          */
2871                         m->m_pkthdr.PH_vt.vt_nrecs++;
2872                         if (m != m0)
2873                                 mbufq_enqueue(mq, m);
2874                         nbytes += npbytes;
2875                 } while (nims != NULL);
2876                 drt |= crt;
2877                 crt = (~crt & REC_FULL);
2878         }
2879
2880         CTR3(KTR_MLD, "%s: queued %d ALLOW_NEW, %d BLOCK_OLD", __func__,
2881             nallow, nblock);
2882
2883         return (nbytes);
2884 }
2885
2886 static int
2887 mld_v2_merge_state_changes(struct in6_multi *inm, struct mbufq *scq)
2888 {
2889         struct mbufq    *gq;
2890         struct mbuf     *m;             /* pending state-change */
2891         struct mbuf     *m0;            /* copy of pending state-change */
2892         struct mbuf     *mt;            /* last state-change in packet */
2893         int              docopy, domerge;
2894         u_int            recslen;
2895
2896         docopy = 0;
2897         domerge = 0;
2898         recslen = 0;
2899
2900         IN6_MULTI_LIST_LOCK_ASSERT();
2901         MLD_LOCK_ASSERT();
2902
2903         /*
2904          * If there are further pending retransmissions, make a writable
2905          * copy of each queued state-change message before merging.
2906          */
2907         if (inm->in6m_scrv > 0)
2908                 docopy = 1;
2909
2910         gq = &inm->in6m_scq;
2911 #ifdef KTR
2912         if (mbufq_first(gq) == NULL) {
2913                 CTR2(KTR_MLD, "%s: WARNING: queue for inm %p is empty",
2914                     __func__, inm);
2915         }
2916 #endif
2917
2918         m = mbufq_first(gq);
2919         while (m != NULL) {
2920                 /*
2921                  * Only merge the report into the current packet if
2922                  * there is sufficient space to do so; an MLDv2 report
2923                  * packet may only contain 65,535 group records.
2924                  * Always use a simple mbuf chain concatentation to do this,
2925                  * as large state changes for single groups may have
2926                  * allocated clusters.
2927                  */
2928                 domerge = 0;
2929                 mt = mbufq_last(scq);
2930                 if (mt != NULL) {
2931                         recslen = m_length(m, NULL);
2932
2933                         if ((mt->m_pkthdr.PH_vt.vt_nrecs +
2934                             m->m_pkthdr.PH_vt.vt_nrecs <=
2935                             MLD_V2_REPORT_MAXRECS) &&
2936                             (mt->m_pkthdr.len + recslen <=
2937                             (inm->in6m_ifp->if_mtu - MLD_MTUSPACE)))
2938                                 domerge = 1;
2939                 }
2940
2941                 if (!domerge && mbufq_full(gq)) {
2942                         CTR2(KTR_MLD,
2943                             "%s: outbound queue full, skipping whole packet %p",
2944                             __func__, m);
2945                         mt = m->m_nextpkt;
2946                         if (!docopy)
2947                                 m_freem(m);
2948                         m = mt;
2949                         continue;
2950                 }
2951
2952                 if (!docopy) {
2953                         CTR2(KTR_MLD, "%s: dequeueing %p", __func__, m);
2954                         m0 = mbufq_dequeue(gq);
2955                         m = m0->m_nextpkt;
2956                 } else {
2957                         CTR2(KTR_MLD, "%s: copying %p", __func__, m);
2958                         m0 = m_dup(m, M_NOWAIT);
2959                         if (m0 == NULL)
2960                                 return (ENOMEM);
2961                         m0->m_nextpkt = NULL;
2962                         m = m->m_nextpkt;
2963                 }
2964
2965                 if (!domerge) {
2966                         CTR3(KTR_MLD, "%s: queueing %p to scq %p)",
2967                             __func__, m0, scq);
2968                         mbufq_enqueue(scq, m0);
2969                 } else {
2970                         struct mbuf *mtl;       /* last mbuf of packet mt */
2971
2972                         CTR3(KTR_MLD, "%s: merging %p with ifscq tail %p)",
2973                             __func__, m0, mt);
2974
2975                         mtl = m_last(mt);
2976                         m0->m_flags &= ~M_PKTHDR;
2977                         mt->m_pkthdr.len += recslen;
2978                         mt->m_pkthdr.PH_vt.vt_nrecs +=
2979                             m0->m_pkthdr.PH_vt.vt_nrecs;
2980
2981                         mtl->m_next = m0;
2982                 }
2983         }
2984
2985         return (0);
2986 }
2987
2988 /*
2989  * Respond to a pending MLDv2 General Query.
2990  */
2991 static void
2992 mld_v2_dispatch_general_query(struct mld_ifsoftc *mli)
2993 {
2994         struct ifmultiaddr      *ifma;
2995         struct ifnet            *ifp;
2996         struct in6_multi        *inm;
2997         int                      retval;
2998
2999         IN6_MULTI_LIST_LOCK_ASSERT();
3000         MLD_LOCK_ASSERT();
3001
3002         KASSERT(mli->mli_version == MLD_VERSION_2,
3003             ("%s: called when version %d", __func__, mli->mli_version));
3004
3005         /*
3006          * Check that there are some packets queued. If so, send them first.
3007          * For large number of groups the reply to general query can take
3008          * many packets, we should finish sending them before starting of
3009          * queuing the new reply.
3010          */
3011         if (mbufq_len(&mli->mli_gq) != 0)
3012                 goto send;
3013
3014         ifp = mli->mli_ifp;
3015
3016         IF_ADDR_RLOCK(ifp);
3017         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3018                 inm = in6m_ifmultiaddr_get_inm(ifma);
3019                 if (inm == NULL)
3020                         continue;
3021                 KASSERT(ifp == inm->in6m_ifp,
3022                     ("%s: inconsistent ifp", __func__));
3023
3024                 switch (inm->in6m_state) {
3025                 case MLD_NOT_MEMBER:
3026                 case MLD_SILENT_MEMBER:
3027                         break;
3028                 case MLD_REPORTING_MEMBER:
3029                 case MLD_IDLE_MEMBER:
3030                 case MLD_LAZY_MEMBER:
3031                 case MLD_SLEEPING_MEMBER:
3032                 case MLD_AWAKENING_MEMBER:
3033                         inm->in6m_state = MLD_REPORTING_MEMBER;
3034                         retval = mld_v2_enqueue_group_record(&mli->mli_gq,
3035                             inm, 0, 0, 0, 0);
3036                         CTR2(KTR_MLD, "%s: enqueue record = %d",
3037                             __func__, retval);
3038                         break;
3039                 case MLD_G_QUERY_PENDING_MEMBER:
3040                 case MLD_SG_QUERY_PENDING_MEMBER:
3041                 case MLD_LEAVING_MEMBER:
3042                         break;
3043                 }
3044         }
3045         IF_ADDR_RUNLOCK(ifp);
3046
3047 send:
3048         mld_dispatch_queue(&mli->mli_gq, MLD_MAX_RESPONSE_BURST);
3049
3050         /*
3051          * Slew transmission of bursts over 500ms intervals.
3052          */
3053         if (mbufq_first(&mli->mli_gq) != NULL) {
3054                 mli->mli_v2_timer = 1 + MLD_RANDOM_DELAY(
3055                     MLD_RESPONSE_BURST_INTERVAL);
3056                 V_interface_timers_running6 = 1;
3057         }
3058 }
3059
3060 /*
3061  * Transmit the next pending message in the output queue.
3062  *
3063  * VIMAGE: Needs to store/restore vnet pointer on a per-mbuf-chain basis.
3064  * MRT: Nothing needs to be done, as MLD traffic is always local to
3065  * a link and uses a link-scope multicast address.
3066  */
3067 static void
3068 mld_dispatch_packet(struct mbuf *m)
3069 {
3070         struct ip6_moptions      im6o;
3071         struct ifnet            *ifp;
3072         struct ifnet            *oifp;
3073         struct mbuf             *m0;
3074         struct mbuf             *md;
3075         struct ip6_hdr          *ip6;
3076         struct mld_hdr          *mld;
3077         int                      error;
3078         int                      off;
3079         int                      type;
3080         uint32_t                 ifindex;
3081
3082         CTR2(KTR_MLD, "%s: transmit %p", __func__, m);
3083
3084         /*
3085          * Set VNET image pointer from enqueued mbuf chain
3086          * before doing anything else. Whilst we use interface
3087          * indexes to guard against interface detach, they are
3088          * unique to each VIMAGE and must be retrieved.
3089          */
3090         ifindex = mld_restore_context(m);
3091
3092         /*
3093          * Check if the ifnet still exists. This limits the scope of
3094          * any race in the absence of a global ifp lock for low cost
3095          * (an array lookup).
3096          */
3097         ifp = ifnet_byindex(ifindex);
3098         if (ifp == NULL) {
3099                 CTR3(KTR_MLD, "%s: dropped %p as ifindex %u went away.",
3100                     __func__, m, ifindex);
3101                 m_freem(m);
3102                 IP6STAT_INC(ip6s_noroute);
3103                 goto out;
3104         }
3105
3106         im6o.im6o_multicast_hlim  = 1;
3107         im6o.im6o_multicast_loop = (V_ip6_mrouter != NULL);
3108         im6o.im6o_multicast_ifp = ifp;
3109
3110         if (m->m_flags & M_MLDV1) {
3111                 m0 = m;
3112         } else {
3113                 m0 = mld_v2_encap_report(ifp, m);
3114                 if (m0 == NULL) {
3115                         CTR2(KTR_MLD, "%s: dropped %p", __func__, m);
3116                         IP6STAT_INC(ip6s_odropped);
3117                         goto out;
3118                 }
3119         }
3120
3121         mld_scrub_context(m0);
3122         m_clrprotoflags(m);
3123         m0->m_pkthdr.rcvif = V_loif;
3124
3125         ip6 = mtod(m0, struct ip6_hdr *);
3126 #if 0
3127         (void)in6_setscope(&ip6->ip6_dst, ifp, NULL);   /* XXX LOR */
3128 #else
3129         /*
3130          * XXX XXX Break some KPI rules to prevent an LOR which would
3131          * occur if we called in6_setscope() at transmission.
3132          * See comments at top of file.
3133          */
3134         MLD_EMBEDSCOPE(&ip6->ip6_dst, ifp->if_index);
3135 #endif
3136
3137         /*
3138          * Retrieve the ICMPv6 type before handoff to ip6_output(),
3139          * so we can bump the stats.
3140          */
3141         md = m_getptr(m0, sizeof(struct ip6_hdr), &off);
3142         mld = (struct mld_hdr *)(mtod(md, uint8_t *) + off);
3143         type = mld->mld_type;
3144
3145         error = ip6_output(m0, &mld_po, NULL, IPV6_UNSPECSRC, &im6o,
3146             &oifp, NULL);
3147         if (error) {
3148                 CTR3(KTR_MLD, "%s: ip6_output(%p) = %d", __func__, m0, error);
3149                 goto out;
3150         }
3151         ICMP6STAT_INC(icp6s_outhist[type]);
3152         if (oifp != NULL) {
3153                 icmp6_ifstat_inc(oifp, ifs6_out_msg);
3154                 switch (type) {
3155                 case MLD_LISTENER_REPORT:
3156                 case MLDV2_LISTENER_REPORT:
3157                         icmp6_ifstat_inc(oifp, ifs6_out_mldreport);
3158                         break;
3159                 case MLD_LISTENER_DONE:
3160                         icmp6_ifstat_inc(oifp, ifs6_out_mlddone);
3161                         break;
3162                 }
3163         }
3164 out:
3165         return;
3166 }
3167
3168 /*
3169  * Encapsulate an MLDv2 report.
3170  *
3171  * KAME IPv6 requires that hop-by-hop options be passed separately,
3172  * and that the IPv6 header be prepended in a separate mbuf.
3173  *
3174  * Returns a pointer to the new mbuf chain head, or NULL if the
3175  * allocation failed.
3176  */
3177 static struct mbuf *
3178 mld_v2_encap_report(struct ifnet *ifp, struct mbuf *m)
3179 {
3180         struct mbuf             *mh;
3181         struct mldv2_report     *mld;
3182         struct ip6_hdr          *ip6;
3183         struct in6_ifaddr       *ia;
3184         int                      mldreclen;
3185
3186         KASSERT(ifp != NULL, ("%s: null ifp", __func__));
3187         KASSERT((m->m_flags & M_PKTHDR),
3188             ("%s: mbuf chain %p is !M_PKTHDR", __func__, m));
3189
3190         /*
3191          * RFC3590: OK to send as :: or tentative during DAD.
3192          */
3193         ia = in6ifa_ifpforlinklocal(ifp, IN6_IFF_NOTREADY|IN6_IFF_ANYCAST);
3194         if (ia == NULL)
3195                 CTR1(KTR_MLD, "%s: warning: ia is NULL", __func__);
3196
3197         mh = m_gethdr(M_NOWAIT, MT_DATA);
3198         if (mh == NULL) {
3199                 if (ia != NULL)
3200                         ifa_free(&ia->ia_ifa);
3201                 m_freem(m);
3202                 return (NULL);
3203         }
3204         M_ALIGN(mh, sizeof(struct ip6_hdr) + sizeof(struct mldv2_report));
3205
3206         mldreclen = m_length(m, NULL);
3207         CTR2(KTR_MLD, "%s: mldreclen is %d", __func__, mldreclen);
3208
3209         mh->m_len = sizeof(struct ip6_hdr) + sizeof(struct mldv2_report);
3210         mh->m_pkthdr.len = sizeof(struct ip6_hdr) +
3211             sizeof(struct mldv2_report) + mldreclen;
3212
3213         ip6 = mtod(mh, struct ip6_hdr *);
3214         ip6->ip6_flow = 0;
3215         ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
3216         ip6->ip6_vfc |= IPV6_VERSION;
3217         ip6->ip6_nxt = IPPROTO_ICMPV6;
3218         ip6->ip6_src = ia ? ia->ia_addr.sin6_addr : in6addr_any;
3219         if (ia != NULL)
3220                 ifa_free(&ia->ia_ifa);
3221         ip6->ip6_dst = in6addr_linklocal_allv2routers;
3222         /* scope ID will be set in netisr */
3223
3224         mld = (struct mldv2_report *)(ip6 + 1);
3225         mld->mld_type = MLDV2_LISTENER_REPORT;
3226         mld->mld_code = 0;
3227         mld->mld_cksum = 0;
3228         mld->mld_v2_reserved = 0;
3229         mld->mld_v2_numrecs = htons(m->m_pkthdr.PH_vt.vt_nrecs);
3230         m->m_pkthdr.PH_vt.vt_nrecs = 0;
3231
3232         mh->m_next = m;
3233         mld->mld_cksum = in6_cksum(mh, IPPROTO_ICMPV6,
3234             sizeof(struct ip6_hdr), sizeof(struct mldv2_report) + mldreclen);
3235         return (mh);
3236 }
3237
3238 #ifdef KTR
3239 static char *
3240 mld_rec_type_to_str(const int type)
3241 {
3242
3243         switch (type) {
3244                 case MLD_CHANGE_TO_EXCLUDE_MODE:
3245                         return "TO_EX";
3246                         break;
3247                 case MLD_CHANGE_TO_INCLUDE_MODE:
3248                         return "TO_IN";
3249                         break;
3250                 case MLD_MODE_IS_EXCLUDE:
3251                         return "MODE_EX";
3252                         break;
3253                 case MLD_MODE_IS_INCLUDE:
3254                         return "MODE_IN";
3255                         break;
3256                 case MLD_ALLOW_NEW_SOURCES:
3257                         return "ALLOW_NEW";
3258                         break;
3259                 case MLD_BLOCK_OLD_SOURCES:
3260                         return "BLOCK_OLD";
3261                         break;
3262                 default:
3263                         break;
3264         }
3265         return "unknown";
3266 }
3267 #endif
3268
3269 static void
3270 mld_init(void *unused __unused)
3271 {
3272
3273         CTR1(KTR_MLD, "%s: initializing", __func__);
3274         MLD_LOCK_INIT();
3275
3276         ip6_initpktopts(&mld_po);
3277         mld_po.ip6po_hlim = 1;
3278         mld_po.ip6po_hbh = &mld_ra.hbh;
3279         mld_po.ip6po_prefer_tempaddr = IP6PO_TEMPADDR_NOTPREFER;
3280         mld_po.ip6po_flags = IP6PO_DONTFRAG;
3281 }
3282 SYSINIT(mld_init, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE, mld_init, NULL);
3283
3284 static void
3285 mld_uninit(void *unused __unused)
3286 {
3287
3288         CTR1(KTR_MLD, "%s: tearing down", __func__);
3289         MLD_LOCK_DESTROY();
3290 }
3291 SYSUNINIT(mld_uninit, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE, mld_uninit, NULL);
3292
3293 static void
3294 vnet_mld_init(const void *unused __unused)
3295 {
3296
3297         CTR1(KTR_MLD, "%s: initializing", __func__);
3298
3299         LIST_INIT(&V_mli_head);
3300 }
3301 VNET_SYSINIT(vnet_mld_init, SI_SUB_PROTO_MC, SI_ORDER_ANY, vnet_mld_init,
3302     NULL);
3303
3304 static void
3305 vnet_mld_uninit(const void *unused __unused)
3306 {
3307
3308         /* This can happen if we shutdown the network stack. */
3309         CTR1(KTR_MLD, "%s: tearing down", __func__);
3310 }
3311 VNET_SYSUNINIT(vnet_mld_uninit, SI_SUB_PROTO_MC, SI_ORDER_ANY, vnet_mld_uninit,
3312     NULL);
3313
3314 static int
3315 mld_modevent(module_t mod, int type, void *unused __unused)
3316 {
3317
3318     switch (type) {
3319     case MOD_LOAD:
3320     case MOD_UNLOAD:
3321         break;
3322     default:
3323         return (EOPNOTSUPP);
3324     }
3325     return (0);
3326 }
3327
3328 static moduledata_t mld_mod = {
3329     "mld",
3330     mld_modevent,
3331     0
3332 };
3333 DECLARE_MODULE(mld, mld_mod, SI_SUB_PROTO_MC, SI_ORDER_ANY);