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