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