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