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