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