]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/in6_mcast.c
Use proper prototype for SYSINIT() functions.
[FreeBSD/FreeBSD.git] / sys / netinet6 / in6_mcast.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2009 Bruce Simpson.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote
16  *    products derived from this software without specific prior written
17  *    permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 /*
33  * IPv6 multicast socket, group, and socket option processing module.
34  * Normative references: RFC 2292, RFC 3492, RFC 3542, RFC 3678, RFC 3810.
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_inet6.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/ktr.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/priv.h>
53 #include <sys/taskqueue.h>
54 #include <sys/tree.h>
55
56 #include <net/if.h>
57 #include <net/if_var.h>
58 #include <net/if_dl.h>
59 #include <net/route.h>
60 #include <net/route/nhop.h>
61 #include <net/vnet.h>
62
63 #include <netinet/in.h>
64 #include <netinet/udp.h>
65 #include <netinet/in_var.h>
66 #include <netinet/ip_var.h>
67 #include <netinet/udp_var.h>
68 #include <netinet6/in6_fib.h>
69 #include <netinet6/in6_var.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/tcp_var.h>
75 #include <netinet6/nd6.h>
76 #include <netinet6/mld6_var.h>
77 #include <netinet6/scope6_var.h>
78
79 #ifndef KTR_MLD
80 #define KTR_MLD KTR_INET6
81 #endif
82
83 #ifndef __SOCKUNION_DECLARED
84 union sockunion {
85         struct sockaddr_storage ss;
86         struct sockaddr         sa;
87         struct sockaddr_dl      sdl;
88         struct sockaddr_in6     sin6;
89 };
90 typedef union sockunion sockunion_t;
91 #define __SOCKUNION_DECLARED
92 #endif /* __SOCKUNION_DECLARED */
93
94 static MALLOC_DEFINE(M_IN6MFILTER, "in6_mfilter",
95     "IPv6 multicast PCB-layer source filter");
96 MALLOC_DEFINE(M_IP6MADDR, "in6_multi", "IPv6 multicast group");
97 static MALLOC_DEFINE(M_IP6MOPTS, "ip6_moptions", "IPv6 multicast options");
98 static MALLOC_DEFINE(M_IP6MSOURCE, "ip6_msource",
99     "IPv6 multicast MLD-layer source filter");
100
101 RB_GENERATE(ip6_msource_tree, ip6_msource, im6s_link, ip6_msource_cmp);
102
103 /*
104  * Locking:
105  * - Lock order is: Giant, IN6_MULTI_LOCK, INP_WLOCK,
106  *   IN6_MULTI_LIST_LOCK, MLD_LOCK, IF_ADDR_LOCK.
107  * - The IF_ADDR_LOCK is implicitly taken by in6m_lookup() earlier, however
108  *   it can be taken by code in net/if.c also.
109  * - ip6_moptions and in6_mfilter are covered by the INP_WLOCK.
110  *
111  * struct in6_multi is covered by IN6_MULTI_LOCK. There isn't strictly
112  * any need for in6_multi itself to be virtualized -- it is bound to an ifp
113  * anyway no matter what happens.
114  */
115 struct mtx in6_multi_list_mtx;
116 MTX_SYSINIT(in6_multi_mtx, &in6_multi_list_mtx, "in6_multi_list_mtx", MTX_DEF);
117
118 struct mtx in6_multi_free_mtx;
119 MTX_SYSINIT(in6_multi_free_mtx, &in6_multi_free_mtx, "in6_multi_free_mtx", MTX_DEF);
120
121 struct sx in6_multi_sx;
122 SX_SYSINIT(in6_multi_sx, &in6_multi_sx, "in6_multi_sx");
123
124 static void     im6f_commit(struct in6_mfilter *);
125 static int      im6f_get_source(struct in6_mfilter *imf,
126                     const struct sockaddr_in6 *psin,
127                     struct in6_msource **);
128 static struct in6_msource *
129                 im6f_graft(struct in6_mfilter *, const uint8_t,
130                     const struct sockaddr_in6 *);
131 static void     im6f_leave(struct in6_mfilter *);
132 static int      im6f_prune(struct in6_mfilter *, const struct sockaddr_in6 *);
133 static void     im6f_purge(struct in6_mfilter *);
134 static void     im6f_rollback(struct in6_mfilter *);
135 static void     im6f_reap(struct in6_mfilter *);
136 static struct in6_mfilter *
137                 im6o_match_group(const struct ip6_moptions *,
138                     const struct ifnet *, const struct sockaddr *);
139 static struct in6_msource *
140                 im6o_match_source(struct in6_mfilter *, const struct sockaddr *);
141 static void     im6s_merge(struct ip6_msource *ims,
142                     const struct in6_msource *lims, const int rollback);
143 static int      in6_getmulti(struct ifnet *, const struct in6_addr *,
144                     struct in6_multi **);
145 static int      in6_joingroup_locked(struct ifnet *, const struct in6_addr *,
146                     struct in6_mfilter *, struct in6_multi **, int);
147 static int      in6m_get_source(struct in6_multi *inm,
148                     const struct in6_addr *addr, const int noalloc,
149                     struct ip6_msource **pims);
150 #ifdef KTR
151 static int      in6m_is_ifp_detached(const struct in6_multi *);
152 #endif
153 static int      in6m_merge(struct in6_multi *, /*const*/ struct in6_mfilter *);
154 static void     in6m_purge(struct in6_multi *);
155 static void     in6m_reap(struct in6_multi *);
156 static struct ip6_moptions *
157                 in6p_findmoptions(struct inpcb *);
158 static int      in6p_get_source_filters(struct inpcb *, struct sockopt *);
159 static int      in6p_join_group(struct inpcb *, struct sockopt *);
160 static int      in6p_leave_group(struct inpcb *, struct sockopt *);
161 static struct ifnet *
162                 in6p_lookup_mcast_ifp(const struct inpcb *,
163                     const struct sockaddr_in6 *);
164 static int      in6p_block_unblock_source(struct inpcb *, struct sockopt *);
165 static int      in6p_set_multicast_if(struct inpcb *, struct sockopt *);
166 static int      in6p_set_source_filters(struct inpcb *, struct sockopt *);
167 static int      sysctl_ip6_mcast_filters(SYSCTL_HANDLER_ARGS);
168
169 SYSCTL_DECL(_net_inet6_ip6);    /* XXX Not in any common header. */
170
171 static SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, mcast,
172     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
173     "IPv6 multicast");
174
175 static u_long in6_mcast_maxgrpsrc = IPV6_MAX_GROUP_SRC_FILTER;
176 SYSCTL_ULONG(_net_inet6_ip6_mcast, OID_AUTO, maxgrpsrc,
177     CTLFLAG_RWTUN, &in6_mcast_maxgrpsrc, 0,
178     "Max source filters per group");
179
180 static u_long in6_mcast_maxsocksrc = IPV6_MAX_SOCK_SRC_FILTER;
181 SYSCTL_ULONG(_net_inet6_ip6_mcast, OID_AUTO, maxsocksrc,
182     CTLFLAG_RWTUN, &in6_mcast_maxsocksrc, 0,
183     "Max source filters per socket");
184
185 /* TODO Virtualize this switch. */
186 int in6_mcast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
187 SYSCTL_INT(_net_inet6_ip6_mcast, OID_AUTO, loop, CTLFLAG_RWTUN,
188     &in6_mcast_loop, 0, "Loopback multicast datagrams by default");
189
190 static SYSCTL_NODE(_net_inet6_ip6_mcast, OID_AUTO, filters,
191     CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_ip6_mcast_filters,
192     "Per-interface stack-wide source filters");
193
194 #ifdef KTR
195 /*
196  * Inline function which wraps assertions for a valid ifp.
197  * The ifnet layer will set the ifma's ifp pointer to NULL if the ifp
198  * is detached.
199  */
200 static int __inline
201 in6m_is_ifp_detached(const struct in6_multi *inm)
202 {
203         struct ifnet *ifp;
204
205         KASSERT(inm->in6m_ifma != NULL, ("%s: no ifma", __func__));
206         ifp = inm->in6m_ifma->ifma_ifp;
207         if (ifp != NULL) {
208                 /*
209                  * Sanity check that network-layer notion of ifp is the
210                  * same as that of link-layer.
211                  */
212                 KASSERT(inm->in6m_ifp == ifp, ("%s: bad ifp", __func__));
213         }
214
215         return (ifp == NULL);
216 }
217 #endif
218
219 /*
220  * Initialize an in6_mfilter structure to a known state at t0, t1
221  * with an empty source filter list.
222  */
223 static __inline void
224 im6f_init(struct in6_mfilter *imf, const int st0, const int st1)
225 {
226         memset(imf, 0, sizeof(struct in6_mfilter));
227         RB_INIT(&imf->im6f_sources);
228         imf->im6f_st[0] = st0;
229         imf->im6f_st[1] = st1;
230 }
231
232 struct in6_mfilter *
233 ip6_mfilter_alloc(const int mflags, const int st0, const int st1)
234 {
235         struct in6_mfilter *imf;
236
237         imf = malloc(sizeof(*imf), M_IN6MFILTER, mflags);
238
239         if (imf != NULL)
240                 im6f_init(imf, st0, st1);
241
242         return (imf);
243 }
244
245 void
246 ip6_mfilter_free(struct in6_mfilter *imf)
247 {
248
249         im6f_purge(imf);
250         free(imf, M_IN6MFILTER);
251 }
252
253 /*
254  * Find an IPv6 multicast group entry for this ip6_moptions instance
255  * which matches the specified group, and optionally an interface.
256  * Return its index into the array, or -1 if not found.
257  */
258 static struct in6_mfilter *
259 im6o_match_group(const struct ip6_moptions *imo, const struct ifnet *ifp,
260     const struct sockaddr *group)
261 {
262         const struct sockaddr_in6 *gsin6;
263         struct in6_mfilter *imf;
264         struct in6_multi *inm;
265
266         gsin6 = (const struct sockaddr_in6 *)group;
267
268         IP6_MFILTER_FOREACH(imf, &imo->im6o_head) {
269                 inm = imf->im6f_in6m;
270                 if (inm == NULL)
271                         continue;
272                 if ((ifp == NULL || (inm->in6m_ifp == ifp)) &&
273                     IN6_ARE_ADDR_EQUAL(&inm->in6m_addr,
274                     &gsin6->sin6_addr)) {
275                         break;
276                 }
277         }
278         return (imf);
279 }
280
281 /*
282  * Find an IPv6 multicast source entry for this imo which matches
283  * the given group index for this socket, and source address.
284  *
285  * XXX TODO: The scope ID, if present in src, is stripped before
286  * any comparison. We SHOULD enforce scope/zone checks where the source
287  * filter entry has a link scope.
288  *
289  * NOTE: This does not check if the entry is in-mode, merely if
290  * it exists, which may not be the desired behaviour.
291  */
292 static struct in6_msource *
293 im6o_match_source(struct in6_mfilter *imf, const struct sockaddr *src)
294 {
295         struct ip6_msource       find;
296         struct ip6_msource      *ims;
297         const sockunion_t       *psa;
298
299         KASSERT(src->sa_family == AF_INET6, ("%s: !AF_INET6", __func__));
300
301         psa = (const sockunion_t *)src;
302         find.im6s_addr = psa->sin6.sin6_addr;
303         in6_clearscope(&find.im6s_addr);                /* XXX */
304         ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
305
306         return ((struct in6_msource *)ims);
307 }
308
309 /*
310  * Perform filtering for multicast datagrams on a socket by group and source.
311  *
312  * Returns 0 if a datagram should be allowed through, or various error codes
313  * if the socket was not a member of the group, or the source was muted, etc.
314  */
315 int
316 im6o_mc_filter(const struct ip6_moptions *imo, const struct ifnet *ifp,
317     const struct sockaddr *group, const struct sockaddr *src)
318 {
319         struct in6_mfilter *imf;
320         struct in6_msource *ims;
321         int mode;
322
323         KASSERT(ifp != NULL, ("%s: null ifp", __func__));
324
325         imf = im6o_match_group(imo, ifp, group);
326         if (imf == NULL)
327                 return (MCAST_NOTGMEMBER);
328
329         /*
330          * Check if the source was included in an (S,G) join.
331          * Allow reception on exclusive memberships by default,
332          * reject reception on inclusive memberships by default.
333          * Exclude source only if an in-mode exclude filter exists.
334          * Include source only if an in-mode include filter exists.
335          * NOTE: We are comparing group state here at MLD t1 (now)
336          * with socket-layer t0 (since last downcall).
337          */
338         mode = imf->im6f_st[1];
339         ims = im6o_match_source(imf, src);
340
341         if ((ims == NULL && mode == MCAST_INCLUDE) ||
342             (ims != NULL && ims->im6sl_st[0] != mode))
343                 return (MCAST_NOTSMEMBER);
344
345         return (MCAST_PASS);
346 }
347
348 /*
349  * Find and return a reference to an in6_multi record for (ifp, group),
350  * and bump its reference count.
351  * If one does not exist, try to allocate it, and update link-layer multicast
352  * filters on ifp to listen for group.
353  * Assumes the IN6_MULTI lock is held across the call.
354  * Return 0 if successful, otherwise return an appropriate error code.
355  */
356 static int
357 in6_getmulti(struct ifnet *ifp, const struct in6_addr *group,
358     struct in6_multi **pinm)
359 {
360         struct epoch_tracker     et;
361         struct sockaddr_in6      gsin6;
362         struct ifmultiaddr      *ifma;
363         struct in6_multi        *inm;
364         int                      error;
365
366         error = 0;
367
368         /*
369          * XXX: Accesses to ifma_protospec must be covered by IF_ADDR_LOCK;
370          * if_addmulti() takes this mutex itself, so we must drop and
371          * re-acquire around the call.
372          */
373         IN6_MULTI_LOCK_ASSERT();
374         IN6_MULTI_LIST_LOCK();
375         IF_ADDR_WLOCK(ifp);
376         NET_EPOCH_ENTER(et);
377         inm = in6m_lookup_locked(ifp, group);
378         NET_EPOCH_EXIT(et);
379
380         if (inm != NULL) {
381                 /*
382                  * If we already joined this group, just bump the
383                  * refcount and return it.
384                  */
385                 KASSERT(inm->in6m_refcount >= 1,
386                     ("%s: bad refcount %d", __func__, inm->in6m_refcount));
387                 in6m_acquire_locked(inm);
388                 *pinm = inm;
389                 goto out_locked;
390         }
391
392         memset(&gsin6, 0, sizeof(gsin6));
393         gsin6.sin6_family = AF_INET6;
394         gsin6.sin6_len = sizeof(struct sockaddr_in6);
395         gsin6.sin6_addr = *group;
396
397         /*
398          * Check if a link-layer group is already associated
399          * with this network-layer group on the given ifnet.
400          */
401         IN6_MULTI_LIST_UNLOCK();
402         IF_ADDR_WUNLOCK(ifp);
403         error = if_addmulti(ifp, (struct sockaddr *)&gsin6, &ifma);
404         if (error != 0)
405                 return (error);
406         IN6_MULTI_LIST_LOCK();
407         IF_ADDR_WLOCK(ifp);
408
409         /*
410          * If something other than netinet6 is occupying the link-layer
411          * group, print a meaningful error message and back out of
412          * the allocation.
413          * Otherwise, bump the refcount on the existing network-layer
414          * group association and return it.
415          */
416         if (ifma->ifma_protospec != NULL) {
417                 inm = (struct in6_multi *)ifma->ifma_protospec;
418 #ifdef INVARIANTS
419                 KASSERT(ifma->ifma_addr != NULL, ("%s: no ifma_addr",
420                     __func__));
421                 KASSERT(ifma->ifma_addr->sa_family == AF_INET6,
422                     ("%s: ifma not AF_INET6", __func__));
423                 KASSERT(inm != NULL, ("%s: no ifma_protospec", __func__));
424                 if (inm->in6m_ifma != ifma || inm->in6m_ifp != ifp ||
425                     !IN6_ARE_ADDR_EQUAL(&inm->in6m_addr, group))
426                         panic("%s: ifma %p is inconsistent with %p (%p)",
427                             __func__, ifma, inm, group);
428 #endif
429                 in6m_acquire_locked(inm);
430                 *pinm = inm;
431                 goto out_locked;
432         }
433
434         IF_ADDR_WLOCK_ASSERT(ifp);
435
436         /*
437          * A new in6_multi record is needed; allocate and initialize it.
438          * We DO NOT perform an MLD join as the in6_ layer may need to
439          * push an initial source list down to MLD to support SSM.
440          *
441          * The initial source filter state is INCLUDE, {} as per the RFC.
442          * Pending state-changes per group are subject to a bounds check.
443          */
444         inm = malloc(sizeof(*inm), M_IP6MADDR, M_NOWAIT | M_ZERO);
445         if (inm == NULL) {
446                 IN6_MULTI_LIST_UNLOCK();
447                 IF_ADDR_WUNLOCK(ifp);
448                 if_delmulti_ifma(ifma);
449                 return (ENOMEM);
450         }
451         inm->in6m_addr = *group;
452         inm->in6m_ifp = ifp;
453         inm->in6m_mli = MLD_IFINFO(ifp);
454         inm->in6m_ifma = ifma;
455         inm->in6m_refcount = 1;
456         inm->in6m_state = MLD_NOT_MEMBER;
457         mbufq_init(&inm->in6m_scq, MLD_MAX_STATE_CHANGES);
458
459         inm->in6m_st[0].iss_fmode = MCAST_UNDEFINED;
460         inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
461         RB_INIT(&inm->in6m_srcs);
462
463         ifma->ifma_protospec = inm;
464         *pinm = inm;
465
466  out_locked:
467         IN6_MULTI_LIST_UNLOCK();
468         IF_ADDR_WUNLOCK(ifp);
469         return (error);
470 }
471
472 /*
473  * Drop a reference to an in6_multi record.
474  *
475  * If the refcount drops to 0, free the in6_multi record and
476  * delete the underlying link-layer membership.
477  */
478 static void
479 in6m_release(struct in6_multi *inm)
480 {
481         struct ifmultiaddr *ifma;
482         struct ifnet *ifp;
483
484         CTR2(KTR_MLD, "%s: refcount is %d", __func__, inm->in6m_refcount);
485
486         MPASS(inm->in6m_refcount == 0);
487         CTR2(KTR_MLD, "%s: freeing inm %p", __func__, inm);
488
489         ifma = inm->in6m_ifma;
490         ifp = inm->in6m_ifp;
491         MPASS(ifma->ifma_llifma == NULL);
492
493         /* XXX this access is not covered by IF_ADDR_LOCK */
494         CTR2(KTR_MLD, "%s: purging ifma %p", __func__, ifma);
495         KASSERT(ifma->ifma_protospec == NULL,
496             ("%s: ifma_protospec != NULL", __func__));
497         if (ifp == NULL)
498                 ifp = ifma->ifma_ifp;
499
500         if (ifp != NULL) {
501                 CURVNET_SET(ifp->if_vnet);
502                 in6m_purge(inm);
503                 free(inm, M_IP6MADDR);
504                 if_delmulti_ifma_flags(ifma, 1);
505                 CURVNET_RESTORE();
506                 if_rele(ifp);
507         } else {
508                 in6m_purge(inm);
509                 free(inm, M_IP6MADDR);
510                 if_delmulti_ifma_flags(ifma, 1);
511         }
512 }
513
514 /*
515  * Interface detach can happen in a taskqueue thread context, so we must use a
516  * dedicated thread to avoid deadlocks when draining in6m_release tasks.
517  */
518 TASKQUEUE_DEFINE_THREAD(in6m_free);
519 static struct task in6m_free_task;
520 static struct in6_multi_head in6m_free_list = SLIST_HEAD_INITIALIZER();
521 static void in6m_release_task(void *arg __unused, int pending __unused);
522
523 static void
524 in6m_init(void *arg __unused)
525 {
526         TASK_INIT(&in6m_free_task, 0, in6m_release_task, NULL);
527 }
528 SYSINIT(in6m_init, SI_SUB_TASKQ, SI_ORDER_ANY, in6m_init, NULL);
529
530 void
531 in6m_release_list_deferred(struct in6_multi_head *inmh)
532 {
533         if (SLIST_EMPTY(inmh))
534                 return;
535         mtx_lock(&in6_multi_free_mtx);
536         SLIST_CONCAT(&in6m_free_list, inmh, in6_multi, in6m_nrele);
537         mtx_unlock(&in6_multi_free_mtx);
538         taskqueue_enqueue(taskqueue_in6m_free, &in6m_free_task);
539 }
540
541 void
542 in6m_release_wait(void)
543 {
544         taskqueue_drain_all(taskqueue_in6m_free);
545 }
546
547 void
548 in6m_disconnect_locked(struct in6_multi_head *inmh, struct in6_multi *inm)
549 {
550         struct ifnet *ifp;
551         struct ifaddr *ifa;
552         struct in6_ifaddr *ifa6;
553         struct in6_multi_mship *imm, *imm_tmp;
554         struct ifmultiaddr *ifma, *ll_ifma;
555
556         IN6_MULTI_LIST_LOCK_ASSERT();
557
558         ifp = inm->in6m_ifp;
559         if (ifp == NULL)
560                 return;         /* already called */
561
562         inm->in6m_ifp = NULL;
563         IF_ADDR_WLOCK_ASSERT(ifp);
564         ifma = inm->in6m_ifma;
565         if (ifma == NULL)
566                 return;
567
568         if_ref(ifp);
569         if (ifma->ifma_flags & IFMA_F_ENQUEUED) {
570                 CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifmultiaddr, ifma_link);
571                 ifma->ifma_flags &= ~IFMA_F_ENQUEUED;
572         }
573         MCDPRINTF("removed ifma: %p from %s\n", ifma, ifp->if_xname);
574         if ((ll_ifma = ifma->ifma_llifma) != NULL) {
575                 MPASS(ifma != ll_ifma);
576                 ifma->ifma_llifma = NULL;
577                 MPASS(ll_ifma->ifma_llifma == NULL);
578                 MPASS(ll_ifma->ifma_ifp == ifp);
579                 if (--ll_ifma->ifma_refcount == 0) {
580                         if (ll_ifma->ifma_flags & IFMA_F_ENQUEUED) {
581                                 CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma, ifmultiaddr, ifma_link);
582                                 ll_ifma->ifma_flags &= ~IFMA_F_ENQUEUED;
583                         }
584                         MCDPRINTF("removed ll_ifma: %p from %s\n", ll_ifma, ifp->if_xname);
585                         if_freemulti(ll_ifma);
586                 }
587         }
588         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
589                 if (ifa->ifa_addr->sa_family != AF_INET6)
590                         continue;
591                 ifa6 = (void *)ifa;
592                 LIST_FOREACH_SAFE(imm, &ifa6->ia6_memberships,
593                     i6mm_chain, imm_tmp) {
594                         if (inm == imm->i6mm_maddr) {
595                                 LIST_REMOVE(imm, i6mm_chain);
596                                 free(imm, M_IP6MADDR);
597                                 in6m_rele_locked(inmh, inm);
598                         }
599                 }
600         }
601 }
602
603 static void
604 in6m_release_task(void *arg __unused, int pending __unused)
605 {
606         struct in6_multi_head in6m_free_tmp;
607         struct in6_multi *inm, *tinm;
608
609         SLIST_INIT(&in6m_free_tmp);
610         mtx_lock(&in6_multi_free_mtx);
611         SLIST_CONCAT(&in6m_free_tmp, &in6m_free_list, in6_multi, in6m_nrele);
612         mtx_unlock(&in6_multi_free_mtx);
613         IN6_MULTI_LOCK();
614         SLIST_FOREACH_SAFE(inm, &in6m_free_tmp, in6m_nrele, tinm) {
615                 SLIST_REMOVE_HEAD(&in6m_free_tmp, in6m_nrele);
616                 in6m_release(inm);
617         }
618         IN6_MULTI_UNLOCK();
619 }
620
621 /*
622  * Clear recorded source entries for a group.
623  * Used by the MLD code. Caller must hold the IN6_MULTI lock.
624  * FIXME: Should reap.
625  */
626 void
627 in6m_clear_recorded(struct in6_multi *inm)
628 {
629         struct ip6_msource      *ims;
630
631         IN6_MULTI_LIST_LOCK_ASSERT();
632
633         RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
634                 if (ims->im6s_stp) {
635                         ims->im6s_stp = 0;
636                         --inm->in6m_st[1].iss_rec;
637                 }
638         }
639         KASSERT(inm->in6m_st[1].iss_rec == 0,
640             ("%s: iss_rec %d not 0", __func__, inm->in6m_st[1].iss_rec));
641 }
642
643 /*
644  * Record a source as pending for a Source-Group MLDv2 query.
645  * This lives here as it modifies the shared tree.
646  *
647  * inm is the group descriptor.
648  * naddr is the address of the source to record in network-byte order.
649  *
650  * If the net.inet6.mld.sgalloc sysctl is non-zero, we will
651  * lazy-allocate a source node in response to an SG query.
652  * Otherwise, no allocation is performed. This saves some memory
653  * with the trade-off that the source will not be reported to the
654  * router if joined in the window between the query response and
655  * the group actually being joined on the local host.
656  *
657  * VIMAGE: XXX: Currently the mld_sgalloc feature has been removed.
658  * This turns off the allocation of a recorded source entry if
659  * the group has not been joined.
660  *
661  * Return 0 if the source didn't exist or was already marked as recorded.
662  * Return 1 if the source was marked as recorded by this function.
663  * Return <0 if any error occurred (negated errno code).
664  */
665 int
666 in6m_record_source(struct in6_multi *inm, const struct in6_addr *addr)
667 {
668         struct ip6_msource       find;
669         struct ip6_msource      *ims, *nims;
670
671         IN6_MULTI_LIST_LOCK_ASSERT();
672
673         find.im6s_addr = *addr;
674         ims = RB_FIND(ip6_msource_tree, &inm->in6m_srcs, &find);
675         if (ims && ims->im6s_stp)
676                 return (0);
677         if (ims == NULL) {
678                 if (inm->in6m_nsrc == in6_mcast_maxgrpsrc)
679                         return (-ENOSPC);
680                 nims = malloc(sizeof(struct ip6_msource), M_IP6MSOURCE,
681                     M_NOWAIT | M_ZERO);
682                 if (nims == NULL)
683                         return (-ENOMEM);
684                 nims->im6s_addr = find.im6s_addr;
685                 RB_INSERT(ip6_msource_tree, &inm->in6m_srcs, nims);
686                 ++inm->in6m_nsrc;
687                 ims = nims;
688         }
689
690         /*
691          * Mark the source as recorded and update the recorded
692          * source count.
693          */
694         ++ims->im6s_stp;
695         ++inm->in6m_st[1].iss_rec;
696
697         return (1);
698 }
699
700 /*
701  * Return a pointer to an in6_msource owned by an in6_mfilter,
702  * given its source address.
703  * Lazy-allocate if needed. If this is a new entry its filter state is
704  * undefined at t0.
705  *
706  * imf is the filter set being modified.
707  * addr is the source address.
708  *
709  * SMPng: May be called with locks held; malloc must not block.
710  */
711 static int
712 im6f_get_source(struct in6_mfilter *imf, const struct sockaddr_in6 *psin,
713     struct in6_msource **plims)
714 {
715         struct ip6_msource       find;
716         struct ip6_msource      *ims, *nims;
717         struct in6_msource      *lims;
718         int                      error;
719
720         error = 0;
721         ims = NULL;
722         lims = NULL;
723
724         find.im6s_addr = psin->sin6_addr;
725         ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
726         lims = (struct in6_msource *)ims;
727         if (lims == NULL) {
728                 if (imf->im6f_nsrc == in6_mcast_maxsocksrc)
729                         return (ENOSPC);
730                 nims = malloc(sizeof(struct in6_msource), M_IN6MFILTER,
731                     M_NOWAIT | M_ZERO);
732                 if (nims == NULL)
733                         return (ENOMEM);
734                 lims = (struct in6_msource *)nims;
735                 lims->im6s_addr = find.im6s_addr;
736                 lims->im6sl_st[0] = MCAST_UNDEFINED;
737                 RB_INSERT(ip6_msource_tree, &imf->im6f_sources, nims);
738                 ++imf->im6f_nsrc;
739         }
740
741         *plims = lims;
742
743         return (error);
744 }
745
746 /*
747  * Graft a source entry into an existing socket-layer filter set,
748  * maintaining any required invariants and checking allocations.
749  *
750  * The source is marked as being in the new filter mode at t1.
751  *
752  * Return the pointer to the new node, otherwise return NULL.
753  */
754 static struct in6_msource *
755 im6f_graft(struct in6_mfilter *imf, const uint8_t st1,
756     const struct sockaddr_in6 *psin)
757 {
758         struct ip6_msource      *nims;
759         struct in6_msource      *lims;
760
761         nims = malloc(sizeof(struct in6_msource), M_IN6MFILTER,
762             M_NOWAIT | M_ZERO);
763         if (nims == NULL)
764                 return (NULL);
765         lims = (struct in6_msource *)nims;
766         lims->im6s_addr = psin->sin6_addr;
767         lims->im6sl_st[0] = MCAST_UNDEFINED;
768         lims->im6sl_st[1] = st1;
769         RB_INSERT(ip6_msource_tree, &imf->im6f_sources, nims);
770         ++imf->im6f_nsrc;
771
772         return (lims);
773 }
774
775 /*
776  * Prune a source entry from an existing socket-layer filter set,
777  * maintaining any required invariants and checking allocations.
778  *
779  * The source is marked as being left at t1, it is not freed.
780  *
781  * Return 0 if no error occurred, otherwise return an errno value.
782  */
783 static int
784 im6f_prune(struct in6_mfilter *imf, const struct sockaddr_in6 *psin)
785 {
786         struct ip6_msource       find;
787         struct ip6_msource      *ims;
788         struct in6_msource      *lims;
789
790         find.im6s_addr = psin->sin6_addr;
791         ims = RB_FIND(ip6_msource_tree, &imf->im6f_sources, &find);
792         if (ims == NULL)
793                 return (ENOENT);
794         lims = (struct in6_msource *)ims;
795         lims->im6sl_st[1] = MCAST_UNDEFINED;
796         return (0);
797 }
798
799 /*
800  * Revert socket-layer filter set deltas at t1 to t0 state.
801  */
802 static void
803 im6f_rollback(struct in6_mfilter *imf)
804 {
805         struct ip6_msource      *ims, *tims;
806         struct in6_msource      *lims;
807
808         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
809                 lims = (struct in6_msource *)ims;
810                 if (lims->im6sl_st[0] == lims->im6sl_st[1]) {
811                         /* no change at t1 */
812                         continue;
813                 } else if (lims->im6sl_st[0] != MCAST_UNDEFINED) {
814                         /* revert change to existing source at t1 */
815                         lims->im6sl_st[1] = lims->im6sl_st[0];
816                 } else {
817                         /* revert source added t1 */
818                         CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
819                         RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
820                         free(ims, M_IN6MFILTER);
821                         imf->im6f_nsrc--;
822                 }
823         }
824         imf->im6f_st[1] = imf->im6f_st[0];
825 }
826
827 /*
828  * Mark socket-layer filter set as INCLUDE {} at t1.
829  */
830 static void
831 im6f_leave(struct in6_mfilter *imf)
832 {
833         struct ip6_msource      *ims;
834         struct in6_msource      *lims;
835
836         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
837                 lims = (struct in6_msource *)ims;
838                 lims->im6sl_st[1] = MCAST_UNDEFINED;
839         }
840         imf->im6f_st[1] = MCAST_INCLUDE;
841 }
842
843 /*
844  * Mark socket-layer filter set deltas as committed.
845  */
846 static void
847 im6f_commit(struct in6_mfilter *imf)
848 {
849         struct ip6_msource      *ims;
850         struct in6_msource      *lims;
851
852         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
853                 lims = (struct in6_msource *)ims;
854                 lims->im6sl_st[0] = lims->im6sl_st[1];
855         }
856         imf->im6f_st[0] = imf->im6f_st[1];
857 }
858
859 /*
860  * Reap unreferenced sources from socket-layer filter set.
861  */
862 static void
863 im6f_reap(struct in6_mfilter *imf)
864 {
865         struct ip6_msource      *ims, *tims;
866         struct in6_msource      *lims;
867
868         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
869                 lims = (struct in6_msource *)ims;
870                 if ((lims->im6sl_st[0] == MCAST_UNDEFINED) &&
871                     (lims->im6sl_st[1] == MCAST_UNDEFINED)) {
872                         CTR2(KTR_MLD, "%s: free lims %p", __func__, ims);
873                         RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
874                         free(ims, M_IN6MFILTER);
875                         imf->im6f_nsrc--;
876                 }
877         }
878 }
879
880 /*
881  * Purge socket-layer filter set.
882  */
883 static void
884 im6f_purge(struct in6_mfilter *imf)
885 {
886         struct ip6_msource      *ims, *tims;
887
888         RB_FOREACH_SAFE(ims, ip6_msource_tree, &imf->im6f_sources, tims) {
889                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
890                 RB_REMOVE(ip6_msource_tree, &imf->im6f_sources, ims);
891                 free(ims, M_IN6MFILTER);
892                 imf->im6f_nsrc--;
893         }
894         imf->im6f_st[0] = imf->im6f_st[1] = MCAST_UNDEFINED;
895         KASSERT(RB_EMPTY(&imf->im6f_sources),
896             ("%s: im6f_sources not empty", __func__));
897 }
898
899 /*
900  * Look up a source filter entry for a multicast group.
901  *
902  * inm is the group descriptor to work with.
903  * addr is the IPv6 address to look up.
904  * noalloc may be non-zero to suppress allocation of sources.
905  * *pims will be set to the address of the retrieved or allocated source.
906  *
907  * SMPng: NOTE: may be called with locks held.
908  * Return 0 if successful, otherwise return a non-zero error code.
909  */
910 static int
911 in6m_get_source(struct in6_multi *inm, const struct in6_addr *addr,
912     const int noalloc, struct ip6_msource **pims)
913 {
914         struct ip6_msource       find;
915         struct ip6_msource      *ims, *nims;
916 #ifdef KTR
917         char                     ip6tbuf[INET6_ADDRSTRLEN];
918 #endif
919
920         find.im6s_addr = *addr;
921         ims = RB_FIND(ip6_msource_tree, &inm->in6m_srcs, &find);
922         if (ims == NULL && !noalloc) {
923                 if (inm->in6m_nsrc == in6_mcast_maxgrpsrc)
924                         return (ENOSPC);
925                 nims = malloc(sizeof(struct ip6_msource), M_IP6MSOURCE,
926                     M_NOWAIT | M_ZERO);
927                 if (nims == NULL)
928                         return (ENOMEM);
929                 nims->im6s_addr = *addr;
930                 RB_INSERT(ip6_msource_tree, &inm->in6m_srcs, nims);
931                 ++inm->in6m_nsrc;
932                 ims = nims;
933                 CTR3(KTR_MLD, "%s: allocated %s as %p", __func__,
934                     ip6_sprintf(ip6tbuf, addr), ims);
935         }
936
937         *pims = ims;
938         return (0);
939 }
940
941 /*
942  * Merge socket-layer source into MLD-layer source.
943  * If rollback is non-zero, perform the inverse of the merge.
944  */
945 static void
946 im6s_merge(struct ip6_msource *ims, const struct in6_msource *lims,
947     const int rollback)
948 {
949         int n = rollback ? -1 : 1;
950 #ifdef KTR
951         char ip6tbuf[INET6_ADDRSTRLEN];
952
953         ip6_sprintf(ip6tbuf, &lims->im6s_addr);
954 #endif
955
956         if (lims->im6sl_st[0] == MCAST_EXCLUDE) {
957                 CTR3(KTR_MLD, "%s: t1 ex -= %d on %s", __func__, n, ip6tbuf);
958                 ims->im6s_st[1].ex -= n;
959         } else if (lims->im6sl_st[0] == MCAST_INCLUDE) {
960                 CTR3(KTR_MLD, "%s: t1 in -= %d on %s", __func__, n, ip6tbuf);
961                 ims->im6s_st[1].in -= n;
962         }
963
964         if (lims->im6sl_st[1] == MCAST_EXCLUDE) {
965                 CTR3(KTR_MLD, "%s: t1 ex += %d on %s", __func__, n, ip6tbuf);
966                 ims->im6s_st[1].ex += n;
967         } else if (lims->im6sl_st[1] == MCAST_INCLUDE) {
968                 CTR3(KTR_MLD, "%s: t1 in += %d on %s", __func__, n, ip6tbuf);
969                 ims->im6s_st[1].in += n;
970         }
971 }
972
973 /*
974  * Atomically update the global in6_multi state, when a membership's
975  * filter list is being updated in any way.
976  *
977  * imf is the per-inpcb-membership group filter pointer.
978  * A fake imf may be passed for in-kernel consumers.
979  *
980  * XXX This is a candidate for a set-symmetric-difference style loop
981  * which would eliminate the repeated lookup from root of ims nodes,
982  * as they share the same key space.
983  *
984  * If any error occurred this function will back out of refcounts
985  * and return a non-zero value.
986  */
987 static int
988 in6m_merge(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
989 {
990         struct ip6_msource      *ims, *nims;
991         struct in6_msource      *lims;
992         int                      schanged, error;
993         int                      nsrc0, nsrc1;
994
995         schanged = 0;
996         error = 0;
997         nsrc1 = nsrc0 = 0;
998         IN6_MULTI_LIST_LOCK_ASSERT();
999
1000         /*
1001          * Update the source filters first, as this may fail.
1002          * Maintain count of in-mode filters at t0, t1. These are
1003          * used to work out if we transition into ASM mode or not.
1004          * Maintain a count of source filters whose state was
1005          * actually modified by this operation.
1006          */
1007         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
1008                 lims = (struct in6_msource *)ims;
1009                 if (lims->im6sl_st[0] == imf->im6f_st[0]) nsrc0++;
1010                 if (lims->im6sl_st[1] == imf->im6f_st[1]) nsrc1++;
1011                 if (lims->im6sl_st[0] == lims->im6sl_st[1]) continue;
1012                 error = in6m_get_source(inm, &lims->im6s_addr, 0, &nims);
1013                 ++schanged;
1014                 if (error)
1015                         break;
1016                 im6s_merge(nims, lims, 0);
1017         }
1018         if (error) {
1019                 struct ip6_msource *bims;
1020
1021                 RB_FOREACH_REVERSE_FROM(ims, ip6_msource_tree, nims) {
1022                         lims = (struct in6_msource *)ims;
1023                         if (lims->im6sl_st[0] == lims->im6sl_st[1])
1024                                 continue;
1025                         (void)in6m_get_source(inm, &lims->im6s_addr, 1, &bims);
1026                         if (bims == NULL)
1027                                 continue;
1028                         im6s_merge(bims, lims, 1);
1029                 }
1030                 goto out_reap;
1031         }
1032
1033         CTR3(KTR_MLD, "%s: imf filters in-mode: %d at t0, %d at t1",
1034             __func__, nsrc0, nsrc1);
1035
1036         /* Handle transition between INCLUDE {n} and INCLUDE {} on socket. */
1037         if (imf->im6f_st[0] == imf->im6f_st[1] &&
1038             imf->im6f_st[1] == MCAST_INCLUDE) {
1039                 if (nsrc1 == 0) {
1040                         CTR1(KTR_MLD, "%s: --in on inm at t1", __func__);
1041                         --inm->in6m_st[1].iss_in;
1042                 }
1043         }
1044
1045         /* Handle filter mode transition on socket. */
1046         if (imf->im6f_st[0] != imf->im6f_st[1]) {
1047                 CTR3(KTR_MLD, "%s: imf transition %d to %d",
1048                     __func__, imf->im6f_st[0], imf->im6f_st[1]);
1049
1050                 if (imf->im6f_st[0] == MCAST_EXCLUDE) {
1051                         CTR1(KTR_MLD, "%s: --ex on inm at t1", __func__);
1052                         --inm->in6m_st[1].iss_ex;
1053                 } else if (imf->im6f_st[0] == MCAST_INCLUDE) {
1054                         CTR1(KTR_MLD, "%s: --in on inm at t1", __func__);
1055                         --inm->in6m_st[1].iss_in;
1056                 }
1057
1058                 if (imf->im6f_st[1] == MCAST_EXCLUDE) {
1059                         CTR1(KTR_MLD, "%s: ex++ on inm at t1", __func__);
1060                         inm->in6m_st[1].iss_ex++;
1061                 } else if (imf->im6f_st[1] == MCAST_INCLUDE && nsrc1 > 0) {
1062                         CTR1(KTR_MLD, "%s: in++ on inm at t1", __func__);
1063                         inm->in6m_st[1].iss_in++;
1064                 }
1065         }
1066
1067         /*
1068          * Track inm filter state in terms of listener counts.
1069          * If there are any exclusive listeners, stack-wide
1070          * membership is exclusive.
1071          * Otherwise, if only inclusive listeners, stack-wide is inclusive.
1072          * If no listeners remain, state is undefined at t1,
1073          * and the MLD lifecycle for this group should finish.
1074          */
1075         if (inm->in6m_st[1].iss_ex > 0) {
1076                 CTR1(KTR_MLD, "%s: transition to EX", __func__);
1077                 inm->in6m_st[1].iss_fmode = MCAST_EXCLUDE;
1078         } else if (inm->in6m_st[1].iss_in > 0) {
1079                 CTR1(KTR_MLD, "%s: transition to IN", __func__);
1080                 inm->in6m_st[1].iss_fmode = MCAST_INCLUDE;
1081         } else {
1082                 CTR1(KTR_MLD, "%s: transition to UNDEF", __func__);
1083                 inm->in6m_st[1].iss_fmode = MCAST_UNDEFINED;
1084         }
1085
1086         /* Decrement ASM listener count on transition out of ASM mode. */
1087         if (imf->im6f_st[0] == MCAST_EXCLUDE && nsrc0 == 0) {
1088                 if ((imf->im6f_st[1] != MCAST_EXCLUDE) ||
1089                     (imf->im6f_st[1] == MCAST_EXCLUDE && nsrc1 > 0)) {
1090                         CTR1(KTR_MLD, "%s: --asm on inm at t1", __func__);
1091                         --inm->in6m_st[1].iss_asm;
1092                 }
1093         }
1094
1095         /* Increment ASM listener count on transition to ASM mode. */
1096         if (imf->im6f_st[1] == MCAST_EXCLUDE && nsrc1 == 0) {
1097                 CTR1(KTR_MLD, "%s: asm++ on inm at t1", __func__);
1098                 inm->in6m_st[1].iss_asm++;
1099         }
1100
1101         CTR3(KTR_MLD, "%s: merged imf %p to inm %p", __func__, imf, inm);
1102         in6m_print(inm);
1103
1104 out_reap:
1105         if (schanged > 0) {
1106                 CTR1(KTR_MLD, "%s: sources changed; reaping", __func__);
1107                 in6m_reap(inm);
1108         }
1109         return (error);
1110 }
1111
1112 /*
1113  * Mark an in6_multi's filter set deltas as committed.
1114  * Called by MLD after a state change has been enqueued.
1115  */
1116 void
1117 in6m_commit(struct in6_multi *inm)
1118 {
1119         struct ip6_msource      *ims;
1120
1121         CTR2(KTR_MLD, "%s: commit inm %p", __func__, inm);
1122         CTR1(KTR_MLD, "%s: pre commit:", __func__);
1123         in6m_print(inm);
1124
1125         RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
1126                 ims->im6s_st[0] = ims->im6s_st[1];
1127         }
1128         inm->in6m_st[0] = inm->in6m_st[1];
1129 }
1130
1131 /*
1132  * Reap unreferenced nodes from an in6_multi's filter set.
1133  */
1134 static void
1135 in6m_reap(struct in6_multi *inm)
1136 {
1137         struct ip6_msource      *ims, *tims;
1138
1139         RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs, tims) {
1140                 if (ims->im6s_st[0].ex > 0 || ims->im6s_st[0].in > 0 ||
1141                     ims->im6s_st[1].ex > 0 || ims->im6s_st[1].in > 0 ||
1142                     ims->im6s_stp != 0)
1143                         continue;
1144                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
1145                 RB_REMOVE(ip6_msource_tree, &inm->in6m_srcs, ims);
1146                 free(ims, M_IP6MSOURCE);
1147                 inm->in6m_nsrc--;
1148         }
1149 }
1150
1151 /*
1152  * Purge all source nodes from an in6_multi's filter set.
1153  */
1154 static void
1155 in6m_purge(struct in6_multi *inm)
1156 {
1157         struct ip6_msource      *ims, *tims;
1158
1159         RB_FOREACH_SAFE(ims, ip6_msource_tree, &inm->in6m_srcs, tims) {
1160                 CTR2(KTR_MLD, "%s: free ims %p", __func__, ims);
1161                 RB_REMOVE(ip6_msource_tree, &inm->in6m_srcs, ims);
1162                 free(ims, M_IP6MSOURCE);
1163                 inm->in6m_nsrc--;
1164         }
1165         /* Free state-change requests that might be queued. */
1166         mbufq_drain(&inm->in6m_scq);
1167 }
1168
1169 /*
1170  * Join a multicast address w/o sources.
1171  * KAME compatibility entry point.
1172  *
1173  * SMPng: Assume no mc locks held by caller.
1174  */
1175 int
1176 in6_joingroup(struct ifnet *ifp, const struct in6_addr *mcaddr,
1177     /*const*/ struct in6_mfilter *imf, struct in6_multi **pinm,
1178     const int delay)
1179 {
1180         int error;
1181
1182         IN6_MULTI_LOCK();
1183         error = in6_joingroup_locked(ifp, mcaddr, NULL, pinm, delay);
1184         IN6_MULTI_UNLOCK();
1185         return (error);
1186 }
1187
1188 /*
1189  * Join a multicast group; real entry point.
1190  *
1191  * Only preserves atomicity at inm level.
1192  * NOTE: imf argument cannot be const due to sys/tree.h limitations.
1193  *
1194  * If the MLD downcall fails, the group is not joined, and an error
1195  * code is returned.
1196  */
1197 static int
1198 in6_joingroup_locked(struct ifnet *ifp, const struct in6_addr *mcaddr,
1199     /*const*/ struct in6_mfilter *imf, struct in6_multi **pinm,
1200     const int delay)
1201 {
1202         struct in6_multi_head    inmh;
1203         struct in6_mfilter       timf;
1204         struct in6_multi        *inm;
1205         struct ifmultiaddr *ifma;
1206         int                      error;
1207 #ifdef KTR
1208         char                     ip6tbuf[INET6_ADDRSTRLEN];
1209 #endif
1210
1211         /*
1212          * Sanity: Check scope zone ID was set for ifp, if and
1213          * only if group is scoped to an interface.
1214          */
1215         KASSERT(IN6_IS_ADDR_MULTICAST(mcaddr),
1216             ("%s: not a multicast address", __func__));
1217         if (IN6_IS_ADDR_MC_LINKLOCAL(mcaddr) ||
1218             IN6_IS_ADDR_MC_INTFACELOCAL(mcaddr)) {
1219                 KASSERT(mcaddr->s6_addr16[1] != 0,
1220                     ("%s: scope zone ID not set", __func__));
1221         }
1222
1223         IN6_MULTI_LOCK_ASSERT();
1224         IN6_MULTI_LIST_UNLOCK_ASSERT();
1225
1226         CTR4(KTR_MLD, "%s: join %s on %p(%s))", __func__,
1227             ip6_sprintf(ip6tbuf, mcaddr), ifp, if_name(ifp));
1228
1229         error = 0;
1230         inm = NULL;
1231
1232         /*
1233          * If no imf was specified (i.e. kernel consumer),
1234          * fake one up and assume it is an ASM join.
1235          */
1236         if (imf == NULL) {
1237                 im6f_init(&timf, MCAST_UNDEFINED, MCAST_EXCLUDE);
1238                 imf = &timf;
1239         }
1240         error = in6_getmulti(ifp, mcaddr, &inm);
1241         if (error) {
1242                 CTR1(KTR_MLD, "%s: in6_getmulti() failure", __func__);
1243                 return (error);
1244         }
1245
1246         IN6_MULTI_LIST_LOCK();
1247         CTR1(KTR_MLD, "%s: merge inm state", __func__);
1248         error = in6m_merge(inm, imf);
1249         if (error) {
1250                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
1251                 goto out_in6m_release;
1252         }
1253
1254         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
1255         error = mld_change_state(inm, delay);
1256         if (error) {
1257                 CTR1(KTR_MLD, "%s: failed to update source", __func__);
1258                 goto out_in6m_release;
1259         }
1260
1261 out_in6m_release:
1262         SLIST_INIT(&inmh);
1263         if (error) {
1264                 struct epoch_tracker et;
1265
1266                 CTR2(KTR_MLD, "%s: dropping ref on %p", __func__, inm);
1267                 IF_ADDR_WLOCK(ifp);
1268                 NET_EPOCH_ENTER(et);
1269                 CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1270                         if (ifma->ifma_protospec == inm) {
1271                                 ifma->ifma_protospec = NULL;
1272                                 break;
1273                         }
1274                 }
1275                 in6m_disconnect_locked(&inmh, inm);
1276                 in6m_rele_locked(&inmh, inm);
1277                 NET_EPOCH_EXIT(et);
1278                 IF_ADDR_WUNLOCK(ifp);
1279         } else {
1280                 *pinm = inm;
1281         }
1282         IN6_MULTI_LIST_UNLOCK();
1283         in6m_release_list_deferred(&inmh);
1284         return (error);
1285 }
1286
1287 /*
1288  * Leave a multicast group; unlocked entry point.
1289  */
1290 int
1291 in6_leavegroup(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
1292 {
1293         int error;
1294
1295         IN6_MULTI_LOCK();
1296         error = in6_leavegroup_locked(inm, imf);
1297         IN6_MULTI_UNLOCK();
1298         return (error);
1299 }
1300
1301 /*
1302  * Leave a multicast group; real entry point.
1303  * All source filters will be expunged.
1304  *
1305  * Only preserves atomicity at inm level.
1306  *
1307  * Holding the write lock for the INP which contains imf
1308  * is highly advisable. We can't assert for it as imf does not
1309  * contain a back-pointer to the owning inp.
1310  *
1311  * Note: This is not the same as in6m_release(*) as this function also
1312  * makes a state change downcall into MLD.
1313  */
1314 int
1315 in6_leavegroup_locked(struct in6_multi *inm, /*const*/ struct in6_mfilter *imf)
1316 {
1317         struct in6_multi_head    inmh;
1318         struct in6_mfilter       timf;
1319         struct ifnet *ifp;
1320         int                      error;
1321 #ifdef KTR
1322         char                     ip6tbuf[INET6_ADDRSTRLEN];
1323 #endif
1324
1325         error = 0;
1326
1327         IN6_MULTI_LOCK_ASSERT();
1328
1329         CTR5(KTR_MLD, "%s: leave inm %p, %s/%s, imf %p", __func__,
1330             inm, ip6_sprintf(ip6tbuf, &inm->in6m_addr),
1331             (in6m_is_ifp_detached(inm) ? "null" : if_name(inm->in6m_ifp)),
1332             imf);
1333
1334         /*
1335          * If no imf was specified (i.e. kernel consumer),
1336          * fake one up and assume it is an ASM join.
1337          */
1338         if (imf == NULL) {
1339                 im6f_init(&timf, MCAST_EXCLUDE, MCAST_UNDEFINED);
1340                 imf = &timf;
1341         }
1342
1343         /*
1344          * Begin state merge transaction at MLD layer.
1345          *
1346          * As this particular invocation should not cause any memory
1347          * to be allocated, and there is no opportunity to roll back
1348          * the transaction, it MUST NOT fail.
1349          */
1350
1351         ifp = inm->in6m_ifp;
1352         IN6_MULTI_LIST_LOCK();
1353         CTR1(KTR_MLD, "%s: merge inm state", __func__);
1354         error = in6m_merge(inm, imf);
1355         KASSERT(error == 0, ("%s: failed to merge inm state", __func__));
1356
1357         CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
1358         error = 0;
1359         if (ifp)
1360                 error = mld_change_state(inm, 0);
1361         if (error)
1362                 CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
1363
1364         CTR2(KTR_MLD, "%s: dropping ref on %p", __func__, inm);
1365         if (ifp)
1366                 IF_ADDR_WLOCK(ifp);
1367
1368         SLIST_INIT(&inmh);
1369         if (inm->in6m_refcount == 1)
1370                 in6m_disconnect_locked(&inmh, inm);
1371         in6m_rele_locked(&inmh, inm);
1372         if (ifp)
1373                 IF_ADDR_WUNLOCK(ifp);
1374         IN6_MULTI_LIST_UNLOCK();
1375         in6m_release_list_deferred(&inmh);
1376         return (error);
1377 }
1378
1379
1380 /*
1381  * Block or unblock an ASM multicast source on an inpcb.
1382  * This implements the delta-based API described in RFC 3678.
1383  *
1384  * The delta-based API applies only to exclusive-mode memberships.
1385  * An MLD downcall will be performed.
1386  *
1387  * SMPng: NOTE: Must take Giant as a join may create a new ifma.
1388  *
1389  * Return 0 if successful, otherwise return an appropriate error code.
1390  */
1391 static int
1392 in6p_block_unblock_source(struct inpcb *inp, struct sockopt *sopt)
1393 {
1394         struct group_source_req          gsr;
1395         sockunion_t                     *gsa, *ssa;
1396         struct ifnet                    *ifp;
1397         struct in6_mfilter              *imf;
1398         struct ip6_moptions             *imo;
1399         struct in6_msource              *ims;
1400         struct in6_multi                        *inm;
1401         uint16_t                         fmode;
1402         int                              error, doblock;
1403 #ifdef KTR
1404         char                             ip6tbuf[INET6_ADDRSTRLEN];
1405 #endif
1406
1407         ifp = NULL;
1408         error = 0;
1409         doblock = 0;
1410
1411         memset(&gsr, 0, sizeof(struct group_source_req));
1412         gsa = (sockunion_t *)&gsr.gsr_group;
1413         ssa = (sockunion_t *)&gsr.gsr_source;
1414
1415         switch (sopt->sopt_name) {
1416         case MCAST_BLOCK_SOURCE:
1417         case MCAST_UNBLOCK_SOURCE:
1418                 error = sooptcopyin(sopt, &gsr,
1419                     sizeof(struct group_source_req),
1420                     sizeof(struct group_source_req));
1421                 if (error)
1422                         return (error);
1423
1424                 if (gsa->sin6.sin6_family != AF_INET6 ||
1425                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
1426                         return (EINVAL);
1427
1428                 if (ssa->sin6.sin6_family != AF_INET6 ||
1429                     ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
1430                         return (EINVAL);
1431
1432                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
1433                         return (EADDRNOTAVAIL);
1434
1435                 ifp = ifnet_byindex(gsr.gsr_interface);
1436
1437                 if (sopt->sopt_name == MCAST_BLOCK_SOURCE)
1438                         doblock = 1;
1439                 break;
1440
1441         default:
1442                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
1443                     __func__, sopt->sopt_name);
1444                 return (EOPNOTSUPP);
1445                 break;
1446         }
1447
1448         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
1449                 return (EINVAL);
1450
1451         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
1452
1453         /*
1454          * Check if we are actually a member of this group.
1455          */
1456         imo = in6p_findmoptions(inp);
1457         imf = im6o_match_group(imo, ifp, &gsa->sa);
1458         if (imf == NULL) {
1459                 error = EADDRNOTAVAIL;
1460                 goto out_in6p_locked;
1461         }
1462         inm = imf->im6f_in6m;
1463
1464         /*
1465          * Attempting to use the delta-based API on an
1466          * non exclusive-mode membership is an error.
1467          */
1468         fmode = imf->im6f_st[0];
1469         if (fmode != MCAST_EXCLUDE) {
1470                 error = EINVAL;
1471                 goto out_in6p_locked;
1472         }
1473
1474         /*
1475          * Deal with error cases up-front:
1476          *  Asked to block, but already blocked; or
1477          *  Asked to unblock, but nothing to unblock.
1478          * If adding a new block entry, allocate it.
1479          */
1480         ims = im6o_match_source(imf, &ssa->sa);
1481         if ((ims != NULL && doblock) || (ims == NULL && !doblock)) {
1482                 CTR3(KTR_MLD, "%s: source %s %spresent", __func__,
1483                     ip6_sprintf(ip6tbuf, &ssa->sin6.sin6_addr),
1484                     doblock ? "" : "not ");
1485                 error = EADDRNOTAVAIL;
1486                 goto out_in6p_locked;
1487         }
1488
1489         INP_WLOCK_ASSERT(inp);
1490
1491         /*
1492          * Begin state merge transaction at socket layer.
1493          */
1494         if (doblock) {
1495                 CTR2(KTR_MLD, "%s: %s source", __func__, "block");
1496                 ims = im6f_graft(imf, fmode, &ssa->sin6);
1497                 if (ims == NULL)
1498                         error = ENOMEM;
1499         } else {
1500                 CTR2(KTR_MLD, "%s: %s source", __func__, "allow");
1501                 error = im6f_prune(imf, &ssa->sin6);
1502         }
1503
1504         if (error) {
1505                 CTR1(KTR_MLD, "%s: merge imf state failed", __func__);
1506                 goto out_im6f_rollback;
1507         }
1508
1509         /*
1510          * Begin state merge transaction at MLD layer.
1511          */
1512         IN6_MULTI_LIST_LOCK();
1513         CTR1(KTR_MLD, "%s: merge inm state", __func__);
1514         error = in6m_merge(inm, imf);
1515         if (error)
1516                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
1517         else {
1518                 CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
1519                 error = mld_change_state(inm, 0);
1520                 if (error)
1521                         CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
1522         }
1523
1524         IN6_MULTI_LIST_UNLOCK();
1525
1526 out_im6f_rollback:
1527         if (error)
1528                 im6f_rollback(imf);
1529         else
1530                 im6f_commit(imf);
1531
1532         im6f_reap(imf);
1533
1534 out_in6p_locked:
1535         INP_WUNLOCK(inp);
1536         return (error);
1537 }
1538
1539 /*
1540  * Given an inpcb, return its multicast options structure pointer.  Accepts
1541  * an unlocked inpcb pointer, but will return it locked.  May sleep.
1542  *
1543  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
1544  * SMPng: NOTE: Returns with the INP write lock held.
1545  */
1546 static struct ip6_moptions *
1547 in6p_findmoptions(struct inpcb *inp)
1548 {
1549         struct ip6_moptions      *imo;
1550
1551         INP_WLOCK(inp);
1552         if (inp->in6p_moptions != NULL)
1553                 return (inp->in6p_moptions);
1554
1555         INP_WUNLOCK(inp);
1556
1557         imo = malloc(sizeof(*imo), M_IP6MOPTS, M_WAITOK);
1558
1559         imo->im6o_multicast_ifp = NULL;
1560         imo->im6o_multicast_hlim = V_ip6_defmcasthlim;
1561         imo->im6o_multicast_loop = in6_mcast_loop;
1562         STAILQ_INIT(&imo->im6o_head);
1563
1564         INP_WLOCK(inp);
1565         if (inp->in6p_moptions != NULL) {
1566                 free(imo, M_IP6MOPTS);
1567                 return (inp->in6p_moptions);
1568         }
1569         inp->in6p_moptions = imo;
1570         return (imo);
1571 }
1572
1573 /*
1574  * Discard the IPv6 multicast options (and source filters).
1575  *
1576  * SMPng: NOTE: assumes INP write lock is held.
1577  *
1578  * XXX can all be safely deferred to epoch_call
1579  *
1580  */
1581
1582 static void
1583 inp_gcmoptions(struct ip6_moptions *imo)
1584 {
1585         struct in6_mfilter *imf;
1586         struct in6_multi *inm;
1587         struct ifnet *ifp;
1588
1589         while ((imf = ip6_mfilter_first(&imo->im6o_head)) != NULL) {
1590                 ip6_mfilter_remove(&imo->im6o_head, imf);
1591
1592                 im6f_leave(imf);
1593                 if ((inm = imf->im6f_in6m) != NULL) {
1594                         if ((ifp = inm->in6m_ifp) != NULL) {
1595                                 CURVNET_SET(ifp->if_vnet);
1596                                 (void)in6_leavegroup(inm, imf);
1597                                 CURVNET_RESTORE();
1598                         } else {
1599                                 (void)in6_leavegroup(inm, imf);
1600                         }
1601                 }
1602                 ip6_mfilter_free(imf);
1603         }
1604         free(imo, M_IP6MOPTS);
1605 }
1606
1607 void
1608 ip6_freemoptions(struct ip6_moptions *imo)
1609 {
1610         if (imo == NULL)
1611                 return;
1612         inp_gcmoptions(imo);
1613 }
1614
1615 /*
1616  * Atomically get source filters on a socket for an IPv6 multicast group.
1617  * Called with INP lock held; returns with lock released.
1618  */
1619 static int
1620 in6p_get_source_filters(struct inpcb *inp, struct sockopt *sopt)
1621 {
1622         struct __msfilterreq     msfr;
1623         sockunion_t             *gsa;
1624         struct ifnet            *ifp;
1625         struct ip6_moptions     *imo;
1626         struct in6_mfilter      *imf;
1627         struct ip6_msource      *ims;
1628         struct in6_msource      *lims;
1629         struct sockaddr_in6     *psin;
1630         struct sockaddr_storage *ptss;
1631         struct sockaddr_storage *tss;
1632         int                      error;
1633         size_t                   nsrcs, ncsrcs;
1634
1635         INP_WLOCK_ASSERT(inp);
1636
1637         imo = inp->in6p_moptions;
1638         KASSERT(imo != NULL, ("%s: null ip6_moptions", __func__));
1639
1640         INP_WUNLOCK(inp);
1641
1642         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
1643             sizeof(struct __msfilterreq));
1644         if (error)
1645                 return (error);
1646
1647         if (msfr.msfr_group.ss_family != AF_INET6 ||
1648             msfr.msfr_group.ss_len != sizeof(struct sockaddr_in6))
1649                 return (EINVAL);
1650
1651         gsa = (sockunion_t *)&msfr.msfr_group;
1652         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
1653                 return (EINVAL);
1654
1655         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
1656                 return (EADDRNOTAVAIL);
1657         ifp = ifnet_byindex(msfr.msfr_ifindex);
1658         if (ifp == NULL)
1659                 return (EADDRNOTAVAIL);
1660         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
1661
1662         INP_WLOCK(inp);
1663
1664         /*
1665          * Lookup group on the socket.
1666          */
1667         imf = im6o_match_group(imo, ifp, &gsa->sa);
1668         if (imf == NULL) {
1669                 INP_WUNLOCK(inp);
1670                 return (EADDRNOTAVAIL);
1671         }
1672
1673         /*
1674          * Ignore memberships which are in limbo.
1675          */
1676         if (imf->im6f_st[1] == MCAST_UNDEFINED) {
1677                 INP_WUNLOCK(inp);
1678                 return (EAGAIN);
1679         }
1680         msfr.msfr_fmode = imf->im6f_st[1];
1681
1682         /*
1683          * If the user specified a buffer, copy out the source filter
1684          * entries to userland gracefully.
1685          * We only copy out the number of entries which userland
1686          * has asked for, but we always tell userland how big the
1687          * buffer really needs to be.
1688          */
1689         if (msfr.msfr_nsrcs > in6_mcast_maxsocksrc)
1690                 msfr.msfr_nsrcs = in6_mcast_maxsocksrc;
1691         tss = NULL;
1692         if (msfr.msfr_srcs != NULL && msfr.msfr_nsrcs > 0) {
1693                 tss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
1694                     M_TEMP, M_NOWAIT | M_ZERO);
1695                 if (tss == NULL) {
1696                         INP_WUNLOCK(inp);
1697                         return (ENOBUFS);
1698                 }
1699         }
1700
1701         /*
1702          * Count number of sources in-mode at t0.
1703          * If buffer space exists and remains, copy out source entries.
1704          */
1705         nsrcs = msfr.msfr_nsrcs;
1706         ncsrcs = 0;
1707         ptss = tss;
1708         RB_FOREACH(ims, ip6_msource_tree, &imf->im6f_sources) {
1709                 lims = (struct in6_msource *)ims;
1710                 if (lims->im6sl_st[0] == MCAST_UNDEFINED ||
1711                     lims->im6sl_st[0] != imf->im6f_st[0])
1712                         continue;
1713                 ++ncsrcs;
1714                 if (tss != NULL && nsrcs > 0) {
1715                         psin = (struct sockaddr_in6 *)ptss;
1716                         psin->sin6_family = AF_INET6;
1717                         psin->sin6_len = sizeof(struct sockaddr_in6);
1718                         psin->sin6_addr = lims->im6s_addr;
1719                         psin->sin6_port = 0;
1720                         --nsrcs;
1721                         ++ptss;
1722                 }
1723         }
1724
1725         INP_WUNLOCK(inp);
1726
1727         if (tss != NULL) {
1728                 error = copyout(tss, msfr.msfr_srcs,
1729                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
1730                 free(tss, M_TEMP);
1731                 if (error)
1732                         return (error);
1733         }
1734
1735         msfr.msfr_nsrcs = ncsrcs;
1736         error = sooptcopyout(sopt, &msfr, sizeof(struct __msfilterreq));
1737
1738         return (error);
1739 }
1740
1741 /*
1742  * Return the IP multicast options in response to user getsockopt().
1743  */
1744 int
1745 ip6_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1746 {
1747         struct ip6_moptions     *im6o;
1748         int                      error;
1749         u_int                    optval;
1750
1751         INP_WLOCK(inp);
1752         im6o = inp->in6p_moptions;
1753         /*
1754          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
1755          * or is a divert socket, reject it.
1756          */
1757         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
1758             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
1759             inp->inp_socket->so_proto->pr_type != SOCK_DGRAM)) {
1760                 INP_WUNLOCK(inp);
1761                 return (EOPNOTSUPP);
1762         }
1763
1764         error = 0;
1765         switch (sopt->sopt_name) {
1766         case IPV6_MULTICAST_IF:
1767                 if (im6o == NULL || im6o->im6o_multicast_ifp == NULL) {
1768                         optval = 0;
1769                 } else {
1770                         optval = im6o->im6o_multicast_ifp->if_index;
1771                 }
1772                 INP_WUNLOCK(inp);
1773                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
1774                 break;
1775
1776         case IPV6_MULTICAST_HOPS:
1777                 if (im6o == NULL)
1778                         optval = V_ip6_defmcasthlim;
1779                 else
1780                         optval = im6o->im6o_multicast_hlim;
1781                 INP_WUNLOCK(inp);
1782                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
1783                 break;
1784
1785         case IPV6_MULTICAST_LOOP:
1786                 if (im6o == NULL)
1787                         optval = in6_mcast_loop; /* XXX VIMAGE */
1788                 else
1789                         optval = im6o->im6o_multicast_loop;
1790                 INP_WUNLOCK(inp);
1791                 error = sooptcopyout(sopt, &optval, sizeof(u_int));
1792                 break;
1793
1794         case IPV6_MSFILTER:
1795                 if (im6o == NULL) {
1796                         error = EADDRNOTAVAIL;
1797                         INP_WUNLOCK(inp);
1798                 } else {
1799                         error = in6p_get_source_filters(inp, sopt);
1800                 }
1801                 break;
1802
1803         default:
1804                 INP_WUNLOCK(inp);
1805                 error = ENOPROTOOPT;
1806                 break;
1807         }
1808
1809         INP_UNLOCK_ASSERT(inp);
1810
1811         return (error);
1812 }
1813
1814 /*
1815  * Look up the ifnet to use for a multicast group membership,
1816  * given the address of an IPv6 group.
1817  *
1818  * This routine exists to support legacy IPv6 multicast applications.
1819  *
1820  * Use the socket's current FIB number for any required FIB lookup. Look up the
1821  * group address in the unicast FIB, and use its ifp; usually, this points to
1822  * the default next-hop.  If the FIB lookup fails, return NULL.
1823  *
1824  * FUTURE: Support multiple forwarding tables for IPv6.
1825  *
1826  * Returns NULL if no ifp could be found.
1827  */
1828 static struct ifnet *
1829 in6p_lookup_mcast_ifp(const struct inpcb *inp, const struct sockaddr_in6 *gsin6)
1830 {
1831         struct nhop_object      *nh;
1832         struct in6_addr         dst;
1833         uint32_t                scopeid;
1834         uint32_t                fibnum;
1835
1836         KASSERT(gsin6->sin6_family == AF_INET6,
1837             ("%s: not AF_INET6 group", __func__));
1838
1839         in6_splitscope(&gsin6->sin6_addr, &dst, &scopeid);
1840         fibnum = inp->inp_inc.inc_fibnum;
1841         nh = fib6_lookup(fibnum, &dst, scopeid, 0, 0);
1842
1843         return (nh ? nh->nh_ifp : NULL);
1844 }
1845
1846 /*
1847  * Join an IPv6 multicast group, possibly with a source.
1848  *
1849  * FIXME: The KAME use of the unspecified address (::)
1850  * to join *all* multicast groups is currently unsupported.
1851  */
1852 static int
1853 in6p_join_group(struct inpcb *inp, struct sockopt *sopt)
1854 {
1855         struct in6_multi_head            inmh;
1856         struct group_source_req          gsr;
1857         sockunion_t                     *gsa, *ssa;
1858         struct ifnet                    *ifp;
1859         struct in6_mfilter              *imf;
1860         struct ip6_moptions             *imo;
1861         struct in6_multi                *inm;
1862         struct in6_msource              *lims;
1863         int                              error, is_new;
1864
1865         SLIST_INIT(&inmh);
1866         ifp = NULL;
1867         lims = NULL;
1868         error = 0;
1869
1870         memset(&gsr, 0, sizeof(struct group_source_req));
1871         gsa = (sockunion_t *)&gsr.gsr_group;
1872         gsa->ss.ss_family = AF_UNSPEC;
1873         ssa = (sockunion_t *)&gsr.gsr_source;
1874         ssa->ss.ss_family = AF_UNSPEC;
1875
1876         /*
1877          * Chew everything into struct group_source_req.
1878          * Overwrite the port field if present, as the sockaddr
1879          * being copied in may be matched with a binary comparison.
1880          * Ignore passed-in scope ID.
1881          */
1882         switch (sopt->sopt_name) {
1883         case IPV6_JOIN_GROUP: {
1884                 struct ipv6_mreq mreq;
1885
1886                 error = sooptcopyin(sopt, &mreq, sizeof(struct ipv6_mreq),
1887                     sizeof(struct ipv6_mreq));
1888                 if (error)
1889                         return (error);
1890
1891                 gsa->sin6.sin6_family = AF_INET6;
1892                 gsa->sin6.sin6_len = sizeof(struct sockaddr_in6);
1893                 gsa->sin6.sin6_addr = mreq.ipv6mr_multiaddr;
1894
1895                 if (mreq.ipv6mr_interface == 0) {
1896                         ifp = in6p_lookup_mcast_ifp(inp, &gsa->sin6);
1897                 } else {
1898                         if (V_if_index < mreq.ipv6mr_interface)
1899                                 return (EADDRNOTAVAIL);
1900                         ifp = ifnet_byindex(mreq.ipv6mr_interface);
1901                 }
1902                 CTR3(KTR_MLD, "%s: ipv6mr_interface = %d, ifp = %p",
1903                     __func__, mreq.ipv6mr_interface, ifp);
1904         } break;
1905
1906         case MCAST_JOIN_GROUP:
1907         case MCAST_JOIN_SOURCE_GROUP:
1908                 if (sopt->sopt_name == MCAST_JOIN_GROUP) {
1909                         error = sooptcopyin(sopt, &gsr,
1910                             sizeof(struct group_req),
1911                             sizeof(struct group_req));
1912                 } else if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
1913                         error = sooptcopyin(sopt, &gsr,
1914                             sizeof(struct group_source_req),
1915                             sizeof(struct group_source_req));
1916                 }
1917                 if (error)
1918                         return (error);
1919
1920                 if (gsa->sin6.sin6_family != AF_INET6 ||
1921                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
1922                         return (EINVAL);
1923
1924                 if (sopt->sopt_name == MCAST_JOIN_SOURCE_GROUP) {
1925                         if (ssa->sin6.sin6_family != AF_INET6 ||
1926                             ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
1927                                 return (EINVAL);
1928                         if (IN6_IS_ADDR_MULTICAST(&ssa->sin6.sin6_addr))
1929                                 return (EINVAL);
1930                         /*
1931                          * TODO: Validate embedded scope ID in source
1932                          * list entry against passed-in ifp, if and only
1933                          * if source list filter entry is iface or node local.
1934                          */
1935                         in6_clearscope(&ssa->sin6.sin6_addr);
1936                         ssa->sin6.sin6_port = 0;
1937                         ssa->sin6.sin6_scope_id = 0;
1938                 }
1939
1940                 if (gsr.gsr_interface == 0 || V_if_index < gsr.gsr_interface)
1941                         return (EADDRNOTAVAIL);
1942                 ifp = ifnet_byindex(gsr.gsr_interface);
1943                 break;
1944
1945         default:
1946                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
1947                     __func__, sopt->sopt_name);
1948                 return (EOPNOTSUPP);
1949                 break;
1950         }
1951
1952         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
1953                 return (EINVAL);
1954
1955         if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0)
1956                 return (EADDRNOTAVAIL);
1957
1958         gsa->sin6.sin6_port = 0;
1959         gsa->sin6.sin6_scope_id = 0;
1960
1961         /*
1962          * Always set the scope zone ID on memberships created from userland.
1963          * Use the passed-in ifp to do this.
1964          * XXX The in6_setscope() return value is meaningless.
1965          * XXX SCOPE6_LOCK() is taken by in6_setscope().
1966          */
1967         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
1968
1969         IN6_MULTI_LOCK();
1970
1971         /*
1972          * Find the membership in the membership list.
1973          */
1974         imo = in6p_findmoptions(inp);
1975         imf = im6o_match_group(imo, ifp, &gsa->sa);
1976         if (imf == NULL) {
1977                 is_new = 1;
1978                 inm = NULL;
1979
1980                 if (ip6_mfilter_count(&imo->im6o_head) >= IPV6_MAX_MEMBERSHIPS) {
1981                         error = ENOMEM;
1982                         goto out_in6p_locked;
1983                 }
1984         } else {
1985                 is_new = 0;
1986                 inm = imf->im6f_in6m;
1987
1988                 if (ssa->ss.ss_family != AF_UNSPEC) {
1989                         /*
1990                          * MCAST_JOIN_SOURCE_GROUP on an exclusive membership
1991                          * is an error. On an existing inclusive membership,
1992                          * it just adds the source to the filter list.
1993                          */
1994                         if (imf->im6f_st[1] != MCAST_INCLUDE) {
1995                                 error = EINVAL;
1996                                 goto out_in6p_locked;
1997                         }
1998                         /*
1999                          * Throw out duplicates.
2000                          *
2001                          * XXX FIXME: This makes a naive assumption that
2002                          * even if entries exist for *ssa in this imf,
2003                          * they will be rejected as dupes, even if they
2004                          * are not valid in the current mode (in-mode).
2005                          *
2006                          * in6_msource is transactioned just as for anything
2007                          * else in SSM -- but note naive use of in6m_graft()
2008                          * below for allocating new filter entries.
2009                          *
2010                          * This is only an issue if someone mixes the
2011                          * full-state SSM API with the delta-based API,
2012                          * which is discouraged in the relevant RFCs.
2013                          */
2014                         lims = im6o_match_source(imf, &ssa->sa);
2015                         if (lims != NULL /*&&
2016                             lims->im6sl_st[1] == MCAST_INCLUDE*/) {
2017                                 error = EADDRNOTAVAIL;
2018                                 goto out_in6p_locked;
2019                         }
2020                 } else {
2021                         /*
2022                          * MCAST_JOIN_GROUP alone, on any existing membership,
2023                          * is rejected, to stop the same inpcb tying up
2024                          * multiple refs to the in_multi.
2025                          * On an existing inclusive membership, this is also
2026                          * an error; if you want to change filter mode,
2027                          * you must use the userland API setsourcefilter().
2028                          * XXX We don't reject this for imf in UNDEFINED
2029                          * state at t1, because allocation of a filter
2030                          * is atomic with allocation of a membership.
2031                          */
2032                         error = EINVAL;
2033                         goto out_in6p_locked;
2034                 }
2035         }
2036
2037         /*
2038          * Begin state merge transaction at socket layer.
2039          */
2040         INP_WLOCK_ASSERT(inp);
2041
2042         /*
2043          * Graft new source into filter list for this inpcb's
2044          * membership of the group. The in6_multi may not have
2045          * been allocated yet if this is a new membership, however,
2046          * the in_mfilter slot will be allocated and must be initialized.
2047          *
2048          * Note: Grafting of exclusive mode filters doesn't happen
2049          * in this path.
2050          * XXX: Should check for non-NULL lims (node exists but may
2051          * not be in-mode) for interop with full-state API.
2052          */
2053         if (ssa->ss.ss_family != AF_UNSPEC) {
2054                 /* Membership starts in IN mode */
2055                 if (is_new) {
2056                         CTR1(KTR_MLD, "%s: new join w/source", __func__);
2057                         imf = ip6_mfilter_alloc(M_NOWAIT, MCAST_UNDEFINED, MCAST_INCLUDE);
2058                         if (imf == NULL) {
2059                                 error = ENOMEM;
2060                                 goto out_in6p_locked;
2061                         }
2062                 } else {
2063                         CTR2(KTR_MLD, "%s: %s source", __func__, "allow");
2064                 }
2065                 lims = im6f_graft(imf, MCAST_INCLUDE, &ssa->sin6);
2066                 if (lims == NULL) {
2067                         CTR1(KTR_MLD, "%s: merge imf state failed",
2068                             __func__);
2069                         error = ENOMEM;
2070                         goto out_in6p_locked;
2071                 }
2072         } else {
2073                 /* No address specified; Membership starts in EX mode */
2074                 if (is_new) {
2075                         CTR1(KTR_MLD, "%s: new join w/o source", __func__);
2076                         imf = ip6_mfilter_alloc(M_NOWAIT, MCAST_UNDEFINED, MCAST_EXCLUDE);
2077                         if (imf == NULL) {
2078                                 error = ENOMEM;
2079                                 goto out_in6p_locked;
2080                         }
2081                 }
2082         }
2083
2084         /*
2085          * Begin state merge transaction at MLD layer.
2086          */
2087         if (is_new) {
2088                 in_pcbref(inp);
2089                 INP_WUNLOCK(inp);
2090
2091                 error = in6_joingroup_locked(ifp, &gsa->sin6.sin6_addr, imf,
2092                     &imf->im6f_in6m, 0);
2093
2094                 INP_WLOCK(inp);
2095                 if (in_pcbrele_wlocked(inp)) {
2096                         error = ENXIO;
2097                         goto out_in6p_unlocked;
2098                 }
2099                 if (error) {
2100                         goto out_in6p_locked;
2101                 }
2102                 /*
2103                  * NOTE: Refcount from in6_joingroup_locked()
2104                  * is protecting membership.
2105                  */
2106                 ip6_mfilter_insert(&imo->im6o_head, imf);
2107         } else {
2108                 CTR1(KTR_MLD, "%s: merge inm state", __func__);
2109                 IN6_MULTI_LIST_LOCK();
2110                 error = in6m_merge(inm, imf);
2111                 if (error) {
2112                         CTR1(KTR_MLD, "%s: failed to merge inm state",
2113                             __func__);
2114                         IN6_MULTI_LIST_UNLOCK();
2115                         im6f_rollback(imf);
2116                         im6f_reap(imf);
2117                         goto out_in6p_locked;
2118                 }
2119                 CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
2120                 error = mld_change_state(inm, 0);
2121                 IN6_MULTI_LIST_UNLOCK();
2122
2123                 if (error) {
2124                         CTR1(KTR_MLD, "%s: failed mld downcall",
2125                              __func__);
2126                         im6f_rollback(imf);
2127                         im6f_reap(imf);
2128                         goto out_in6p_locked;
2129                 }
2130         }
2131
2132         im6f_commit(imf);
2133         imf = NULL;
2134
2135 out_in6p_locked:
2136         INP_WUNLOCK(inp);
2137 out_in6p_unlocked:
2138         IN6_MULTI_UNLOCK();
2139
2140         if (is_new && imf) {
2141                 if (imf->im6f_in6m != NULL) {
2142                         struct in6_multi_head inmh;
2143
2144                         SLIST_INIT(&inmh);
2145                         SLIST_INSERT_HEAD(&inmh, imf->im6f_in6m, in6m_defer);
2146                         in6m_release_list_deferred(&inmh);
2147                 }
2148                 ip6_mfilter_free(imf);
2149         }
2150         return (error);
2151 }
2152
2153 /*
2154  * Leave an IPv6 multicast group on an inpcb, possibly with a source.
2155  */
2156 static int
2157 in6p_leave_group(struct inpcb *inp, struct sockopt *sopt)
2158 {
2159         struct ipv6_mreq                 mreq;
2160         struct group_source_req          gsr;
2161         sockunion_t                     *gsa, *ssa;
2162         struct ifnet                    *ifp;
2163         struct in6_mfilter              *imf;
2164         struct ip6_moptions             *imo;
2165         struct in6_msource              *ims;
2166         struct in6_multi                *inm;
2167         uint32_t                         ifindex;
2168         int                              error;
2169         bool                             is_final;
2170 #ifdef KTR
2171         char                             ip6tbuf[INET6_ADDRSTRLEN];
2172 #endif
2173
2174         ifp = NULL;
2175         ifindex = 0;
2176         error = 0;
2177         is_final = true;
2178
2179         memset(&gsr, 0, sizeof(struct group_source_req));
2180         gsa = (sockunion_t *)&gsr.gsr_group;
2181         gsa->ss.ss_family = AF_UNSPEC;
2182         ssa = (sockunion_t *)&gsr.gsr_source;
2183         ssa->ss.ss_family = AF_UNSPEC;
2184
2185         /*
2186          * Chew everything passed in up into a struct group_source_req
2187          * as that is easier to process.
2188          * Note: Any embedded scope ID in the multicast group passed
2189          * in by userland is ignored, the interface index is the recommended
2190          * mechanism to specify an interface; see below.
2191          */
2192         switch (sopt->sopt_name) {
2193         case IPV6_LEAVE_GROUP:
2194                 error = sooptcopyin(sopt, &mreq, sizeof(struct ipv6_mreq),
2195                     sizeof(struct ipv6_mreq));
2196                 if (error)
2197                         return (error);
2198                 gsa->sin6.sin6_family = AF_INET6;
2199                 gsa->sin6.sin6_len = sizeof(struct sockaddr_in6);
2200                 gsa->sin6.sin6_addr = mreq.ipv6mr_multiaddr;
2201                 gsa->sin6.sin6_port = 0;
2202                 gsa->sin6.sin6_scope_id = 0;
2203                 ifindex = mreq.ipv6mr_interface;
2204                 break;
2205
2206         case MCAST_LEAVE_GROUP:
2207         case MCAST_LEAVE_SOURCE_GROUP:
2208                 if (sopt->sopt_name == MCAST_LEAVE_GROUP) {
2209                         error = sooptcopyin(sopt, &gsr,
2210                             sizeof(struct group_req),
2211                             sizeof(struct group_req));
2212                 } else if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2213                         error = sooptcopyin(sopt, &gsr,
2214                             sizeof(struct group_source_req),
2215                             sizeof(struct group_source_req));
2216                 }
2217                 if (error)
2218                         return (error);
2219
2220                 if (gsa->sin6.sin6_family != AF_INET6 ||
2221                     gsa->sin6.sin6_len != sizeof(struct sockaddr_in6))
2222                         return (EINVAL);
2223                 if (sopt->sopt_name == MCAST_LEAVE_SOURCE_GROUP) {
2224                         if (ssa->sin6.sin6_family != AF_INET6 ||
2225                             ssa->sin6.sin6_len != sizeof(struct sockaddr_in6))
2226                                 return (EINVAL);
2227                         if (IN6_IS_ADDR_MULTICAST(&ssa->sin6.sin6_addr))
2228                                 return (EINVAL);
2229                         /*
2230                          * TODO: Validate embedded scope ID in source
2231                          * list entry against passed-in ifp, if and only
2232                          * if source list filter entry is iface or node local.
2233                          */
2234                         in6_clearscope(&ssa->sin6.sin6_addr);
2235                 }
2236                 gsa->sin6.sin6_port = 0;
2237                 gsa->sin6.sin6_scope_id = 0;
2238                 ifindex = gsr.gsr_interface;
2239                 break;
2240
2241         default:
2242                 CTR2(KTR_MLD, "%s: unknown sopt_name %d",
2243                     __func__, sopt->sopt_name);
2244                 return (EOPNOTSUPP);
2245                 break;
2246         }
2247
2248         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
2249                 return (EINVAL);
2250
2251         /*
2252          * Validate interface index if provided. If no interface index
2253          * was provided separately, attempt to look the membership up
2254          * from the default scope as a last resort to disambiguate
2255          * the membership we are being asked to leave.
2256          * XXX SCOPE6 lock potentially taken here.
2257          */
2258         if (ifindex != 0) {
2259                 if (V_if_index < ifindex)
2260                         return (EADDRNOTAVAIL);
2261                 ifp = ifnet_byindex(ifindex);
2262                 if (ifp == NULL)
2263                         return (EADDRNOTAVAIL);
2264                 (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
2265         } else {
2266                 error = sa6_embedscope(&gsa->sin6, V_ip6_use_defzone);
2267                 if (error)
2268                         return (EADDRNOTAVAIL);
2269                 /*
2270                  * Some badly behaved applications don't pass an ifindex
2271                  * or a scope ID, which is an API violation. In this case,
2272                  * perform a lookup as per a v6 join.
2273                  *
2274                  * XXX For now, stomp on zone ID for the corner case.
2275                  * This is not the 'KAME way', but we need to see the ifp
2276                  * directly until such time as this implementation is
2277                  * refactored, assuming the scope IDs are the way to go.
2278                  */
2279                 ifindex = ntohs(gsa->sin6.sin6_addr.s6_addr16[1]);
2280                 if (ifindex == 0) {
2281                         CTR2(KTR_MLD, "%s: warning: no ifindex, looking up "
2282                             "ifp for group %s.", __func__,
2283                             ip6_sprintf(ip6tbuf, &gsa->sin6.sin6_addr));
2284                         ifp = in6p_lookup_mcast_ifp(inp, &gsa->sin6);
2285                 } else {
2286                         ifp = ifnet_byindex(ifindex);
2287                 }
2288                 if (ifp == NULL)
2289                         return (EADDRNOTAVAIL);
2290         }
2291
2292         CTR2(KTR_MLD, "%s: ifp = %p", __func__, ifp);
2293         KASSERT(ifp != NULL, ("%s: ifp did not resolve", __func__));
2294
2295         IN6_MULTI_LOCK();
2296
2297         /*
2298          * Find the membership in the membership list.
2299          */
2300         imo = in6p_findmoptions(inp);
2301         imf = im6o_match_group(imo, ifp, &gsa->sa);
2302         if (imf == NULL) {
2303                 error = EADDRNOTAVAIL;
2304                 goto out_in6p_locked;
2305         }
2306         inm = imf->im6f_in6m;
2307
2308         if (ssa->ss.ss_family != AF_UNSPEC)
2309                 is_final = false;
2310
2311         /*
2312          * Begin state merge transaction at socket layer.
2313          */
2314         INP_WLOCK_ASSERT(inp);
2315
2316         /*
2317          * If we were instructed only to leave a given source, do so.
2318          * MCAST_LEAVE_SOURCE_GROUP is only valid for inclusive memberships.
2319          */
2320         if (is_final) {
2321                 ip6_mfilter_remove(&imo->im6o_head, imf);
2322                 im6f_leave(imf);
2323
2324                 /*
2325                  * Give up the multicast address record to which
2326                  * the membership points.
2327                  */
2328                 (void)in6_leavegroup_locked(inm, imf);
2329         } else {
2330                 if (imf->im6f_st[0] == MCAST_EXCLUDE) {
2331                         error = EADDRNOTAVAIL;
2332                         goto out_in6p_locked;
2333                 }
2334                 ims = im6o_match_source(imf, &ssa->sa);
2335                 if (ims == NULL) {
2336                         CTR3(KTR_MLD, "%s: source %p %spresent", __func__,
2337                             ip6_sprintf(ip6tbuf, &ssa->sin6.sin6_addr),
2338                             "not ");
2339                         error = EADDRNOTAVAIL;
2340                         goto out_in6p_locked;
2341                 }
2342                 CTR2(KTR_MLD, "%s: %s source", __func__, "block");
2343                 error = im6f_prune(imf, &ssa->sin6);
2344                 if (error) {
2345                         CTR1(KTR_MLD, "%s: merge imf state failed",
2346                             __func__);
2347                         goto out_in6p_locked;
2348                 }
2349         }
2350
2351         /*
2352          * Begin state merge transaction at MLD layer.
2353          */
2354         if (!is_final) {
2355                 CTR1(KTR_MLD, "%s: merge inm state", __func__);
2356                 IN6_MULTI_LIST_LOCK();
2357                 error = in6m_merge(inm, imf);
2358                 if (error) {
2359                         CTR1(KTR_MLD, "%s: failed to merge inm state",
2360                             __func__);
2361                         IN6_MULTI_LIST_UNLOCK();
2362                         im6f_rollback(imf);
2363                         im6f_reap(imf);
2364                         goto out_in6p_locked;
2365                 }
2366
2367                 CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
2368                 error = mld_change_state(inm, 0);
2369                 IN6_MULTI_LIST_UNLOCK();
2370                 if (error) {
2371                         CTR1(KTR_MLD, "%s: failed mld downcall",
2372                              __func__);
2373                         im6f_rollback(imf);
2374                         im6f_reap(imf);
2375                         goto out_in6p_locked;
2376                 }
2377         }
2378
2379         im6f_commit(imf);
2380         im6f_reap(imf);
2381
2382 out_in6p_locked:
2383         INP_WUNLOCK(inp);
2384
2385         if (is_final && imf)
2386                 ip6_mfilter_free(imf);
2387
2388         IN6_MULTI_UNLOCK();
2389         return (error);
2390 }
2391
2392 /*
2393  * Select the interface for transmitting IPv6 multicast datagrams.
2394  *
2395  * Either an instance of struct in6_addr or an instance of struct ipv6_mreqn
2396  * may be passed to this socket option. An address of in6addr_any or an
2397  * interface index of 0 is used to remove a previous selection.
2398  * When no interface is selected, one is chosen for every send.
2399  */
2400 static int
2401 in6p_set_multicast_if(struct inpcb *inp, struct sockopt *sopt)
2402 {
2403         struct ifnet            *ifp;
2404         struct ip6_moptions     *imo;
2405         u_int                    ifindex;
2406         int                      error;
2407
2408         if (sopt->sopt_valsize != sizeof(u_int))
2409                 return (EINVAL);
2410
2411         error = sooptcopyin(sopt, &ifindex, sizeof(u_int), sizeof(u_int));
2412         if (error)
2413                 return (error);
2414         if (V_if_index < ifindex)
2415                 return (EINVAL);
2416         if (ifindex == 0)
2417                 ifp = NULL;
2418         else {
2419                 ifp = ifnet_byindex(ifindex);
2420                 if (ifp == NULL)
2421                         return (EINVAL);
2422                 if ((ifp->if_flags & IFF_MULTICAST) == 0)
2423                         return (EADDRNOTAVAIL);
2424         }
2425         imo = in6p_findmoptions(inp);
2426         imo->im6o_multicast_ifp = ifp;
2427         INP_WUNLOCK(inp);
2428
2429         return (0);
2430 }
2431
2432 /*
2433  * Atomically set source filters on a socket for an IPv6 multicast group.
2434  *
2435  * SMPng: NOTE: Potentially calls malloc(M_WAITOK) with Giant held.
2436  */
2437 static int
2438 in6p_set_source_filters(struct inpcb *inp, struct sockopt *sopt)
2439 {
2440         struct __msfilterreq     msfr;
2441         sockunion_t             *gsa;
2442         struct ifnet            *ifp;
2443         struct in6_mfilter      *imf;
2444         struct ip6_moptions     *imo;
2445         struct in6_multi                *inm;
2446         int                      error;
2447
2448         error = sooptcopyin(sopt, &msfr, sizeof(struct __msfilterreq),
2449             sizeof(struct __msfilterreq));
2450         if (error)
2451                 return (error);
2452
2453         if (msfr.msfr_nsrcs > in6_mcast_maxsocksrc)
2454                 return (ENOBUFS);
2455
2456         if (msfr.msfr_fmode != MCAST_EXCLUDE &&
2457             msfr.msfr_fmode != MCAST_INCLUDE)
2458                 return (EINVAL);
2459
2460         if (msfr.msfr_group.ss_family != AF_INET6 ||
2461             msfr.msfr_group.ss_len != sizeof(struct sockaddr_in6))
2462                 return (EINVAL);
2463
2464         gsa = (sockunion_t *)&msfr.msfr_group;
2465         if (!IN6_IS_ADDR_MULTICAST(&gsa->sin6.sin6_addr))
2466                 return (EINVAL);
2467
2468         gsa->sin6.sin6_port = 0;        /* ignore port */
2469
2470         if (msfr.msfr_ifindex == 0 || V_if_index < msfr.msfr_ifindex)
2471                 return (EADDRNOTAVAIL);
2472         ifp = ifnet_byindex(msfr.msfr_ifindex);
2473         if (ifp == NULL)
2474                 return (EADDRNOTAVAIL);
2475         (void)in6_setscope(&gsa->sin6.sin6_addr, ifp, NULL);
2476
2477         /*
2478          * Take the INP write lock.
2479          * Check if this socket is a member of this group.
2480          */
2481         imo = in6p_findmoptions(inp);
2482         imf = im6o_match_group(imo, ifp, &gsa->sa);
2483         if (imf == NULL) {
2484                 error = EADDRNOTAVAIL;
2485                 goto out_in6p_locked;
2486         }
2487         inm = imf->im6f_in6m;
2488
2489         /*
2490          * Begin state merge transaction at socket layer.
2491          */
2492         INP_WLOCK_ASSERT(inp);
2493
2494         imf->im6f_st[1] = msfr.msfr_fmode;
2495
2496         /*
2497          * Apply any new source filters, if present.
2498          * Make a copy of the user-space source vector so
2499          * that we may copy them with a single copyin. This
2500          * allows us to deal with page faults up-front.
2501          */
2502         if (msfr.msfr_nsrcs > 0) {
2503                 struct in6_msource      *lims;
2504                 struct sockaddr_in6     *psin;
2505                 struct sockaddr_storage *kss, *pkss;
2506                 int                      i;
2507
2508                 INP_WUNLOCK(inp);
2509  
2510                 CTR2(KTR_MLD, "%s: loading %lu source list entries",
2511                     __func__, (unsigned long)msfr.msfr_nsrcs);
2512                 kss = malloc(sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs,
2513                     M_TEMP, M_WAITOK);
2514                 error = copyin(msfr.msfr_srcs, kss,
2515                     sizeof(struct sockaddr_storage) * msfr.msfr_nsrcs);
2516                 if (error) {
2517                         free(kss, M_TEMP);
2518                         return (error);
2519                 }
2520
2521                 INP_WLOCK(inp);
2522
2523                 /*
2524                  * Mark all source filters as UNDEFINED at t1.
2525                  * Restore new group filter mode, as im6f_leave()
2526                  * will set it to INCLUDE.
2527                  */
2528                 im6f_leave(imf);
2529                 imf->im6f_st[1] = msfr.msfr_fmode;
2530
2531                 /*
2532                  * Update socket layer filters at t1, lazy-allocating
2533                  * new entries. This saves a bunch of memory at the
2534                  * cost of one RB_FIND() per source entry; duplicate
2535                  * entries in the msfr_nsrcs vector are ignored.
2536                  * If we encounter an error, rollback transaction.
2537                  *
2538                  * XXX This too could be replaced with a set-symmetric
2539                  * difference like loop to avoid walking from root
2540                  * every time, as the key space is common.
2541                  */
2542                 for (i = 0, pkss = kss; i < msfr.msfr_nsrcs; i++, pkss++) {
2543                         psin = (struct sockaddr_in6 *)pkss;
2544                         if (psin->sin6_family != AF_INET6) {
2545                                 error = EAFNOSUPPORT;
2546                                 break;
2547                         }
2548                         if (psin->sin6_len != sizeof(struct sockaddr_in6)) {
2549                                 error = EINVAL;
2550                                 break;
2551                         }
2552                         if (IN6_IS_ADDR_MULTICAST(&psin->sin6_addr)) {
2553                                 error = EINVAL;
2554                                 break;
2555                         }
2556                         /*
2557                          * TODO: Validate embedded scope ID in source
2558                          * list entry against passed-in ifp, if and only
2559                          * if source list filter entry is iface or node local.
2560                          */
2561                         in6_clearscope(&psin->sin6_addr);
2562                         error = im6f_get_source(imf, psin, &lims);
2563                         if (error)
2564                                 break;
2565                         lims->im6sl_st[1] = imf->im6f_st[1];
2566                 }
2567                 free(kss, M_TEMP);
2568         }
2569
2570         if (error)
2571                 goto out_im6f_rollback;
2572
2573         INP_WLOCK_ASSERT(inp);
2574         IN6_MULTI_LIST_LOCK();
2575
2576         /*
2577          * Begin state merge transaction at MLD layer.
2578          */
2579         CTR1(KTR_MLD, "%s: merge inm state", __func__);
2580         error = in6m_merge(inm, imf);
2581         if (error)
2582                 CTR1(KTR_MLD, "%s: failed to merge inm state", __func__);
2583         else {
2584                 CTR1(KTR_MLD, "%s: doing mld downcall", __func__);
2585                 error = mld_change_state(inm, 0);
2586                 if (error)
2587                         CTR1(KTR_MLD, "%s: failed mld downcall", __func__);
2588         }
2589
2590         IN6_MULTI_LIST_UNLOCK();
2591
2592 out_im6f_rollback:
2593         if (error)
2594                 im6f_rollback(imf);
2595         else
2596                 im6f_commit(imf);
2597
2598         im6f_reap(imf);
2599
2600 out_in6p_locked:
2601         INP_WUNLOCK(inp);
2602         return (error);
2603 }
2604
2605 /*
2606  * Set the IP multicast options in response to user setsockopt().
2607  *
2608  * Many of the socket options handled in this function duplicate the
2609  * functionality of socket options in the regular unicast API. However,
2610  * it is not possible to merge the duplicate code, because the idempotence
2611  * of the IPv6 multicast part of the BSD Sockets API must be preserved;
2612  * the effects of these options must be treated as separate and distinct.
2613  *
2614  * SMPng: XXX: Unlocked read of inp_socket believed OK.
2615  */
2616 int
2617 ip6_setmoptions(struct inpcb *inp, struct sockopt *sopt)
2618 {
2619         struct ip6_moptions     *im6o;
2620         int                      error;
2621
2622         error = 0;
2623
2624         /*
2625          * If socket is neither of type SOCK_RAW or SOCK_DGRAM,
2626          * or is a divert socket, reject it.
2627          */
2628         if (inp->inp_socket->so_proto->pr_protocol == IPPROTO_DIVERT ||
2629             (inp->inp_socket->so_proto->pr_type != SOCK_RAW &&
2630              inp->inp_socket->so_proto->pr_type != SOCK_DGRAM))
2631                 return (EOPNOTSUPP);
2632
2633         switch (sopt->sopt_name) {
2634         case IPV6_MULTICAST_IF:
2635                 error = in6p_set_multicast_if(inp, sopt);
2636                 break;
2637
2638         case IPV6_MULTICAST_HOPS: {
2639                 int hlim;
2640
2641                 if (sopt->sopt_valsize != sizeof(int)) {
2642                         error = EINVAL;
2643                         break;
2644                 }
2645                 error = sooptcopyin(sopt, &hlim, sizeof(hlim), sizeof(int));
2646                 if (error)
2647                         break;
2648                 if (hlim < -1 || hlim > 255) {
2649                         error = EINVAL;
2650                         break;
2651                 } else if (hlim == -1) {
2652                         hlim = V_ip6_defmcasthlim;
2653                 }
2654                 im6o = in6p_findmoptions(inp);
2655                 im6o->im6o_multicast_hlim = hlim;
2656                 INP_WUNLOCK(inp);
2657                 break;
2658         }
2659
2660         case IPV6_MULTICAST_LOOP: {
2661                 u_int loop;
2662
2663                 /*
2664                  * Set the loopback flag for outgoing multicast packets.
2665                  * Must be zero or one.
2666                  */
2667                 if (sopt->sopt_valsize != sizeof(u_int)) {
2668                         error = EINVAL;
2669                         break;
2670                 }
2671                 error = sooptcopyin(sopt, &loop, sizeof(u_int), sizeof(u_int));
2672                 if (error)
2673                         break;
2674                 if (loop > 1) {
2675                         error = EINVAL;
2676                         break;
2677                 }
2678                 im6o = in6p_findmoptions(inp);
2679                 im6o->im6o_multicast_loop = loop;
2680                 INP_WUNLOCK(inp);
2681                 break;
2682         }
2683
2684         case IPV6_JOIN_GROUP:
2685         case MCAST_JOIN_GROUP:
2686         case MCAST_JOIN_SOURCE_GROUP:
2687                 error = in6p_join_group(inp, sopt);
2688                 break;
2689
2690         case IPV6_LEAVE_GROUP:
2691         case MCAST_LEAVE_GROUP:
2692         case MCAST_LEAVE_SOURCE_GROUP:
2693                 error = in6p_leave_group(inp, sopt);
2694                 break;
2695
2696         case MCAST_BLOCK_SOURCE:
2697         case MCAST_UNBLOCK_SOURCE:
2698                 error = in6p_block_unblock_source(inp, sopt);
2699                 break;
2700
2701         case IPV6_MSFILTER:
2702                 error = in6p_set_source_filters(inp, sopt);
2703                 break;
2704
2705         default:
2706                 error = EOPNOTSUPP;
2707                 break;
2708         }
2709
2710         INP_UNLOCK_ASSERT(inp);
2711
2712         return (error);
2713 }
2714
2715 /*
2716  * Expose MLD's multicast filter mode and source list(s) to userland,
2717  * keyed by (ifindex, group).
2718  * The filter mode is written out as a uint32_t, followed by
2719  * 0..n of struct in6_addr.
2720  * For use by ifmcstat(8).
2721  * SMPng: NOTE: unlocked read of ifindex space.
2722  */
2723 static int
2724 sysctl_ip6_mcast_filters(SYSCTL_HANDLER_ARGS)
2725 {
2726         struct in6_addr                  mcaddr;
2727         struct in6_addr                  src;
2728         struct epoch_tracker             et;
2729         struct ifnet                    *ifp;
2730         struct ifmultiaddr              *ifma;
2731         struct in6_multi                *inm;
2732         struct ip6_msource              *ims;
2733         int                             *name;
2734         int                              retval;
2735         u_int                            namelen;
2736         uint32_t                         fmode, ifindex;
2737 #ifdef KTR
2738         char                             ip6tbuf[INET6_ADDRSTRLEN];
2739 #endif
2740
2741         name = (int *)arg1;
2742         namelen = arg2;
2743
2744         if (req->newptr != NULL)
2745                 return (EPERM);
2746
2747         /* int: ifindex + 4 * 32 bits of IPv6 address */
2748         if (namelen != 5)
2749                 return (EINVAL);
2750
2751         ifindex = name[0];
2752         if (ifindex <= 0 || ifindex > V_if_index) {
2753                 CTR2(KTR_MLD, "%s: ifindex %u out of range",
2754                     __func__, ifindex);
2755                 return (ENOENT);
2756         }
2757
2758         memcpy(&mcaddr, &name[1], sizeof(struct in6_addr));
2759         if (!IN6_IS_ADDR_MULTICAST(&mcaddr)) {
2760                 CTR2(KTR_MLD, "%s: group %s is not multicast",
2761                     __func__, ip6_sprintf(ip6tbuf, &mcaddr));
2762                 return (EINVAL);
2763         }
2764
2765         NET_EPOCH_ENTER(et);
2766         ifp = ifnet_byindex(ifindex);
2767         if (ifp == NULL) {
2768                 NET_EPOCH_EXIT(et);
2769                 CTR2(KTR_MLD, "%s: no ifp for ifindex %u",
2770                     __func__, ifindex);
2771                 return (ENOENT);
2772         }
2773         /*
2774          * Internal MLD lookups require that scope/zone ID is set.
2775          */
2776         (void)in6_setscope(&mcaddr, ifp, NULL);
2777
2778         retval = sysctl_wire_old_buffer(req,
2779             sizeof(uint32_t) + (in6_mcast_maxgrpsrc * sizeof(struct in6_addr)));
2780         if (retval) {
2781                 NET_EPOCH_EXIT(et);
2782                 return (retval);
2783         }
2784
2785         IN6_MULTI_LOCK();
2786         IN6_MULTI_LIST_LOCK();
2787         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2788                 inm = in6m_ifmultiaddr_get_inm(ifma);
2789                 if (inm == NULL)
2790                         continue;
2791                 if (!IN6_ARE_ADDR_EQUAL(&inm->in6m_addr, &mcaddr))
2792                         continue;
2793                 fmode = inm->in6m_st[1].iss_fmode;
2794                 retval = SYSCTL_OUT(req, &fmode, sizeof(uint32_t));
2795                 if (retval != 0)
2796                         break;
2797                 RB_FOREACH(ims, ip6_msource_tree, &inm->in6m_srcs) {
2798                         CTR2(KTR_MLD, "%s: visit node %p", __func__, ims);
2799                         /*
2800                          * Only copy-out sources which are in-mode.
2801                          */
2802                         if (fmode != im6s_get_mode(inm, ims, 1)) {
2803                                 CTR1(KTR_MLD, "%s: skip non-in-mode",
2804                                     __func__);
2805                                 continue;
2806                         }
2807                         src = ims->im6s_addr;
2808                         retval = SYSCTL_OUT(req, &src,
2809                             sizeof(struct in6_addr));
2810                         if (retval != 0)
2811                                 break;
2812                 }
2813         }
2814         IN6_MULTI_LIST_UNLOCK();
2815         IN6_MULTI_UNLOCK();
2816         NET_EPOCH_EXIT(et);
2817
2818         return (retval);
2819 }
2820
2821 #ifdef KTR
2822
2823 static const char *in6m_modestrs[] = { "un", "in", "ex" };
2824
2825 static const char *
2826 in6m_mode_str(const int mode)
2827 {
2828
2829         if (mode >= MCAST_UNDEFINED && mode <= MCAST_EXCLUDE)
2830                 return (in6m_modestrs[mode]);
2831         return ("??");
2832 }
2833
2834 static const char *in6m_statestrs[] = {
2835         "not-member",
2836         "silent",
2837         "idle",
2838         "lazy",
2839         "sleeping",
2840         "awakening",
2841         "query-pending",
2842         "sg-query-pending",
2843         "leaving"
2844 };
2845
2846 static const char *
2847 in6m_state_str(const int state)
2848 {
2849
2850         if (state >= MLD_NOT_MEMBER && state <= MLD_LEAVING_MEMBER)
2851                 return (in6m_statestrs[state]);
2852         return ("??");
2853 }
2854
2855 /*
2856  * Dump an in6_multi structure to the console.
2857  */
2858 void
2859 in6m_print(const struct in6_multi *inm)
2860 {
2861         int t;
2862         char ip6tbuf[INET6_ADDRSTRLEN];
2863
2864         if ((ktr_mask & KTR_MLD) == 0)
2865                 return;
2866
2867         printf("%s: --- begin in6m %p ---\n", __func__, inm);
2868         printf("addr %s ifp %p(%s) ifma %p\n",
2869             ip6_sprintf(ip6tbuf, &inm->in6m_addr),
2870             inm->in6m_ifp,
2871             if_name(inm->in6m_ifp),
2872             inm->in6m_ifma);
2873         printf("timer %u state %s refcount %u scq.len %u\n",
2874             inm->in6m_timer,
2875             in6m_state_str(inm->in6m_state),
2876             inm->in6m_refcount,
2877             mbufq_len(&inm->in6m_scq));
2878         printf("mli %p nsrc %lu sctimer %u scrv %u\n",
2879             inm->in6m_mli,
2880             inm->in6m_nsrc,
2881             inm->in6m_sctimer,
2882             inm->in6m_scrv);
2883         for (t = 0; t < 2; t++) {
2884                 printf("t%d: fmode %s asm %u ex %u in %u rec %u\n", t,
2885                     in6m_mode_str(inm->in6m_st[t].iss_fmode),
2886                     inm->in6m_st[t].iss_asm,
2887                     inm->in6m_st[t].iss_ex,
2888                     inm->in6m_st[t].iss_in,
2889                     inm->in6m_st[t].iss_rec);
2890         }
2891         printf("%s: --- end in6m %p ---\n", __func__, inm);
2892 }
2893
2894 #else /* !KTR */
2895
2896 void
2897 in6m_print(const struct in6_multi *inm)
2898 {
2899
2900 }
2901
2902 #endif /* KTR */