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