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