]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/igmp.c
riscv: Call identify_cpu() earlier for CPU 0
[FreeBSD/FreeBSD.git] / sys / netinet / igmp.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2007-2009 Bruce Simpson.
5  * Copyright (c) 1988 Stephen Deering.
6  * Copyright (c) 1992, 1993
7  *      The Regents of the University of California.  All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Stephen Deering of Stanford University.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)igmp.c      8.1 (Berkeley) 7/19/93
37  */
38
39 /*
40  * Internet Group Management Protocol (IGMP) routines.
41  * [RFC1112, RFC2236, RFC3376]
42  *
43  * Written by Steve Deering, Stanford, May 1988.
44  * Modified by Rosen Sharma, Stanford, Aug 1994.
45  * Modified by Bill Fenner, Xerox PARC, Feb 1995.
46  * Modified to fully comply to IGMPv2 by Bill Fenner, Oct 1995.
47  * Significantly rewritten for IGMPv3, VIMAGE, and SMP by Bruce Simpson.
48  *
49  * MULTICAST Revision: 3.5.1.4
50  */
51
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54
55 #include "opt_ddb.h"
56
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/module.h>
60 #include <sys/malloc.h>
61 #include <sys/mbuf.h>
62 #include <sys/socket.h>
63 #include <sys/protosw.h>
64 #include <sys/kernel.h>
65 #include <sys/lock.h>
66 #include <sys/rmlock.h>
67 #include <sys/sysctl.h>
68 #include <sys/ktr.h>
69 #include <sys/condvar.h>
70
71 #ifdef DDB
72 #include <ddb/ddb.h>
73 #endif
74
75 #include <net/if.h>
76 #include <net/if_var.h>
77 #include <net/netisr.h>
78 #include <net/vnet.h>
79
80 #include <netinet/in.h>
81 #include <netinet/in_var.h>
82 #include <netinet/in_systm.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_var.h>
85 #include <netinet/ip_options.h>
86 #include <netinet/igmp.h>
87 #include <netinet/igmp_var.h>
88
89 #include <machine/in_cksum.h>
90
91 #include <security/mac/mac_framework.h>
92
93 #ifndef KTR_IGMPV3
94 #define KTR_IGMPV3 KTR_INET
95 #endif
96
97 static struct igmp_ifsoftc *
98                 igi_alloc_locked(struct ifnet *);
99 static void     igi_delete_locked(const struct ifnet *);
100 static void     igmp_dispatch_queue(struct mbufq *, int, const int);
101 static void     igmp_fasttimo_vnet(void);
102 static void     igmp_final_leave(struct in_multi *, struct igmp_ifsoftc *);
103 static int      igmp_handle_state_change(struct in_multi *,
104                     struct igmp_ifsoftc *);
105 static int      igmp_initial_join(struct in_multi *, struct igmp_ifsoftc *);
106 static int      igmp_input_v1_query(struct ifnet *, const struct ip *,
107                     const struct igmp *);
108 static int      igmp_input_v2_query(struct ifnet *, const struct ip *,
109                     const struct igmp *);
110 static int      igmp_input_v3_query(struct ifnet *, const struct ip *,
111                     /*const*/ struct igmpv3 *);
112 static int      igmp_input_v3_group_query(struct in_multi *,
113                     struct igmp_ifsoftc *, int, /*const*/ struct igmpv3 *);
114 static int      igmp_input_v1_report(struct ifnet *, /*const*/ struct ip *,
115                     /*const*/ struct igmp *);
116 static int      igmp_input_v2_report(struct ifnet *, /*const*/ struct ip *,
117                     /*const*/ struct igmp *);
118 static void     igmp_intr(struct mbuf *);
119 static int      igmp_isgroupreported(const struct in_addr);
120 static struct mbuf *
121                 igmp_ra_alloc(void);
122 #ifdef KTR
123 static char *   igmp_rec_type_to_str(const int);
124 #endif
125 static void     igmp_set_version(struct igmp_ifsoftc *, const int);
126 static void     igmp_slowtimo_vnet(void);
127 static int      igmp_v1v2_queue_report(struct in_multi *, const int);
128 static void     igmp_v1v2_process_group_timer(struct in_multi *, const int);
129 static void     igmp_v1v2_process_querier_timers(struct igmp_ifsoftc *);
130 static void     igmp_v2_update_group(struct in_multi *, const int);
131 static void     igmp_v3_cancel_link_timers(struct igmp_ifsoftc *);
132 static void     igmp_v3_dispatch_general_query(struct igmp_ifsoftc *);
133 static struct mbuf *
134                 igmp_v3_encap_report(struct ifnet *, struct mbuf *);
135 static int      igmp_v3_enqueue_group_record(struct mbufq *,
136                     struct in_multi *, const int, const int, const int);
137 static int      igmp_v3_enqueue_filter_change(struct mbufq *,
138                     struct in_multi *);
139 static void     igmp_v3_process_group_timers(struct in_multi_head *,
140                     struct mbufq *, struct mbufq *, struct in_multi *,
141                     const int);
142 static int      igmp_v3_merge_state_changes(struct in_multi *,
143                     struct mbufq *);
144 static void     igmp_v3_suppress_group_record(struct in_multi *);
145 static int      sysctl_igmp_default_version(SYSCTL_HANDLER_ARGS);
146 static int      sysctl_igmp_gsr(SYSCTL_HANDLER_ARGS);
147 static int      sysctl_igmp_ifinfo(SYSCTL_HANDLER_ARGS);
148 static int      sysctl_igmp_stat(SYSCTL_HANDLER_ARGS);
149
150 static const struct netisr_handler igmp_nh = {
151         .nh_name = "igmp",
152         .nh_handler = igmp_intr,
153         .nh_proto = NETISR_IGMP,
154         .nh_policy = NETISR_POLICY_SOURCE,
155 };
156
157 /*
158  * System-wide globals.
159  *
160  * Unlocked access to these is OK, except for the global IGMP output
161  * queue. The IGMP subsystem lock ends up being system-wide for the moment,
162  * because all VIMAGEs have to share a global output queue, as netisrs
163  * themselves are not virtualized.
164  *
165  * Locking:
166  *  * The permitted lock order is: IN_MULTI_LIST_LOCK, IGMP_LOCK, IF_ADDR_LOCK.
167  *    Any may be taken independently; if any are held at the same
168  *    time, the above lock order must be followed.
169  *  * All output is delegated to the netisr.
170  *    Now that Giant has been eliminated, the netisr may be inlined.
171  *  * IN_MULTI_LIST_LOCK covers in_multi.
172  *  * IGMP_LOCK covers igmp_ifsoftc and any global variables in this file,
173  *    including the output queue.
174  *  * IF_ADDR_LOCK covers if_multiaddrs, which is used for a variety of
175  *    per-link state iterators.
176  *  * igmp_ifsoftc is valid as long as PF_INET is attached to the interface,
177  *    therefore it is not refcounted.
178  *    We allow unlocked reads of igmp_ifsoftc when accessed via in_multi.
179  *
180  * Reference counting
181  *  * IGMP acquires its own reference every time an in_multi is passed to
182  *    it and the group is being joined for the first time.
183  *  * IGMP releases its reference(s) on in_multi in a deferred way,
184  *    because the operations which process the release run as part of
185  *    a loop whose control variables are directly affected by the release
186  *    (that, and not recursing on the IF_ADDR_LOCK).
187  *
188  * VIMAGE: Each in_multi corresponds to an ifp, and each ifp corresponds
189  * to a vnet in ifp->if_vnet.
190  *
191  * SMPng: XXX We may potentially race operations on ifma_protospec.
192  * The problem is that we currently lack a clean way of taking the
193  * IF_ADDR_LOCK() between the ifnet and in layers w/o recursing,
194  * as anything which modifies ifma needs to be covered by that lock.
195  * So check for ifma_protospec being NULL before proceeding.
196  */
197 struct mtx               igmp_mtx;
198
199 struct mbuf             *m_raopt;                /* Router Alert option */
200 static MALLOC_DEFINE(M_IGMP, "igmp", "igmp state");
201
202 /*
203  * VIMAGE-wide globals.
204  *
205  * The IGMPv3 timers themselves need to run per-image, however,
206  * protosw timers run globally (see tcp).
207  * An ifnet can only be in one vimage at a time, and the loopback
208  * ifnet, loif, is itself virtualized.
209  * It would otherwise be possible to seriously hose IGMP state,
210  * and create inconsistencies in upstream multicast routing, if you have
211  * multiple VIMAGEs running on the same link joining different multicast
212  * groups, UNLESS the "primary IP address" is different. This is because
213  * IGMP for IPv4 does not force link-local addresses to be used for each
214  * node, unlike MLD for IPv6.
215  * Obviously the IGMPv3 per-interface state has per-vimage granularity
216  * also as a result.
217  *
218  * FUTURE: Stop using IFP_TO_IA/INADDR_ANY, and use source address selection
219  * policy to control the address used by IGMP on the link.
220  */
221 VNET_DEFINE_STATIC(int, interface_timers_running);      /* IGMPv3 general
222                                                          * query response */
223 VNET_DEFINE_STATIC(int, state_change_timers_running);   /* IGMPv3 state-change
224                                                          * retransmit */
225 VNET_DEFINE_STATIC(int, current_state_timers_running);  /* IGMPv1/v2 host
226                                                          * report; IGMPv3 g/sg
227                                                          * query response */
228
229 #define V_interface_timers_running      VNET(interface_timers_running)
230 #define V_state_change_timers_running   VNET(state_change_timers_running)
231 #define V_current_state_timers_running  VNET(current_state_timers_running)
232
233 VNET_PCPUSTAT_DEFINE(struct igmpstat, igmpstat);
234 VNET_PCPUSTAT_SYSINIT(igmpstat);
235 VNET_PCPUSTAT_SYSUNINIT(igmpstat);
236
237 VNET_DEFINE_STATIC(LIST_HEAD(, igmp_ifsoftc), igi_head) =
238     LIST_HEAD_INITIALIZER(igi_head);
239 VNET_DEFINE_STATIC(struct timeval, igmp_gsrdelay) = {10, 0};
240
241 #define V_igi_head                      VNET(igi_head)
242 #define V_igmp_gsrdelay                 VNET(igmp_gsrdelay)
243
244 VNET_DEFINE_STATIC(int, igmp_recvifkludge) = 1;
245 VNET_DEFINE_STATIC(int, igmp_sendra) = 1;
246 VNET_DEFINE_STATIC(int, igmp_sendlocal) = 1;
247 VNET_DEFINE_STATIC(int, igmp_v1enable) = 1;
248 VNET_DEFINE_STATIC(int, igmp_v2enable) = 1;
249 VNET_DEFINE_STATIC(int, igmp_legacysupp);
250 VNET_DEFINE_STATIC(int, igmp_default_version) = IGMP_VERSION_3;
251
252 #define V_igmp_recvifkludge             VNET(igmp_recvifkludge)
253 #define V_igmp_sendra                   VNET(igmp_sendra)
254 #define V_igmp_sendlocal                VNET(igmp_sendlocal)
255 #define V_igmp_v1enable                 VNET(igmp_v1enable)
256 #define V_igmp_v2enable                 VNET(igmp_v2enable)
257 #define V_igmp_legacysupp               VNET(igmp_legacysupp)
258 #define V_igmp_default_version          VNET(igmp_default_version)
259
260 /*
261  * Virtualized sysctls.
262  */
263 SYSCTL_PROC(_net_inet_igmp, IGMPCTL_STATS, stats,
264     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_MPSAFE,
265     &VNET_NAME(igmpstat), 0, sysctl_igmp_stat, "S,igmpstat",
266     "IGMP statistics (struct igmpstat, netinet/igmp_var.h)");
267 SYSCTL_INT(_net_inet_igmp, OID_AUTO, recvifkludge, CTLFLAG_VNET | CTLFLAG_RW,
268     &VNET_NAME(igmp_recvifkludge), 0,
269     "Rewrite IGMPv1/v2 reports from 0.0.0.0 to contain subnet address");
270 SYSCTL_INT(_net_inet_igmp, OID_AUTO, sendra, CTLFLAG_VNET | CTLFLAG_RW,
271     &VNET_NAME(igmp_sendra), 0,
272     "Send IP Router Alert option in IGMPv2/v3 messages");
273 SYSCTL_INT(_net_inet_igmp, OID_AUTO, sendlocal, CTLFLAG_VNET | CTLFLAG_RW,
274     &VNET_NAME(igmp_sendlocal), 0,
275     "Send IGMP membership reports for 224.0.0.0/24 groups");
276 SYSCTL_INT(_net_inet_igmp, OID_AUTO, v1enable, CTLFLAG_VNET | CTLFLAG_RW,
277     &VNET_NAME(igmp_v1enable), 0,
278     "Enable backwards compatibility with IGMPv1");
279 SYSCTL_INT(_net_inet_igmp, OID_AUTO, v2enable, CTLFLAG_VNET | CTLFLAG_RW,
280     &VNET_NAME(igmp_v2enable), 0,
281     "Enable backwards compatibility with IGMPv2");
282 SYSCTL_INT(_net_inet_igmp, OID_AUTO, legacysupp, CTLFLAG_VNET | CTLFLAG_RW,
283     &VNET_NAME(igmp_legacysupp), 0,
284     "Allow v1/v2 reports to suppress v3 group responses");
285 SYSCTL_PROC(_net_inet_igmp, OID_AUTO, default_version,
286     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
287     &VNET_NAME(igmp_default_version), 0, sysctl_igmp_default_version, "I",
288     "Default version of IGMP to run on each interface");
289 SYSCTL_PROC(_net_inet_igmp, OID_AUTO, gsrdelay,
290     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
291     &VNET_NAME(igmp_gsrdelay.tv_sec), 0, sysctl_igmp_gsr, "I",
292     "Rate limit for IGMPv3 Group-and-Source queries in seconds");
293
294 /*
295  * Non-virtualized sysctls.
296  */
297 static SYSCTL_NODE(_net_inet_igmp, OID_AUTO, ifinfo,
298     CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_igmp_ifinfo,
299     "Per-interface IGMPv3 state");
300
301 static __inline void
302 igmp_save_context(struct mbuf *m, struct ifnet *ifp)
303 {
304
305 #ifdef VIMAGE
306         m->m_pkthdr.PH_loc.ptr = ifp->if_vnet;
307 #endif /* VIMAGE */
308         m->m_pkthdr.rcvif = ifp;
309         m->m_pkthdr.flowid = ifp->if_index;
310 }
311
312 static __inline void
313 igmp_scrub_context(struct mbuf *m)
314 {
315
316         m->m_pkthdr.PH_loc.ptr = NULL;
317         m->m_pkthdr.flowid = 0;
318 }
319
320 /*
321  * Restore context from a queued IGMP output chain.
322  * Return saved ifindex.
323  *
324  * VIMAGE: The assertion is there to make sure that we
325  * actually called CURVNET_SET() with what's in the mbuf chain.
326  */
327 static __inline uint32_t
328 igmp_restore_context(struct mbuf *m)
329 {
330
331 #ifdef notyet
332 #if defined(VIMAGE) && defined(INVARIANTS)
333         KASSERT(curvnet == (m->m_pkthdr.PH_loc.ptr),
334             ("%s: called when curvnet was not restored", __func__));
335 #endif
336 #endif
337         return (m->m_pkthdr.flowid);
338 }
339
340 /*
341  * IGMP statistics.
342  */
343 static int
344 sysctl_igmp_stat(SYSCTL_HANDLER_ARGS)
345 {
346         struct igmpstat igps0;
347         int error;
348         char *p;
349
350         error = sysctl_wire_old_buffer(req, sizeof(struct igmpstat));
351         if (error)
352                 return (error);
353
354         if (req->oldptr != NULL) {
355                 if (req->oldlen < sizeof(struct igmpstat))
356                         error = ENOMEM;
357                 else {
358                         /*
359                          * Copy the counters, and explicitly set the struct's
360                          * version and length fields.
361                          */
362                         COUNTER_ARRAY_COPY(VNET(igmpstat), &igps0,
363                             sizeof(struct igmpstat) / sizeof(uint64_t));
364                         igps0.igps_version = IGPS_VERSION_3;
365                         igps0.igps_len = IGPS_VERSION3_LEN;
366                         error = SYSCTL_OUT(req, &igps0,
367                             sizeof(struct igmpstat));
368                 }
369         } else
370                 req->validlen = sizeof(struct igmpstat);
371         if (error)
372                 goto out;
373         if (req->newptr != NULL) {
374                 if (req->newlen < sizeof(struct igmpstat))
375                         error = ENOMEM;
376                 else
377                         error = SYSCTL_IN(req, &igps0,
378                             sizeof(igps0));
379                 if (error)
380                         goto out;
381                 /*
382                  * igps0 must be "all zero".
383                  */
384                 p = (char *)&igps0;
385                 while (p < (char *)&igps0 + sizeof(igps0) && *p == '\0')
386                         p++;
387                 if (p != (char *)&igps0 + sizeof(igps0)) {
388                         error = EINVAL;
389                         goto out;
390                 }
391                 COUNTER_ARRAY_ZERO(VNET(igmpstat),
392                     sizeof(struct igmpstat) / sizeof(uint64_t));
393         }
394 out:
395         return (error);
396 }
397
398 /*
399  * Retrieve or set default IGMP version.
400  *
401  * VIMAGE: Assume curvnet set by caller.
402  * SMPng: NOTE: Serialized by IGMP lock.
403  */
404 static int
405 sysctl_igmp_default_version(SYSCTL_HANDLER_ARGS)
406 {
407         int      error;
408         int      new;
409
410         error = sysctl_wire_old_buffer(req, sizeof(int));
411         if (error)
412                 return (error);
413
414         IGMP_LOCK();
415
416         new = V_igmp_default_version;
417
418         error = sysctl_handle_int(oidp, &new, 0, req);
419         if (error || !req->newptr)
420                 goto out_locked;
421
422         if (new < IGMP_VERSION_1 || new > IGMP_VERSION_3) {
423                 error = EINVAL;
424                 goto out_locked;
425         }
426
427         CTR2(KTR_IGMPV3, "change igmp_default_version from %d to %d",
428              V_igmp_default_version, new);
429
430         V_igmp_default_version = new;
431
432 out_locked:
433         IGMP_UNLOCK();
434         return (error);
435 }
436
437 /*
438  * Retrieve or set threshold between group-source queries in seconds.
439  *
440  * VIMAGE: Assume curvnet set by caller.
441  * SMPng: NOTE: Serialized by IGMP lock.
442  */
443 static int
444 sysctl_igmp_gsr(SYSCTL_HANDLER_ARGS)
445 {
446         int error;
447         int i;
448
449         error = sysctl_wire_old_buffer(req, sizeof(int));
450         if (error)
451                 return (error);
452
453         IGMP_LOCK();
454
455         i = V_igmp_gsrdelay.tv_sec;
456
457         error = sysctl_handle_int(oidp, &i, 0, req);
458         if (error || !req->newptr)
459                 goto out_locked;
460
461         if (i < -1 || i >= 60) {
462                 error = EINVAL;
463                 goto out_locked;
464         }
465
466         CTR2(KTR_IGMPV3, "change igmp_gsrdelay from %d to %d",
467              V_igmp_gsrdelay.tv_sec, i);
468         V_igmp_gsrdelay.tv_sec = i;
469
470 out_locked:
471         IGMP_UNLOCK();
472         return (error);
473 }
474
475 /*
476  * Expose struct igmp_ifsoftc to userland, keyed by ifindex.
477  * For use by ifmcstat(8).
478  *
479  * SMPng: NOTE: Does an unlocked ifindex space read.
480  * VIMAGE: Assume curvnet set by caller. The node handler itself
481  * is not directly virtualized.
482  */
483 static int
484 sysctl_igmp_ifinfo(SYSCTL_HANDLER_ARGS)
485 {
486         int                     *name;
487         int                      error;
488         u_int                    namelen;
489         struct ifnet            *ifp;
490         struct igmp_ifsoftc     *igi;
491
492         name = (int *)arg1;
493         namelen = arg2;
494
495         if (req->newptr != NULL)
496                 return (EPERM);
497
498         if (namelen != 1)
499                 return (EINVAL);
500
501         error = sysctl_wire_old_buffer(req, sizeof(struct igmp_ifinfo));
502         if (error)
503                 return (error);
504
505         IN_MULTI_LIST_LOCK();
506         IGMP_LOCK();
507
508         if (name[0] <= 0 || name[0] > V_if_index) {
509                 error = ENOENT;
510                 goto out_locked;
511         }
512
513         error = ENOENT;
514
515         ifp = ifnet_byindex(name[0]);
516         if (ifp == NULL)
517                 goto out_locked;
518
519         LIST_FOREACH(igi, &V_igi_head, igi_link) {
520                 if (ifp == igi->igi_ifp) {
521                         struct igmp_ifinfo info;
522
523                         info.igi_version = igi->igi_version;
524                         info.igi_v1_timer = igi->igi_v1_timer;
525                         info.igi_v2_timer = igi->igi_v2_timer;
526                         info.igi_v3_timer = igi->igi_v3_timer;
527                         info.igi_flags = igi->igi_flags;
528                         info.igi_rv = igi->igi_rv;
529                         info.igi_qi = igi->igi_qi;
530                         info.igi_qri = igi->igi_qri;
531                         info.igi_uri = igi->igi_uri;
532                         error = SYSCTL_OUT(req, &info, sizeof(info));
533                         break;
534                 }
535         }
536
537 out_locked:
538         IGMP_UNLOCK();
539         IN_MULTI_LIST_UNLOCK();
540         return (error);
541 }
542
543 /*
544  * Dispatch an entire queue of pending packet chains
545  * using the netisr.
546  * VIMAGE: Assumes the vnet pointer has been set.
547  */
548 static void
549 igmp_dispatch_queue(struct mbufq *mq, int limit, const int loop)
550 {
551         struct epoch_tracker et;
552         struct mbuf *m;
553
554         NET_EPOCH_ENTER(et);
555         while ((m = mbufq_dequeue(mq)) != NULL) {
556                 CTR3(KTR_IGMPV3, "%s: dispatch %p from %p", __func__, mq, m);
557                 if (loop)
558                         m->m_flags |= M_IGMP_LOOP;
559                 netisr_dispatch(NETISR_IGMP, m);
560                 if (--limit == 0)
561                         break;
562         }
563         NET_EPOCH_EXIT(et);
564 }
565
566 /*
567  * Filter outgoing IGMP report state by group.
568  *
569  * Reports are ALWAYS suppressed for ALL-HOSTS (224.0.0.1).
570  * If the net.inet.igmp.sendlocal sysctl is 0, then IGMP reports are
571  * disabled for all groups in the 224.0.0.0/24 link-local scope. However,
572  * this may break certain IGMP snooping switches which rely on the old
573  * report behaviour.
574  *
575  * Return zero if the given group is one for which IGMP reports
576  * should be suppressed, or non-zero if reports should be issued.
577  */
578 static __inline int
579 igmp_isgroupreported(const struct in_addr addr)
580 {
581
582         if (in_allhosts(addr) ||
583             ((!V_igmp_sendlocal && IN_LOCAL_GROUP(ntohl(addr.s_addr)))))
584                 return (0);
585
586         return (1);
587 }
588
589 /*
590  * Construct a Router Alert option to use in outgoing packets.
591  */
592 static struct mbuf *
593 igmp_ra_alloc(void)
594 {
595         struct mbuf     *m;
596         struct ipoption *p;
597
598         m = m_get(M_WAITOK, MT_DATA);
599         p = mtod(m, struct ipoption *);
600         p->ipopt_dst.s_addr = INADDR_ANY;
601         p->ipopt_list[0] = (char)IPOPT_RA;      /* Router Alert Option */
602         p->ipopt_list[1] = 0x04;                /* 4 bytes long */
603         p->ipopt_list[2] = IPOPT_EOL;           /* End of IP option list */
604         p->ipopt_list[3] = 0x00;                /* pad byte */
605         m->m_len = sizeof(p->ipopt_dst) + p->ipopt_list[1];
606
607         return (m);
608 }
609
610 /*
611  * Attach IGMP when PF_INET is attached to an interface.
612  */
613 struct igmp_ifsoftc *
614 igmp_domifattach(struct ifnet *ifp)
615 {
616         struct igmp_ifsoftc *igi;
617
618         CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)",
619             __func__, ifp, ifp->if_xname);
620
621         IGMP_LOCK();
622
623         igi = igi_alloc_locked(ifp);
624         if (!(ifp->if_flags & IFF_MULTICAST))
625                 igi->igi_flags |= IGIF_SILENT;
626
627         IGMP_UNLOCK();
628
629         return (igi);
630 }
631
632 /*
633  * VIMAGE: assume curvnet set by caller.
634  */
635 static struct igmp_ifsoftc *
636 igi_alloc_locked(/*const*/ struct ifnet *ifp)
637 {
638         struct igmp_ifsoftc *igi;
639
640         IGMP_LOCK_ASSERT();
641
642         igi = malloc(sizeof(struct igmp_ifsoftc), M_IGMP, M_NOWAIT|M_ZERO);
643         if (igi == NULL)
644                 goto out;
645
646         igi->igi_ifp = ifp;
647         igi->igi_version = V_igmp_default_version;
648         igi->igi_flags = 0;
649         igi->igi_rv = IGMP_RV_INIT;
650         igi->igi_qi = IGMP_QI_INIT;
651         igi->igi_qri = IGMP_QRI_INIT;
652         igi->igi_uri = IGMP_URI_INIT;
653         mbufq_init(&igi->igi_gq, IGMP_MAX_RESPONSE_PACKETS);
654
655         LIST_INSERT_HEAD(&V_igi_head, igi, igi_link);
656
657         CTR2(KTR_IGMPV3, "allocate igmp_ifsoftc for ifp %p(%s)",
658              ifp, ifp->if_xname);
659
660 out:
661         return (igi);
662 }
663
664 /*
665  * Hook for ifdetach.
666  *
667  * NOTE: Some finalization tasks need to run before the protocol domain
668  * is detached, but also before the link layer does its cleanup.
669  *
670  * SMPNG: igmp_ifdetach() needs to take IF_ADDR_LOCK().
671  * XXX This is also bitten by unlocked ifma_protospec access.
672  */
673 void
674 igmp_ifdetach(struct ifnet *ifp)
675 {
676         struct epoch_tracker     et;
677         struct igmp_ifsoftc     *igi;
678         struct ifmultiaddr      *ifma;
679         struct in_multi         *inm;
680         struct in_multi_head inm_free_tmp;
681         CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)", __func__, ifp,
682             ifp->if_xname);
683
684         SLIST_INIT(&inm_free_tmp);
685         IGMP_LOCK();
686
687         igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
688         if (igi->igi_version == IGMP_VERSION_3) {
689                 IF_ADDR_WLOCK(ifp);
690                 NET_EPOCH_ENTER(et);
691                 CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
692                         inm = inm_ifmultiaddr_get_inm(ifma);
693                         if (inm == NULL)
694                                 continue;
695                         if (inm->inm_state == IGMP_LEAVING_MEMBER)
696                                 inm_rele_locked(&inm_free_tmp, inm);
697                         inm_clear_recorded(inm);
698                 }
699                 NET_EPOCH_EXIT(et);
700                 IF_ADDR_WUNLOCK(ifp);
701                 inm_release_list_deferred(&inm_free_tmp);
702         }
703         IGMP_UNLOCK();
704
705 }
706
707 /*
708  * Hook for domifdetach.
709  */
710 void
711 igmp_domifdetach(struct ifnet *ifp)
712 {
713
714         CTR3(KTR_IGMPV3, "%s: called for ifp %p(%s)",
715             __func__, ifp, ifp->if_xname);
716
717         IGMP_LOCK();
718         igi_delete_locked(ifp);
719         IGMP_UNLOCK();
720 }
721
722 static void
723 igi_delete_locked(const struct ifnet *ifp)
724 {
725         struct igmp_ifsoftc *igi, *tigi;
726
727         CTR3(KTR_IGMPV3, "%s: freeing igmp_ifsoftc for ifp %p(%s)",
728             __func__, ifp, ifp->if_xname);
729
730         IGMP_LOCK_ASSERT();
731
732         LIST_FOREACH_SAFE(igi, &V_igi_head, igi_link, tigi) {
733                 if (igi->igi_ifp == ifp) {
734                         /*
735                          * Free deferred General Query responses.
736                          */
737                         mbufq_drain(&igi->igi_gq);
738
739                         LIST_REMOVE(igi, igi_link);
740                         free(igi, M_IGMP);
741                         return;
742                 }
743         }
744 }
745
746 /*
747  * Process a received IGMPv1 query.
748  * Return non-zero if the message should be dropped.
749  *
750  * VIMAGE: The curvnet pointer is derived from the input ifp.
751  */
752 static int
753 igmp_input_v1_query(struct ifnet *ifp, const struct ip *ip,
754     const struct igmp *igmp)
755 {
756         struct ifmultiaddr      *ifma;
757         struct igmp_ifsoftc     *igi;
758         struct in_multi         *inm;
759
760         NET_EPOCH_ASSERT();
761
762         /*
763          * IGMPv1 Host Mmembership Queries SHOULD always be addressed to
764          * 224.0.0.1. They are always treated as General Queries.
765          * igmp_group is always ignored. Do not drop it as a userland
766          * daemon may wish to see it.
767          * XXX SMPng: unlocked increments in igmpstat assumed atomic.
768          */
769         if (!in_allhosts(ip->ip_dst) || !in_nullhost(igmp->igmp_group)) {
770                 IGMPSTAT_INC(igps_rcv_badqueries);
771                 return (0);
772         }
773         IGMPSTAT_INC(igps_rcv_gen_queries);
774
775         IN_MULTI_LIST_LOCK();
776         IGMP_LOCK();
777
778         igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
779         KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
780
781         if (igi->igi_flags & IGIF_LOOPBACK) {
782                 CTR2(KTR_IGMPV3, "ignore v1 query on IGIF_LOOPBACK ifp %p(%s)",
783                     ifp, ifp->if_xname);
784                 goto out_locked;
785         }
786
787         /*
788          * Switch to IGMPv1 host compatibility mode.
789          */
790         igmp_set_version(igi, IGMP_VERSION_1);
791
792         CTR2(KTR_IGMPV3, "process v1 query on ifp %p(%s)", ifp, ifp->if_xname);
793
794         /*
795          * Start the timers in all of our group records
796          * for the interface on which the query arrived,
797          * except those which are already running.
798          */
799         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
800                 inm = inm_ifmultiaddr_get_inm(ifma);
801                 if (inm == NULL)
802                         continue;
803                 if (inm->inm_timer != 0)
804                         continue;
805                 switch (inm->inm_state) {
806                 case IGMP_NOT_MEMBER:
807                 case IGMP_SILENT_MEMBER:
808                         break;
809                 case IGMP_G_QUERY_PENDING_MEMBER:
810                 case IGMP_SG_QUERY_PENDING_MEMBER:
811                 case IGMP_REPORTING_MEMBER:
812                 case IGMP_IDLE_MEMBER:
813                 case IGMP_LAZY_MEMBER:
814                 case IGMP_SLEEPING_MEMBER:
815                 case IGMP_AWAKENING_MEMBER:
816                         inm->inm_state = IGMP_REPORTING_MEMBER;
817                         inm->inm_timer = IGMP_RANDOM_DELAY(
818                             IGMP_V1V2_MAX_RI * PR_FASTHZ);
819                         V_current_state_timers_running = 1;
820                         break;
821                 case IGMP_LEAVING_MEMBER:
822                         break;
823                 }
824         }
825
826 out_locked:
827         IGMP_UNLOCK();
828         IN_MULTI_LIST_UNLOCK();
829
830         return (0);
831 }
832
833 /*
834  * Process a received IGMPv2 general or group-specific query.
835  */
836 static int
837 igmp_input_v2_query(struct ifnet *ifp, const struct ip *ip,
838     const struct igmp *igmp)
839 {
840         struct ifmultiaddr      *ifma;
841         struct igmp_ifsoftc     *igi;
842         struct in_multi         *inm;
843         int                      is_general_query;
844         uint16_t                 timer;
845
846         NET_EPOCH_ASSERT();
847
848         is_general_query = 0;
849
850         /*
851          * Validate address fields upfront.
852          * XXX SMPng: unlocked increments in igmpstat assumed atomic.
853          */
854         if (in_nullhost(igmp->igmp_group)) {
855                 /*
856                  * IGMPv2 General Query.
857                  * If this was not sent to the all-hosts group, ignore it.
858                  */
859                 if (!in_allhosts(ip->ip_dst))
860                         return (0);
861                 IGMPSTAT_INC(igps_rcv_gen_queries);
862                 is_general_query = 1;
863         } else {
864                 /* IGMPv2 Group-Specific Query. */
865                 IGMPSTAT_INC(igps_rcv_group_queries);
866         }
867
868         IN_MULTI_LIST_LOCK();
869         IGMP_LOCK();
870
871         igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
872         KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
873
874         if (igi->igi_flags & IGIF_LOOPBACK) {
875                 CTR2(KTR_IGMPV3, "ignore v2 query on IGIF_LOOPBACK ifp %p(%s)",
876                     ifp, ifp->if_xname);
877                 goto out_locked;
878         }
879
880         /*
881          * Ignore v2 query if in v1 Compatibility Mode.
882          */
883         if (igi->igi_version == IGMP_VERSION_1)
884                 goto out_locked;
885
886         igmp_set_version(igi, IGMP_VERSION_2);
887
888         timer = igmp->igmp_code * PR_FASTHZ / IGMP_TIMER_SCALE;
889         if (timer == 0)
890                 timer = 1;
891
892         if (is_general_query) {
893                 /*
894                  * For each reporting group joined on this
895                  * interface, kick the report timer.
896                  */
897                 CTR2(KTR_IGMPV3, "process v2 general query on ifp %p(%s)",
898                     ifp, ifp->if_xname);
899                 CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
900                         inm = inm_ifmultiaddr_get_inm(ifma);
901                         if (inm == NULL)
902                                 continue;
903                         igmp_v2_update_group(inm, timer);
904                 }
905         } else {
906                 /*
907                  * Group-specific IGMPv2 query, we need only
908                  * look up the single group to process it.
909                  */
910                 inm = inm_lookup(ifp, igmp->igmp_group);
911                 if (inm != NULL) {
912                         CTR3(KTR_IGMPV3,
913                             "process v2 query 0x%08x on ifp %p(%s)",
914                             ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
915                         igmp_v2_update_group(inm, timer);
916                 }
917         }
918
919 out_locked:
920         IGMP_UNLOCK();
921         IN_MULTI_LIST_UNLOCK();
922
923         return (0);
924 }
925
926 /*
927  * Update the report timer on a group in response to an IGMPv2 query.
928  *
929  * If we are becoming the reporting member for this group, start the timer.
930  * If we already are the reporting member for this group, and timer is
931  * below the threshold, reset it.
932  *
933  * We may be updating the group for the first time since we switched
934  * to IGMPv3. If we are, then we must clear any recorded source lists,
935  * and transition to REPORTING state; the group timer is overloaded
936  * for group and group-source query responses.
937  *
938  * Unlike IGMPv3, the delay per group should be jittered
939  * to avoid bursts of IGMPv2 reports.
940  */
941 static void
942 igmp_v2_update_group(struct in_multi *inm, const int timer)
943 {
944
945         CTR4(KTR_IGMPV3, "0x%08x: %s/%s timer=%d", __func__,
946             ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname, timer);
947
948         IN_MULTI_LIST_LOCK_ASSERT();
949
950         switch (inm->inm_state) {
951         case IGMP_NOT_MEMBER:
952         case IGMP_SILENT_MEMBER:
953                 break;
954         case IGMP_REPORTING_MEMBER:
955                 if (inm->inm_timer != 0 &&
956                     inm->inm_timer <= timer) {
957                         CTR1(KTR_IGMPV3, "%s: REPORTING and timer running, "
958                             "skipping.", __func__);
959                         break;
960                 }
961                 /* FALLTHROUGH */
962         case IGMP_SG_QUERY_PENDING_MEMBER:
963         case IGMP_G_QUERY_PENDING_MEMBER:
964         case IGMP_IDLE_MEMBER:
965         case IGMP_LAZY_MEMBER:
966         case IGMP_AWAKENING_MEMBER:
967                 CTR1(KTR_IGMPV3, "%s: ->REPORTING", __func__);
968                 inm->inm_state = IGMP_REPORTING_MEMBER;
969                 inm->inm_timer = IGMP_RANDOM_DELAY(timer);
970                 V_current_state_timers_running = 1;
971                 break;
972         case IGMP_SLEEPING_MEMBER:
973                 CTR1(KTR_IGMPV3, "%s: ->AWAKENING", __func__);
974                 inm->inm_state = IGMP_AWAKENING_MEMBER;
975                 break;
976         case IGMP_LEAVING_MEMBER:
977                 break;
978         }
979 }
980
981 /*
982  * Process a received IGMPv3 general, group-specific or
983  * group-and-source-specific query.
984  * Assumes m has already been pulled up to the full IGMP message length.
985  * Return 0 if successful, otherwise an appropriate error code is returned.
986  */
987 static int
988 igmp_input_v3_query(struct ifnet *ifp, const struct ip *ip,
989     /*const*/ struct igmpv3 *igmpv3)
990 {
991         struct igmp_ifsoftc     *igi;
992         struct in_multi         *inm;
993         int                      is_general_query;
994         uint32_t                 maxresp, nsrc, qqi;
995         uint16_t                 timer;
996         uint8_t                  qrv;
997
998         is_general_query = 0;
999
1000         CTR2(KTR_IGMPV3, "process v3 query on ifp %p(%s)", ifp, ifp->if_xname);
1001
1002         maxresp = igmpv3->igmp_code;    /* in 1/10ths of a second */
1003         if (maxresp >= 128) {
1004                 maxresp = IGMP_MANT(igmpv3->igmp_code) <<
1005                           (IGMP_EXP(igmpv3->igmp_code) + 3);
1006         }
1007
1008         /*
1009          * Robustness must never be less than 2 for on-wire IGMPv3.
1010          * FUTURE: Check if ifp has IGIF_LOOPBACK set, as we will make
1011          * an exception for interfaces whose IGMPv3 state changes
1012          * are redirected to loopback (e.g. MANET).
1013          */
1014         qrv = IGMP_QRV(igmpv3->igmp_misc);
1015         if (qrv < 2) {
1016                 CTR3(KTR_IGMPV3, "%s: clamping qrv %d to %d", __func__,
1017                     qrv, IGMP_RV_INIT);
1018                 qrv = IGMP_RV_INIT;
1019         }
1020
1021         qqi = igmpv3->igmp_qqi;
1022         if (qqi >= 128) {
1023                 qqi = IGMP_MANT(igmpv3->igmp_qqi) <<
1024                      (IGMP_EXP(igmpv3->igmp_qqi) + 3);
1025         }
1026
1027         timer = maxresp * PR_FASTHZ / IGMP_TIMER_SCALE;
1028         if (timer == 0)
1029                 timer = 1;
1030
1031         nsrc = ntohs(igmpv3->igmp_numsrc);
1032
1033         /*
1034          * Validate address fields and versions upfront before
1035          * accepting v3 query.
1036          * XXX SMPng: Unlocked access to igmpstat counters here.
1037          */
1038         if (in_nullhost(igmpv3->igmp_group)) {
1039                 /*
1040                  * IGMPv3 General Query.
1041                  *
1042                  * General Queries SHOULD be directed to 224.0.0.1.
1043                  * A general query with a source list has undefined
1044                  * behaviour; discard it.
1045                  */
1046                 IGMPSTAT_INC(igps_rcv_gen_queries);
1047                 if (!in_allhosts(ip->ip_dst) || nsrc > 0) {
1048                         IGMPSTAT_INC(igps_rcv_badqueries);
1049                         return (0);
1050                 }
1051                 is_general_query = 1;
1052         } else {
1053                 /* Group or group-source specific query. */
1054                 if (nsrc == 0)
1055                         IGMPSTAT_INC(igps_rcv_group_queries);
1056                 else
1057                         IGMPSTAT_INC(igps_rcv_gsr_queries);
1058         }
1059
1060         IN_MULTI_LIST_LOCK();
1061         IGMP_LOCK();
1062
1063         igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
1064         KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
1065
1066         if (igi->igi_flags & IGIF_LOOPBACK) {
1067                 CTR2(KTR_IGMPV3, "ignore v3 query on IGIF_LOOPBACK ifp %p(%s)",
1068                     ifp, ifp->if_xname);
1069                 goto out_locked;
1070         }
1071
1072         /*
1073          * Discard the v3 query if we're in Compatibility Mode.
1074          * The RFC is not obviously worded that hosts need to stay in
1075          * compatibility mode until the Old Version Querier Present
1076          * timer expires.
1077          */
1078         if (igi->igi_version != IGMP_VERSION_3) {
1079                 CTR3(KTR_IGMPV3, "ignore v3 query in v%d mode on ifp %p(%s)",
1080                     igi->igi_version, ifp, ifp->if_xname);
1081                 goto out_locked;
1082         }
1083
1084         igmp_set_version(igi, IGMP_VERSION_3);
1085         igi->igi_rv = qrv;
1086         igi->igi_qi = qqi;
1087         igi->igi_qri = maxresp;
1088
1089         CTR4(KTR_IGMPV3, "%s: qrv %d qi %d qri %d", __func__, qrv, qqi,
1090             maxresp);
1091
1092         if (is_general_query) {
1093                 /*
1094                  * Schedule a current-state report on this ifp for
1095                  * all groups, possibly containing source lists.
1096                  * If there is a pending General Query response
1097                  * scheduled earlier than the selected delay, do
1098                  * not schedule any other reports.
1099                  * Otherwise, reset the interface timer.
1100                  */
1101                 CTR2(KTR_IGMPV3, "process v3 general query on ifp %p(%s)",
1102                     ifp, ifp->if_xname);
1103                 if (igi->igi_v3_timer == 0 || igi->igi_v3_timer >= timer) {
1104                         igi->igi_v3_timer = IGMP_RANDOM_DELAY(timer);
1105                         V_interface_timers_running = 1;
1106                 }
1107         } else {
1108                 /*
1109                  * Group-source-specific queries are throttled on
1110                  * a per-group basis to defeat denial-of-service attempts.
1111                  * Queries for groups we are not a member of on this
1112                  * link are simply ignored.
1113                  */
1114                 inm = inm_lookup(ifp, igmpv3->igmp_group);
1115                 if (inm == NULL)
1116                         goto out_locked;
1117                 if (nsrc > 0) {
1118                         if (!ratecheck(&inm->inm_lastgsrtv,
1119                             &V_igmp_gsrdelay)) {
1120                                 CTR1(KTR_IGMPV3, "%s: GS query throttled.",
1121                                     __func__);
1122                                 IGMPSTAT_INC(igps_drop_gsr_queries);
1123                                 goto out_locked;
1124                         }
1125                 }
1126                 CTR3(KTR_IGMPV3, "process v3 0x%08x query on ifp %p(%s)",
1127                      ntohl(igmpv3->igmp_group.s_addr), ifp, ifp->if_xname);
1128                 /*
1129                  * If there is a pending General Query response
1130                  * scheduled sooner than the selected delay, no
1131                  * further report need be scheduled.
1132                  * Otherwise, prepare to respond to the
1133                  * group-specific or group-and-source query.
1134                  */
1135                 if (igi->igi_v3_timer == 0 || igi->igi_v3_timer >= timer)
1136                         igmp_input_v3_group_query(inm, igi, timer, igmpv3);
1137         }
1138
1139 out_locked:
1140         IGMP_UNLOCK();
1141         IN_MULTI_LIST_UNLOCK();
1142
1143         return (0);
1144 }
1145
1146 /*
1147  * Process a received IGMPv3 group-specific or group-and-source-specific
1148  * query.
1149  * Return <0 if any error occurred. Currently this is ignored.
1150  */
1151 static int
1152 igmp_input_v3_group_query(struct in_multi *inm, struct igmp_ifsoftc *igi,
1153     int timer, /*const*/ struct igmpv3 *igmpv3)
1154 {
1155         int                      retval;
1156         uint16_t                 nsrc;
1157
1158         IN_MULTI_LIST_LOCK_ASSERT();
1159         IGMP_LOCK_ASSERT();
1160
1161         retval = 0;
1162
1163         switch (inm->inm_state) {
1164         case IGMP_NOT_MEMBER:
1165         case IGMP_SILENT_MEMBER:
1166         case IGMP_SLEEPING_MEMBER:
1167         case IGMP_LAZY_MEMBER:
1168         case IGMP_AWAKENING_MEMBER:
1169         case IGMP_IDLE_MEMBER:
1170         case IGMP_LEAVING_MEMBER:
1171                 return (retval);
1172                 break;
1173         case IGMP_REPORTING_MEMBER:
1174         case IGMP_G_QUERY_PENDING_MEMBER:
1175         case IGMP_SG_QUERY_PENDING_MEMBER:
1176                 break;
1177         }
1178
1179         nsrc = ntohs(igmpv3->igmp_numsrc);
1180
1181         /*
1182          * Deal with group-specific queries upfront.
1183          * If any group query is already pending, purge any recorded
1184          * source-list state if it exists, and schedule a query response
1185          * for this group-specific query.
1186          */
1187         if (nsrc == 0) {
1188                 if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER ||
1189                     inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER) {
1190                         inm_clear_recorded(inm);
1191                         timer = min(inm->inm_timer, timer);
1192                 }
1193                 inm->inm_state = IGMP_G_QUERY_PENDING_MEMBER;
1194                 inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1195                 V_current_state_timers_running = 1;
1196                 return (retval);
1197         }
1198
1199         /*
1200          * Deal with the case where a group-and-source-specific query has
1201          * been received but a group-specific query is already pending.
1202          */
1203         if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER) {
1204                 timer = min(inm->inm_timer, timer);
1205                 inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1206                 V_current_state_timers_running = 1;
1207                 return (retval);
1208         }
1209
1210         /*
1211          * Finally, deal with the case where a group-and-source-specific
1212          * query has been received, where a response to a previous g-s-r
1213          * query exists, or none exists.
1214          * In this case, we need to parse the source-list which the Querier
1215          * has provided us with and check if we have any source list filter
1216          * entries at T1 for these sources. If we do not, there is no need
1217          * schedule a report and the query may be dropped.
1218          * If we do, we must record them and schedule a current-state
1219          * report for those sources.
1220          * FIXME: Handling source lists larger than 1 mbuf requires that
1221          * we pass the mbuf chain pointer down to this function, and use
1222          * m_getptr() to walk the chain.
1223          */
1224         if (inm->inm_nsrc > 0) {
1225                 const struct in_addr    *ap;
1226                 int                      i, nrecorded;
1227
1228                 ap = (const struct in_addr *)(igmpv3 + 1);
1229                 nrecorded = 0;
1230                 for (i = 0; i < nsrc; i++, ap++) {
1231                         retval = inm_record_source(inm, ap->s_addr);
1232                         if (retval < 0)
1233                                 break;
1234                         nrecorded += retval;
1235                 }
1236                 if (nrecorded > 0) {
1237                         CTR1(KTR_IGMPV3,
1238                             "%s: schedule response to SG query", __func__);
1239                         inm->inm_state = IGMP_SG_QUERY_PENDING_MEMBER;
1240                         inm->inm_timer = IGMP_RANDOM_DELAY(timer);
1241                         V_current_state_timers_running = 1;
1242                 }
1243         }
1244
1245         return (retval);
1246 }
1247
1248 /*
1249  * Process a received IGMPv1 host membership report.
1250  *
1251  * NOTE: 0.0.0.0 workaround breaks const correctness.
1252  */
1253 static int
1254 igmp_input_v1_report(struct ifnet *ifp, /*const*/ struct ip *ip,
1255     /*const*/ struct igmp *igmp)
1256 {
1257         struct rm_priotracker in_ifa_tracker;
1258         struct in_ifaddr *ia;
1259         struct in_multi *inm;
1260
1261         IGMPSTAT_INC(igps_rcv_reports);
1262
1263         if (ifp->if_flags & IFF_LOOPBACK)
1264                 return (0);
1265
1266         if (!IN_MULTICAST(ntohl(igmp->igmp_group.s_addr)) ||
1267             !in_hosteq(igmp->igmp_group, ip->ip_dst)) {
1268                 IGMPSTAT_INC(igps_rcv_badreports);
1269                 return (EINVAL);
1270         }
1271
1272         /*
1273          * RFC 3376, Section 4.2.13, 9.2, 9.3:
1274          * Booting clients may use the source address 0.0.0.0. Some
1275          * IGMP daemons may not know how to use IP_RECVIF to determine
1276          * the interface upon which this message was received.
1277          * Replace 0.0.0.0 with the subnet address if told to do so.
1278          */
1279         if (V_igmp_recvifkludge && in_nullhost(ip->ip_src)) {
1280                 IFP_TO_IA(ifp, ia, &in_ifa_tracker);
1281                 if (ia != NULL)
1282                         ip->ip_src.s_addr = htonl(ia->ia_subnet);
1283         }
1284
1285         CTR3(KTR_IGMPV3, "process v1 report 0x%08x on ifp %p(%s)",
1286              ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1287
1288         /*
1289          * IGMPv1 report suppression.
1290          * If we are a member of this group, and our membership should be
1291          * reported, stop our group timer and transition to the 'lazy' state.
1292          */
1293         IN_MULTI_LIST_LOCK();
1294         inm = inm_lookup(ifp, igmp->igmp_group);
1295         if (inm != NULL) {
1296                 struct igmp_ifsoftc *igi;
1297
1298                 igi = inm->inm_igi;
1299                 if (igi == NULL) {
1300                         KASSERT(igi != NULL,
1301                             ("%s: no igi for ifp %p", __func__, ifp));
1302                         goto out_locked;
1303                 }
1304
1305                 IGMPSTAT_INC(igps_rcv_ourreports);
1306
1307                 /*
1308                  * If we are in IGMPv3 host mode, do not allow the
1309                  * other host's IGMPv1 report to suppress our reports
1310                  * unless explicitly configured to do so.
1311                  */
1312                 if (igi->igi_version == IGMP_VERSION_3) {
1313                         if (V_igmp_legacysupp)
1314                                 igmp_v3_suppress_group_record(inm);
1315                         goto out_locked;
1316                 }
1317
1318                 inm->inm_timer = 0;
1319
1320                 switch (inm->inm_state) {
1321                 case IGMP_NOT_MEMBER:
1322                 case IGMP_SILENT_MEMBER:
1323                         break;
1324                 case IGMP_IDLE_MEMBER:
1325                 case IGMP_LAZY_MEMBER:
1326                 case IGMP_AWAKENING_MEMBER:
1327                         CTR3(KTR_IGMPV3,
1328                             "report suppressed for 0x%08x on ifp %p(%s)",
1329                             ntohl(igmp->igmp_group.s_addr), ifp,
1330                             ifp->if_xname);
1331                 case IGMP_SLEEPING_MEMBER:
1332                         inm->inm_state = IGMP_SLEEPING_MEMBER;
1333                         break;
1334                 case IGMP_REPORTING_MEMBER:
1335                         CTR3(KTR_IGMPV3,
1336                             "report suppressed for 0x%08x on ifp %p(%s)",
1337                             ntohl(igmp->igmp_group.s_addr), ifp,
1338                             ifp->if_xname);
1339                         if (igi->igi_version == IGMP_VERSION_1)
1340                                 inm->inm_state = IGMP_LAZY_MEMBER;
1341                         else if (igi->igi_version == IGMP_VERSION_2)
1342                                 inm->inm_state = IGMP_SLEEPING_MEMBER;
1343                         break;
1344                 case IGMP_G_QUERY_PENDING_MEMBER:
1345                 case IGMP_SG_QUERY_PENDING_MEMBER:
1346                 case IGMP_LEAVING_MEMBER:
1347                         break;
1348                 }
1349         }
1350
1351 out_locked:
1352         IN_MULTI_LIST_UNLOCK();
1353
1354         return (0);
1355 }
1356
1357 /*
1358  * Process a received IGMPv2 host membership report.
1359  *
1360  * NOTE: 0.0.0.0 workaround breaks const correctness.
1361  */
1362 static int
1363 igmp_input_v2_report(struct ifnet *ifp, /*const*/ struct ip *ip,
1364     /*const*/ struct igmp *igmp)
1365 {
1366         struct rm_priotracker in_ifa_tracker;
1367         struct in_ifaddr *ia;
1368         struct in_multi *inm;
1369
1370         /*
1371          * Make sure we don't hear our own membership report.  Fast
1372          * leave requires knowing that we are the only member of a
1373          * group.
1374          */
1375         IFP_TO_IA(ifp, ia, &in_ifa_tracker);
1376         if (ia != NULL && in_hosteq(ip->ip_src, IA_SIN(ia)->sin_addr)) {
1377                 return (0);
1378         }
1379
1380         IGMPSTAT_INC(igps_rcv_reports);
1381
1382         if (ifp->if_flags & IFF_LOOPBACK) {
1383                 return (0);
1384         }
1385
1386         if (!IN_MULTICAST(ntohl(igmp->igmp_group.s_addr)) ||
1387             !in_hosteq(igmp->igmp_group, ip->ip_dst)) {
1388                 IGMPSTAT_INC(igps_rcv_badreports);
1389                 return (EINVAL);
1390         }
1391
1392         /*
1393          * RFC 3376, Section 4.2.13, 9.2, 9.3:
1394          * Booting clients may use the source address 0.0.0.0. Some
1395          * IGMP daemons may not know how to use IP_RECVIF to determine
1396          * the interface upon which this message was received.
1397          * Replace 0.0.0.0 with the subnet address if told to do so.
1398          */
1399         if (V_igmp_recvifkludge && in_nullhost(ip->ip_src)) {
1400                 if (ia != NULL)
1401                         ip->ip_src.s_addr = htonl(ia->ia_subnet);
1402         }
1403
1404         CTR3(KTR_IGMPV3, "process v2 report 0x%08x on ifp %p(%s)",
1405              ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1406
1407         /*
1408          * IGMPv2 report suppression.
1409          * If we are a member of this group, and our membership should be
1410          * reported, and our group timer is pending or about to be reset,
1411          * stop our group timer by transitioning to the 'lazy' state.
1412          */
1413         IN_MULTI_LIST_LOCK();
1414         inm = inm_lookup(ifp, igmp->igmp_group);
1415         if (inm != NULL) {
1416                 struct igmp_ifsoftc *igi;
1417
1418                 igi = inm->inm_igi;
1419                 KASSERT(igi != NULL, ("%s: no igi for ifp %p", __func__, ifp));
1420
1421                 IGMPSTAT_INC(igps_rcv_ourreports);
1422
1423                 /*
1424                  * If we are in IGMPv3 host mode, do not allow the
1425                  * other host's IGMPv1 report to suppress our reports
1426                  * unless explicitly configured to do so.
1427                  */
1428                 if (igi->igi_version == IGMP_VERSION_3) {
1429                         if (V_igmp_legacysupp)
1430                                 igmp_v3_suppress_group_record(inm);
1431                         goto out_locked;
1432                 }
1433
1434                 inm->inm_timer = 0;
1435
1436                 switch (inm->inm_state) {
1437                 case IGMP_NOT_MEMBER:
1438                 case IGMP_SILENT_MEMBER:
1439                 case IGMP_SLEEPING_MEMBER:
1440                         break;
1441                 case IGMP_REPORTING_MEMBER:
1442                 case IGMP_IDLE_MEMBER:
1443                 case IGMP_AWAKENING_MEMBER:
1444                         CTR3(KTR_IGMPV3,
1445                             "report suppressed for 0x%08x on ifp %p(%s)",
1446                             ntohl(igmp->igmp_group.s_addr), ifp, ifp->if_xname);
1447                 case IGMP_LAZY_MEMBER:
1448                         inm->inm_state = IGMP_LAZY_MEMBER;
1449                         break;
1450                 case IGMP_G_QUERY_PENDING_MEMBER:
1451                 case IGMP_SG_QUERY_PENDING_MEMBER:
1452                 case IGMP_LEAVING_MEMBER:
1453                         break;
1454                 }
1455         }
1456
1457 out_locked:
1458         IN_MULTI_LIST_UNLOCK();
1459
1460         return (0);
1461 }
1462
1463 int
1464 igmp_input(struct mbuf **mp, int *offp, int proto)
1465 {
1466         int iphlen;
1467         struct ifnet *ifp;
1468         struct igmp *igmp;
1469         struct ip *ip;
1470         struct mbuf *m;
1471         int igmplen;
1472         int minlen;
1473         int queryver;
1474
1475         CTR3(KTR_IGMPV3, "%s: called w/mbuf (%p,%d)", __func__, *mp, *offp);
1476
1477         m = *mp;
1478         ifp = m->m_pkthdr.rcvif;
1479         *mp = NULL;
1480
1481         IGMPSTAT_INC(igps_rcv_total);
1482
1483         ip = mtod(m, struct ip *);
1484         iphlen = *offp;
1485         igmplen = ntohs(ip->ip_len) - iphlen;
1486
1487         /*
1488          * Validate lengths.
1489          */
1490         if (igmplen < IGMP_MINLEN) {
1491                 IGMPSTAT_INC(igps_rcv_tooshort);
1492                 m_freem(m);
1493                 return (IPPROTO_DONE);
1494         }
1495
1496         /*
1497          * Always pullup to the minimum size for v1/v2 or v3
1498          * to amortize calls to m_pullup().
1499          */
1500         minlen = iphlen;
1501         if (igmplen >= IGMP_V3_QUERY_MINLEN)
1502                 minlen += IGMP_V3_QUERY_MINLEN;
1503         else
1504                 minlen += IGMP_MINLEN;
1505         if ((!M_WRITABLE(m) || m->m_len < minlen) &&
1506             (m = m_pullup(m, minlen)) == NULL) {
1507                 IGMPSTAT_INC(igps_rcv_tooshort);
1508                 return (IPPROTO_DONE);
1509         }
1510         ip = mtod(m, struct ip *);
1511
1512         /*
1513          * Validate checksum.
1514          */
1515         m->m_data += iphlen;
1516         m->m_len -= iphlen;
1517         igmp = mtod(m, struct igmp *);
1518         if (in_cksum(m, igmplen)) {
1519                 IGMPSTAT_INC(igps_rcv_badsum);
1520                 m_freem(m);
1521                 return (IPPROTO_DONE);
1522         }
1523         m->m_data -= iphlen;
1524         m->m_len += iphlen;
1525
1526         /*
1527          * IGMP control traffic is link-scope, and must have a TTL of 1.
1528          * DVMRP traffic (e.g. mrinfo, mtrace) is an exception;
1529          * probe packets may come from beyond the LAN.
1530          */
1531         if (igmp->igmp_type != IGMP_DVMRP && ip->ip_ttl != 1) {
1532                 IGMPSTAT_INC(igps_rcv_badttl);
1533                 m_freem(m);
1534                 return (IPPROTO_DONE);
1535         }
1536
1537         switch (igmp->igmp_type) {
1538         case IGMP_HOST_MEMBERSHIP_QUERY:
1539                 if (igmplen == IGMP_MINLEN) {
1540                         if (igmp->igmp_code == 0)
1541                                 queryver = IGMP_VERSION_1;
1542                         else
1543                                 queryver = IGMP_VERSION_2;
1544                 } else if (igmplen >= IGMP_V3_QUERY_MINLEN) {
1545                         queryver = IGMP_VERSION_3;
1546                 } else {
1547                         IGMPSTAT_INC(igps_rcv_tooshort);
1548                         m_freem(m);
1549                         return (IPPROTO_DONE);
1550                 }
1551
1552                 switch (queryver) {
1553                 case IGMP_VERSION_1:
1554                         IGMPSTAT_INC(igps_rcv_v1v2_queries);
1555                         if (!V_igmp_v1enable)
1556                                 break;
1557                         if (igmp_input_v1_query(ifp, ip, igmp) != 0) {
1558                                 m_freem(m);
1559                                 return (IPPROTO_DONE);
1560                         }
1561                         break;
1562
1563                 case IGMP_VERSION_2:
1564                         IGMPSTAT_INC(igps_rcv_v1v2_queries);
1565                         if (!V_igmp_v2enable)
1566                                 break;
1567                         if (igmp_input_v2_query(ifp, ip, igmp) != 0) {
1568                                 m_freem(m);
1569                                 return (IPPROTO_DONE);
1570                         }
1571                         break;
1572
1573                 case IGMP_VERSION_3: {
1574                                 struct igmpv3 *igmpv3;
1575                                 uint16_t igmpv3len;
1576                                 uint16_t nsrc;
1577
1578                                 IGMPSTAT_INC(igps_rcv_v3_queries);
1579                                 igmpv3 = (struct igmpv3 *)igmp;
1580                                 /*
1581                                  * Validate length based on source count.
1582                                  */
1583                                 nsrc = ntohs(igmpv3->igmp_numsrc);
1584                                 if (nsrc * sizeof(in_addr_t) >
1585                                     UINT16_MAX - iphlen - IGMP_V3_QUERY_MINLEN) {
1586                                         IGMPSTAT_INC(igps_rcv_tooshort);
1587                                         m_freem(m);
1588                                         return (IPPROTO_DONE);
1589                                 }
1590                                 /*
1591                                  * m_pullup() may modify m, so pullup in
1592                                  * this scope.
1593                                  */
1594                                 igmpv3len = iphlen + IGMP_V3_QUERY_MINLEN +
1595                                    sizeof(struct in_addr) * nsrc;
1596                                 if ((!M_WRITABLE(m) ||
1597                                      m->m_len < igmpv3len) &&
1598                                     (m = m_pullup(m, igmpv3len)) == NULL) {
1599                                         IGMPSTAT_INC(igps_rcv_tooshort);
1600                                         return (IPPROTO_DONE);
1601                                 }
1602                                 igmpv3 = (struct igmpv3 *)(mtod(m, uint8_t *)
1603                                     + iphlen);
1604                                 if (igmp_input_v3_query(ifp, ip, igmpv3) != 0) {
1605                                         m_freem(m);
1606                                         return (IPPROTO_DONE);
1607                                 }
1608                         }
1609                         break;
1610                 }
1611                 break;
1612
1613         case IGMP_v1_HOST_MEMBERSHIP_REPORT:
1614                 if (!V_igmp_v1enable)
1615                         break;
1616                 if (igmp_input_v1_report(ifp, ip, igmp) != 0) {
1617                         m_freem(m);
1618                         return (IPPROTO_DONE);
1619                 }
1620                 break;
1621
1622         case IGMP_v2_HOST_MEMBERSHIP_REPORT:
1623                 if (!V_igmp_v2enable)
1624                         break;
1625                 if (!ip_checkrouteralert(m))
1626                         IGMPSTAT_INC(igps_rcv_nora);
1627                 if (igmp_input_v2_report(ifp, ip, igmp) != 0) {
1628                         m_freem(m);
1629                         return (IPPROTO_DONE);
1630                 }
1631                 break;
1632
1633         case IGMP_v3_HOST_MEMBERSHIP_REPORT:
1634                 /*
1635                  * Hosts do not need to process IGMPv3 membership reports,
1636                  * as report suppression is no longer required.
1637                  */
1638                 if (!ip_checkrouteralert(m))
1639                         IGMPSTAT_INC(igps_rcv_nora);
1640                 break;
1641
1642         default:
1643                 break;
1644         }
1645
1646         /*
1647          * Pass all valid IGMP packets up to any process(es) listening on a
1648          * raw IGMP socket.
1649          */
1650         *mp = m;
1651         return (rip_input(mp, offp, proto));
1652 }
1653
1654 /*
1655  * Fast timeout handler (global).
1656  * VIMAGE: Timeout handlers are expected to service all vimages.
1657  */
1658 void
1659 igmp_fasttimo(void)
1660 {
1661         VNET_ITERATOR_DECL(vnet_iter);
1662
1663         VNET_LIST_RLOCK_NOSLEEP();
1664         VNET_FOREACH(vnet_iter) {
1665                 CURVNET_SET(vnet_iter);
1666                 igmp_fasttimo_vnet();
1667                 CURVNET_RESTORE();
1668         }
1669         VNET_LIST_RUNLOCK_NOSLEEP();
1670 }
1671
1672 /*
1673  * Fast timeout handler (per-vnet).
1674  * Sends are shuffled off to a netisr to deal with Giant.
1675  *
1676  * VIMAGE: Assume caller has set up our curvnet.
1677  */
1678 static void
1679 igmp_fasttimo_vnet(void)
1680 {
1681         struct mbufq             scq;   /* State-change packets */
1682         struct mbufq             qrq;   /* Query response packets */
1683         struct ifnet            *ifp;
1684         struct igmp_ifsoftc     *igi;
1685         struct ifmultiaddr      *ifma;
1686         struct in_multi         *inm;
1687         struct in_multi_head inm_free_tmp;
1688         int                      loop, uri_fasthz;
1689
1690         loop = 0;
1691         uri_fasthz = 0;
1692
1693         /*
1694          * Quick check to see if any work needs to be done, in order to
1695          * minimize the overhead of fasttimo processing.
1696          * SMPng: XXX Unlocked reads.
1697          */
1698         if (!V_current_state_timers_running &&
1699             !V_interface_timers_running &&
1700             !V_state_change_timers_running)
1701                 return;
1702
1703         SLIST_INIT(&inm_free_tmp);
1704         IN_MULTI_LIST_LOCK();
1705         IGMP_LOCK();
1706
1707         /*
1708          * IGMPv3 General Query response timer processing.
1709          */
1710         if (V_interface_timers_running) {
1711                 CTR1(KTR_IGMPV3, "%s: interface timers running", __func__);
1712
1713                 V_interface_timers_running = 0;
1714                 LIST_FOREACH(igi, &V_igi_head, igi_link) {
1715                         if (igi->igi_v3_timer == 0) {
1716                                 /* Do nothing. */
1717                         } else if (--igi->igi_v3_timer == 0) {
1718                                 igmp_v3_dispatch_general_query(igi);
1719                         } else {
1720                                 V_interface_timers_running = 1;
1721                         }
1722                 }
1723         }
1724
1725         if (!V_current_state_timers_running &&
1726             !V_state_change_timers_running)
1727                 goto out_locked;
1728
1729         V_current_state_timers_running = 0;
1730         V_state_change_timers_running = 0;
1731
1732         CTR1(KTR_IGMPV3, "%s: state change timers running", __func__);
1733
1734         /*
1735          * IGMPv1/v2/v3 host report and state-change timer processing.
1736          * Note: Processing a v3 group timer may remove a node.
1737          */
1738         LIST_FOREACH(igi, &V_igi_head, igi_link) {
1739                 ifp = igi->igi_ifp;
1740
1741                 if (igi->igi_version == IGMP_VERSION_3) {
1742                         loop = (igi->igi_flags & IGIF_LOOPBACK) ? 1 : 0;
1743                         uri_fasthz = IGMP_RANDOM_DELAY(igi->igi_uri *
1744                             PR_FASTHZ);
1745                         mbufq_init(&qrq, IGMP_MAX_G_GS_PACKETS);
1746                         mbufq_init(&scq, IGMP_MAX_STATE_CHANGE_PACKETS);
1747                 }
1748
1749                 IF_ADDR_WLOCK(ifp);
1750                 CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1751                         inm = inm_ifmultiaddr_get_inm(ifma);
1752                         if (inm == NULL)
1753                                 continue;
1754                         switch (igi->igi_version) {
1755                         case IGMP_VERSION_1:
1756                         case IGMP_VERSION_2:
1757                                 igmp_v1v2_process_group_timer(inm,
1758                                     igi->igi_version);
1759                                 break;
1760                         case IGMP_VERSION_3:
1761                                 igmp_v3_process_group_timers(&inm_free_tmp, &qrq,
1762                                     &scq, inm, uri_fasthz);
1763                                 break;
1764                         }
1765                 }
1766                 IF_ADDR_WUNLOCK(ifp);
1767
1768                 if (igi->igi_version == IGMP_VERSION_3) {
1769                         igmp_dispatch_queue(&qrq, 0, loop);
1770                         igmp_dispatch_queue(&scq, 0, loop);
1771
1772                         /*
1773                          * Free the in_multi reference(s) for this
1774                          * IGMP lifecycle.
1775                          */
1776                         inm_release_list_deferred(&inm_free_tmp);
1777                 }
1778         }
1779
1780 out_locked:
1781         IGMP_UNLOCK();
1782         IN_MULTI_LIST_UNLOCK();
1783 }
1784
1785 /*
1786  * Update host report group timer for IGMPv1/v2.
1787  * Will update the global pending timer flags.
1788  */
1789 static void
1790 igmp_v1v2_process_group_timer(struct in_multi *inm, const int version)
1791 {
1792         int report_timer_expired;
1793
1794         IN_MULTI_LIST_LOCK_ASSERT();
1795         IGMP_LOCK_ASSERT();
1796
1797         if (inm->inm_timer == 0) {
1798                 report_timer_expired = 0;
1799         } else if (--inm->inm_timer == 0) {
1800                 report_timer_expired = 1;
1801         } else {
1802                 V_current_state_timers_running = 1;
1803                 return;
1804         }
1805
1806         switch (inm->inm_state) {
1807         case IGMP_NOT_MEMBER:
1808         case IGMP_SILENT_MEMBER:
1809         case IGMP_IDLE_MEMBER:
1810         case IGMP_LAZY_MEMBER:
1811         case IGMP_SLEEPING_MEMBER:
1812         case IGMP_AWAKENING_MEMBER:
1813                 break;
1814         case IGMP_REPORTING_MEMBER:
1815                 if (report_timer_expired) {
1816                         inm->inm_state = IGMP_IDLE_MEMBER;
1817                         (void)igmp_v1v2_queue_report(inm,
1818                             (version == IGMP_VERSION_2) ?
1819                              IGMP_v2_HOST_MEMBERSHIP_REPORT :
1820                              IGMP_v1_HOST_MEMBERSHIP_REPORT);
1821                 }
1822                 break;
1823         case IGMP_G_QUERY_PENDING_MEMBER:
1824         case IGMP_SG_QUERY_PENDING_MEMBER:
1825         case IGMP_LEAVING_MEMBER:
1826                 break;
1827         }
1828 }
1829
1830 /*
1831  * Update a group's timers for IGMPv3.
1832  * Will update the global pending timer flags.
1833  * Note: Unlocked read from igi.
1834  */
1835 static void
1836 igmp_v3_process_group_timers(struct in_multi_head *inmh,
1837     struct mbufq *qrq, struct mbufq *scq,
1838     struct in_multi *inm, const int uri_fasthz)
1839 {
1840         int query_response_timer_expired;
1841         int state_change_retransmit_timer_expired;
1842
1843         IN_MULTI_LIST_LOCK_ASSERT();
1844         IGMP_LOCK_ASSERT();
1845
1846         query_response_timer_expired = 0;
1847         state_change_retransmit_timer_expired = 0;
1848
1849         /*
1850          * During a transition from v1/v2 compatibility mode back to v3,
1851          * a group record in REPORTING state may still have its group
1852          * timer active. This is a no-op in this function; it is easier
1853          * to deal with it here than to complicate the slow-timeout path.
1854          */
1855         if (inm->inm_timer == 0) {
1856                 query_response_timer_expired = 0;
1857         } else if (--inm->inm_timer == 0) {
1858                 query_response_timer_expired = 1;
1859         } else {
1860                 V_current_state_timers_running = 1;
1861         }
1862
1863         if (inm->inm_sctimer == 0) {
1864                 state_change_retransmit_timer_expired = 0;
1865         } else if (--inm->inm_sctimer == 0) {
1866                 state_change_retransmit_timer_expired = 1;
1867         } else {
1868                 V_state_change_timers_running = 1;
1869         }
1870
1871         /* We are in fasttimo, so be quick about it. */
1872         if (!state_change_retransmit_timer_expired &&
1873             !query_response_timer_expired)
1874                 return;
1875
1876         switch (inm->inm_state) {
1877         case IGMP_NOT_MEMBER:
1878         case IGMP_SILENT_MEMBER:
1879         case IGMP_SLEEPING_MEMBER:
1880         case IGMP_LAZY_MEMBER:
1881         case IGMP_AWAKENING_MEMBER:
1882         case IGMP_IDLE_MEMBER:
1883                 break;
1884         case IGMP_G_QUERY_PENDING_MEMBER:
1885         case IGMP_SG_QUERY_PENDING_MEMBER:
1886                 /*
1887                  * Respond to a previously pending Group-Specific
1888                  * or Group-and-Source-Specific query by enqueueing
1889                  * the appropriate Current-State report for
1890                  * immediate transmission.
1891                  */
1892                 if (query_response_timer_expired) {
1893                         int retval __unused;
1894
1895                         retval = igmp_v3_enqueue_group_record(qrq, inm, 0, 1,
1896                             (inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER));
1897                         CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
1898                             __func__, retval);
1899                         inm->inm_state = IGMP_REPORTING_MEMBER;
1900                         /* XXX Clear recorded sources for next time. */
1901                         inm_clear_recorded(inm);
1902                 }
1903                 /* FALLTHROUGH */
1904         case IGMP_REPORTING_MEMBER:
1905         case IGMP_LEAVING_MEMBER:
1906                 if (state_change_retransmit_timer_expired) {
1907                         /*
1908                          * State-change retransmission timer fired.
1909                          * If there are any further pending retransmissions,
1910                          * set the global pending state-change flag, and
1911                          * reset the timer.
1912                          */
1913                         if (--inm->inm_scrv > 0) {
1914                                 inm->inm_sctimer = uri_fasthz;
1915                                 V_state_change_timers_running = 1;
1916                         }
1917                         /*
1918                          * Retransmit the previously computed state-change
1919                          * report. If there are no further pending
1920                          * retransmissions, the mbuf queue will be consumed.
1921                          * Update T0 state to T1 as we have now sent
1922                          * a state-change.
1923                          */
1924                         (void)igmp_v3_merge_state_changes(inm, scq);
1925
1926                         inm_commit(inm);
1927                         CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
1928                             ntohl(inm->inm_addr.s_addr),
1929                             inm->inm_ifp->if_xname);
1930
1931                         /*
1932                          * If we are leaving the group for good, make sure
1933                          * we release IGMP's reference to it.
1934                          * This release must be deferred using a SLIST,
1935                          * as we are called from a loop which traverses
1936                          * the in_ifmultiaddr TAILQ.
1937                          */
1938                         if (inm->inm_state == IGMP_LEAVING_MEMBER &&
1939                             inm->inm_scrv == 0) {
1940                                 inm->inm_state = IGMP_NOT_MEMBER;
1941                                 inm_rele_locked(inmh, inm);
1942                         }
1943                 }
1944                 break;
1945         }
1946 }
1947
1948 /*
1949  * Suppress a group's pending response to a group or source/group query.
1950  *
1951  * Do NOT suppress state changes. This leads to IGMPv3 inconsistency.
1952  * Do NOT update ST1/ST0 as this operation merely suppresses
1953  * the currently pending group record.
1954  * Do NOT suppress the response to a general query. It is possible but
1955  * it would require adding another state or flag.
1956  */
1957 static void
1958 igmp_v3_suppress_group_record(struct in_multi *inm)
1959 {
1960
1961         IN_MULTI_LIST_LOCK_ASSERT();
1962
1963         KASSERT(inm->inm_igi->igi_version == IGMP_VERSION_3,
1964                 ("%s: not IGMPv3 mode on link", __func__));
1965
1966         if (inm->inm_state != IGMP_G_QUERY_PENDING_MEMBER ||
1967             inm->inm_state != IGMP_SG_QUERY_PENDING_MEMBER)
1968                 return;
1969
1970         if (inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER)
1971                 inm_clear_recorded(inm);
1972
1973         inm->inm_timer = 0;
1974         inm->inm_state = IGMP_REPORTING_MEMBER;
1975 }
1976
1977 /*
1978  * Switch to a different IGMP version on the given interface,
1979  * as per Section 7.2.1.
1980  */
1981 static void
1982 igmp_set_version(struct igmp_ifsoftc *igi, const int version)
1983 {
1984         int old_version_timer;
1985
1986         IGMP_LOCK_ASSERT();
1987
1988         CTR4(KTR_IGMPV3, "%s: switching to v%d on ifp %p(%s)", __func__,
1989             version, igi->igi_ifp, igi->igi_ifp->if_xname);
1990
1991         if (version == IGMP_VERSION_1 || version == IGMP_VERSION_2) {
1992                 /*
1993                  * Compute the "Older Version Querier Present" timer as per
1994                  * Section 8.12.
1995                  */
1996                 old_version_timer = igi->igi_rv * igi->igi_qi + igi->igi_qri;
1997                 old_version_timer *= PR_SLOWHZ;
1998
1999                 if (version == IGMP_VERSION_1) {
2000                         igi->igi_v1_timer = old_version_timer;
2001                         igi->igi_v2_timer = 0;
2002                 } else if (version == IGMP_VERSION_2) {
2003                         igi->igi_v1_timer = 0;
2004                         igi->igi_v2_timer = old_version_timer;
2005                 }
2006         }
2007
2008         if (igi->igi_v1_timer == 0 && igi->igi_v2_timer > 0) {
2009                 if (igi->igi_version != IGMP_VERSION_2) {
2010                         igi->igi_version = IGMP_VERSION_2;
2011                         igmp_v3_cancel_link_timers(igi);
2012                 }
2013         } else if (igi->igi_v1_timer > 0) {
2014                 if (igi->igi_version != IGMP_VERSION_1) {
2015                         igi->igi_version = IGMP_VERSION_1;
2016                         igmp_v3_cancel_link_timers(igi);
2017                 }
2018         }
2019 }
2020
2021 /*
2022  * Cancel pending IGMPv3 timers for the given link and all groups
2023  * joined on it; state-change, general-query, and group-query timers.
2024  *
2025  * Only ever called on a transition from v3 to Compatibility mode. Kill
2026  * the timers stone dead (this may be expensive for large N groups), they
2027  * will be restarted if Compatibility Mode deems that they must be due to
2028  * query processing.
2029  */
2030 static void
2031 igmp_v3_cancel_link_timers(struct igmp_ifsoftc *igi)
2032 {
2033         struct ifmultiaddr      *ifma;
2034         struct ifnet            *ifp;
2035         struct in_multi         *inm;
2036         struct in_multi_head inm_free_tmp;
2037
2038         CTR3(KTR_IGMPV3, "%s: cancel v3 timers on ifp %p(%s)", __func__,
2039             igi->igi_ifp, igi->igi_ifp->if_xname);
2040
2041         IN_MULTI_LIST_LOCK_ASSERT();
2042         IGMP_LOCK_ASSERT();
2043         NET_EPOCH_ASSERT();
2044
2045         SLIST_INIT(&inm_free_tmp);
2046
2047         /*
2048          * Stop the v3 General Query Response on this link stone dead.
2049          * If fasttimo is woken up due to V_interface_timers_running,
2050          * the flag will be cleared if there are no pending link timers.
2051          */
2052         igi->igi_v3_timer = 0;
2053
2054         /*
2055          * Now clear the current-state and state-change report timers
2056          * for all memberships scoped to this link.
2057          */
2058         ifp = igi->igi_ifp;
2059         IF_ADDR_WLOCK(ifp);
2060         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2061                 inm = inm_ifmultiaddr_get_inm(ifma);
2062                 if (inm == NULL)
2063                         continue;
2064                 switch (inm->inm_state) {
2065                 case IGMP_NOT_MEMBER:
2066                 case IGMP_SILENT_MEMBER:
2067                 case IGMP_IDLE_MEMBER:
2068                 case IGMP_LAZY_MEMBER:
2069                 case IGMP_SLEEPING_MEMBER:
2070                 case IGMP_AWAKENING_MEMBER:
2071                         /*
2072                          * These states are either not relevant in v3 mode,
2073                          * or are unreported. Do nothing.
2074                          */
2075                         break;
2076                 case IGMP_LEAVING_MEMBER:
2077                         /*
2078                          * If we are leaving the group and switching to
2079                          * compatibility mode, we need to release the final
2080                          * reference held for issuing the INCLUDE {}, and
2081                          * transition to REPORTING to ensure the host leave
2082                          * message is sent upstream to the old querier --
2083                          * transition to NOT would lose the leave and race.
2084                          */
2085                         inm_rele_locked(&inm_free_tmp, inm);
2086                         /* FALLTHROUGH */
2087                 case IGMP_G_QUERY_PENDING_MEMBER:
2088                 case IGMP_SG_QUERY_PENDING_MEMBER:
2089                         inm_clear_recorded(inm);
2090                         /* FALLTHROUGH */
2091                 case IGMP_REPORTING_MEMBER:
2092                         inm->inm_state = IGMP_REPORTING_MEMBER;
2093                         break;
2094                 }
2095                 /*
2096                  * Always clear state-change and group report timers.
2097                  * Free any pending IGMPv3 state-change records.
2098                  */
2099                 inm->inm_sctimer = 0;
2100                 inm->inm_timer = 0;
2101                 mbufq_drain(&inm->inm_scq);
2102         }
2103         IF_ADDR_WUNLOCK(ifp);
2104
2105         inm_release_list_deferred(&inm_free_tmp);
2106 }
2107
2108 /*
2109  * Update the Older Version Querier Present timers for a link.
2110  * See Section 7.2.1 of RFC 3376.
2111  */
2112 static void
2113 igmp_v1v2_process_querier_timers(struct igmp_ifsoftc *igi)
2114 {
2115
2116         IGMP_LOCK_ASSERT();
2117
2118         if (igi->igi_v1_timer == 0 && igi->igi_v2_timer == 0) {
2119                 /*
2120                  * IGMPv1 and IGMPv2 Querier Present timers expired.
2121                  *
2122                  * Revert to IGMPv3.
2123                  */
2124                 if (igi->igi_version != IGMP_VERSION_3) {
2125                         CTR5(KTR_IGMPV3,
2126                             "%s: transition from v%d -> v%d on %p(%s)",
2127                             __func__, igi->igi_version, IGMP_VERSION_3,
2128                             igi->igi_ifp, igi->igi_ifp->if_xname);
2129                         igi->igi_version = IGMP_VERSION_3;
2130                 }
2131         } else if (igi->igi_v1_timer == 0 && igi->igi_v2_timer > 0) {
2132                 /*
2133                  * IGMPv1 Querier Present timer expired,
2134                  * IGMPv2 Querier Present timer running.
2135                  * If IGMPv2 was disabled since last timeout,
2136                  * revert to IGMPv3.
2137                  * If IGMPv2 is enabled, revert to IGMPv2.
2138                  */
2139                 if (!V_igmp_v2enable) {
2140                         CTR5(KTR_IGMPV3,
2141                             "%s: transition from v%d -> v%d on %p(%s)",
2142                             __func__, igi->igi_version, IGMP_VERSION_3,
2143                             igi->igi_ifp, igi->igi_ifp->if_xname);
2144                         igi->igi_v2_timer = 0;
2145                         igi->igi_version = IGMP_VERSION_3;
2146                 } else {
2147                         --igi->igi_v2_timer;
2148                         if (igi->igi_version != IGMP_VERSION_2) {
2149                                 CTR5(KTR_IGMPV3,
2150                                     "%s: transition from v%d -> v%d on %p(%s)",
2151                                     __func__, igi->igi_version, IGMP_VERSION_2,
2152                                     igi->igi_ifp, igi->igi_ifp->if_xname);
2153                                 igi->igi_version = IGMP_VERSION_2;
2154                                 igmp_v3_cancel_link_timers(igi);
2155                         }
2156                 }
2157         } else if (igi->igi_v1_timer > 0) {
2158                 /*
2159                  * IGMPv1 Querier Present timer running.
2160                  * Stop IGMPv2 timer if running.
2161                  *
2162                  * If IGMPv1 was disabled since last timeout,
2163                  * revert to IGMPv3.
2164                  * If IGMPv1 is enabled, reset IGMPv2 timer if running.
2165                  */
2166                 if (!V_igmp_v1enable) {
2167                         CTR5(KTR_IGMPV3,
2168                             "%s: transition from v%d -> v%d on %p(%s)",
2169                             __func__, igi->igi_version, IGMP_VERSION_3,
2170                             igi->igi_ifp, igi->igi_ifp->if_xname);
2171                         igi->igi_v1_timer = 0;
2172                         igi->igi_version = IGMP_VERSION_3;
2173                 } else {
2174                         --igi->igi_v1_timer;
2175                 }
2176                 if (igi->igi_v2_timer > 0) {
2177                         CTR3(KTR_IGMPV3,
2178                             "%s: cancel v2 timer on %p(%s)",
2179                             __func__, igi->igi_ifp, igi->igi_ifp->if_xname);
2180                         igi->igi_v2_timer = 0;
2181                 }
2182         }
2183 }
2184
2185 /*
2186  * Global slowtimo handler.
2187  * VIMAGE: Timeout handlers are expected to service all vimages.
2188  */
2189 void
2190 igmp_slowtimo(void)
2191 {
2192         VNET_ITERATOR_DECL(vnet_iter);
2193
2194         VNET_LIST_RLOCK_NOSLEEP();
2195         VNET_FOREACH(vnet_iter) {
2196                 CURVNET_SET(vnet_iter);
2197                 igmp_slowtimo_vnet();
2198                 CURVNET_RESTORE();
2199         }
2200         VNET_LIST_RUNLOCK_NOSLEEP();
2201 }
2202
2203 /*
2204  * Per-vnet slowtimo handler.
2205  */
2206 static void
2207 igmp_slowtimo_vnet(void)
2208 {
2209         struct igmp_ifsoftc *igi;
2210
2211         IGMP_LOCK();
2212
2213         LIST_FOREACH(igi, &V_igi_head, igi_link) {
2214                 igmp_v1v2_process_querier_timers(igi);
2215         }
2216
2217         IGMP_UNLOCK();
2218 }
2219
2220 /*
2221  * Dispatch an IGMPv1/v2 host report or leave message.
2222  * These are always small enough to fit inside a single mbuf.
2223  */
2224 static int
2225 igmp_v1v2_queue_report(struct in_multi *inm, const int type)
2226 {
2227         struct epoch_tracker    et;
2228         struct ifnet            *ifp;
2229         struct igmp             *igmp;
2230         struct ip               *ip;
2231         struct mbuf             *m;
2232
2233         IN_MULTI_LIST_LOCK_ASSERT();
2234         IGMP_LOCK_ASSERT();
2235
2236         ifp = inm->inm_ifp;
2237
2238         m = m_gethdr(M_NOWAIT, MT_DATA);
2239         if (m == NULL)
2240                 return (ENOMEM);
2241         M_ALIGN(m, sizeof(struct ip) + sizeof(struct igmp));
2242
2243         m->m_pkthdr.len = sizeof(struct ip) + sizeof(struct igmp);
2244
2245         m->m_data += sizeof(struct ip);
2246         m->m_len = sizeof(struct igmp);
2247
2248         igmp = mtod(m, struct igmp *);
2249         igmp->igmp_type = type;
2250         igmp->igmp_code = 0;
2251         igmp->igmp_group = inm->inm_addr;
2252         igmp->igmp_cksum = 0;
2253         igmp->igmp_cksum = in_cksum(m, sizeof(struct igmp));
2254
2255         m->m_data -= sizeof(struct ip);
2256         m->m_len += sizeof(struct ip);
2257
2258         ip = mtod(m, struct ip *);
2259         ip->ip_tos = 0;
2260         ip->ip_len = htons(sizeof(struct ip) + sizeof(struct igmp));
2261         ip->ip_off = 0;
2262         ip->ip_p = IPPROTO_IGMP;
2263         ip->ip_src.s_addr = INADDR_ANY;
2264
2265         if (type == IGMP_HOST_LEAVE_MESSAGE)
2266                 ip->ip_dst.s_addr = htonl(INADDR_ALLRTRS_GROUP);
2267         else
2268                 ip->ip_dst = inm->inm_addr;
2269
2270         igmp_save_context(m, ifp);
2271
2272         m->m_flags |= M_IGMPV2;
2273         if (inm->inm_igi->igi_flags & IGIF_LOOPBACK)
2274                 m->m_flags |= M_IGMP_LOOP;
2275
2276         CTR2(KTR_IGMPV3, "%s: netisr_dispatch(NETISR_IGMP, %p)", __func__, m);
2277         NET_EPOCH_ENTER(et);
2278         netisr_dispatch(NETISR_IGMP, m);
2279         NET_EPOCH_EXIT(et);
2280
2281         return (0);
2282 }
2283
2284 /*
2285  * Process a state change from the upper layer for the given IPv4 group.
2286  *
2287  * Each socket holds a reference on the in_multi in its own ip_moptions.
2288  * The socket layer will have made the necessary updates to.the group
2289  * state, it is now up to IGMP to issue a state change report if there
2290  * has been any change between T0 (when the last state-change was issued)
2291  * and T1 (now).
2292  *
2293  * We use the IGMPv3 state machine at group level. The IGMP module
2294  * however makes the decision as to which IGMP protocol version to speak.
2295  * A state change *from* INCLUDE {} always means an initial join.
2296  * A state change *to* INCLUDE {} always means a final leave.
2297  *
2298  * FUTURE: If IGIF_V3LITE is enabled for this interface, then we can
2299  * save ourselves a bunch of work; any exclusive mode groups need not
2300  * compute source filter lists.
2301  *
2302  * VIMAGE: curvnet should have been set by caller, as this routine
2303  * is called from the socket option handlers.
2304  */
2305 int
2306 igmp_change_state(struct in_multi *inm)
2307 {
2308         struct igmp_ifsoftc *igi;
2309         struct ifnet *ifp;
2310         int error;
2311
2312         error = 0;
2313         IN_MULTI_LOCK_ASSERT();
2314         /*
2315          * Try to detect if the upper layer just asked us to change state
2316          * for an interface which has now gone away.
2317          */
2318         KASSERT(inm->inm_ifma != NULL, ("%s: no ifma", __func__));
2319         ifp = inm->inm_ifma->ifma_ifp;
2320         if (ifp == NULL)
2321                 return (0);
2322         /*
2323          * Sanity check that netinet's notion of ifp is the
2324          * same as net's.
2325          */
2326         KASSERT(inm->inm_ifp == ifp, ("%s: bad ifp", __func__));
2327
2328         IGMP_LOCK();
2329
2330         igi = ((struct in_ifinfo *)ifp->if_afdata[AF_INET])->ii_igmp;
2331         KASSERT(igi != NULL, ("%s: no igmp_ifsoftc for ifp %p", __func__, ifp));
2332
2333         /*
2334          * If we detect a state transition to or from MCAST_UNDEFINED
2335          * for this group, then we are starting or finishing an IGMP
2336          * life cycle for this group.
2337          */
2338         if (inm->inm_st[1].iss_fmode != inm->inm_st[0].iss_fmode) {
2339                 CTR3(KTR_IGMPV3, "%s: inm transition %d -> %d", __func__,
2340                     inm->inm_st[0].iss_fmode, inm->inm_st[1].iss_fmode);
2341                 if (inm->inm_st[0].iss_fmode == MCAST_UNDEFINED) {
2342                         CTR1(KTR_IGMPV3, "%s: initial join", __func__);
2343                         error = igmp_initial_join(inm, igi);
2344                         goto out_locked;
2345                 } else if (inm->inm_st[1].iss_fmode == MCAST_UNDEFINED) {
2346                         CTR1(KTR_IGMPV3, "%s: final leave", __func__);
2347                         igmp_final_leave(inm, igi);
2348                         goto out_locked;
2349                 }
2350         } else {
2351                 CTR1(KTR_IGMPV3, "%s: filter set change", __func__);
2352         }
2353
2354         error = igmp_handle_state_change(inm, igi);
2355
2356 out_locked:
2357         IGMP_UNLOCK();
2358         return (error);
2359 }
2360
2361 /*
2362  * Perform the initial join for an IGMP group.
2363  *
2364  * When joining a group:
2365  *  If the group should have its IGMP traffic suppressed, do nothing.
2366  *  IGMPv1 starts sending IGMPv1 host membership reports.
2367  *  IGMPv2 starts sending IGMPv2 host membership reports.
2368  *  IGMPv3 will schedule an IGMPv3 state-change report containing the
2369  *  initial state of the membership.
2370  */
2371 static int
2372 igmp_initial_join(struct in_multi *inm, struct igmp_ifsoftc *igi)
2373 {
2374         struct ifnet            *ifp;
2375         struct mbufq            *mq;
2376         int                      error, retval, syncstates;
2377
2378         CTR4(KTR_IGMPV3, "%s: initial join 0x%08x on ifp %p(%s)", __func__,
2379             ntohl(inm->inm_addr.s_addr), inm->inm_ifp, inm->inm_ifp->if_xname);
2380
2381         error = 0;
2382         syncstates = 1;
2383
2384         ifp = inm->inm_ifp;
2385
2386         IN_MULTI_LOCK_ASSERT();
2387         IGMP_LOCK_ASSERT();
2388
2389         KASSERT(igi && igi->igi_ifp == ifp, ("%s: inconsistent ifp", __func__));
2390
2391         /*
2392          * Groups joined on loopback or marked as 'not reported',
2393          * e.g. 224.0.0.1, enter the IGMP_SILENT_MEMBER state and
2394          * are never reported in any IGMP protocol exchanges.
2395          * All other groups enter the appropriate IGMP state machine
2396          * for the version in use on this link.
2397          * A link marked as IGIF_SILENT causes IGMP to be completely
2398          * disabled for the link.
2399          */
2400         if ((ifp->if_flags & IFF_LOOPBACK) ||
2401             (igi->igi_flags & IGIF_SILENT) ||
2402             !igmp_isgroupreported(inm->inm_addr)) {
2403                 CTR1(KTR_IGMPV3,
2404 "%s: not kicking state machine for silent group", __func__);
2405                 inm->inm_state = IGMP_SILENT_MEMBER;
2406                 inm->inm_timer = 0;
2407         } else {
2408                 /*
2409                  * Deal with overlapping in_multi lifecycle.
2410                  * If this group was LEAVING, then make sure
2411                  * we drop the reference we picked up to keep the
2412                  * group around for the final INCLUDE {} enqueue.
2413                  */
2414                 if (igi->igi_version == IGMP_VERSION_3 &&
2415                     inm->inm_state == IGMP_LEAVING_MEMBER) {
2416                         MPASS(inm->inm_refcount > 1);
2417                         inm_rele_locked(NULL, inm);
2418                 }
2419                 inm->inm_state = IGMP_REPORTING_MEMBER;
2420
2421                 switch (igi->igi_version) {
2422                 case IGMP_VERSION_1:
2423                 case IGMP_VERSION_2:
2424                         inm->inm_state = IGMP_IDLE_MEMBER;
2425                         error = igmp_v1v2_queue_report(inm,
2426                             (igi->igi_version == IGMP_VERSION_2) ?
2427                              IGMP_v2_HOST_MEMBERSHIP_REPORT :
2428                              IGMP_v1_HOST_MEMBERSHIP_REPORT);
2429                         if (error == 0) {
2430                                 inm->inm_timer = IGMP_RANDOM_DELAY(
2431                                     IGMP_V1V2_MAX_RI * PR_FASTHZ);
2432                                 V_current_state_timers_running = 1;
2433                         }
2434                         break;
2435
2436                 case IGMP_VERSION_3:
2437                         /*
2438                          * Defer update of T0 to T1, until the first copy
2439                          * of the state change has been transmitted.
2440                          */
2441                         syncstates = 0;
2442
2443                         /*
2444                          * Immediately enqueue a State-Change Report for
2445                          * this interface, freeing any previous reports.
2446                          * Don't kick the timers if there is nothing to do,
2447                          * or if an error occurred.
2448                          */
2449                         mq = &inm->inm_scq;
2450                         mbufq_drain(mq);
2451                         retval = igmp_v3_enqueue_group_record(mq, inm, 1,
2452                             0, 0);
2453                         CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
2454                             __func__, retval);
2455                         if (retval <= 0) {
2456                                 error = retval * -1;
2457                                 break;
2458                         }
2459
2460                         /*
2461                          * Schedule transmission of pending state-change
2462                          * report up to RV times for this link. The timer
2463                          * will fire at the next igmp_fasttimo (~200ms),
2464                          * giving us an opportunity to merge the reports.
2465                          */
2466                         if (igi->igi_flags & IGIF_LOOPBACK) {
2467                                 inm->inm_scrv = 1;
2468                         } else {
2469                                 KASSERT(igi->igi_rv > 1,
2470                                    ("%s: invalid robustness %d", __func__,
2471                                     igi->igi_rv));
2472                                 inm->inm_scrv = igi->igi_rv;
2473                         }
2474                         inm->inm_sctimer = 1;
2475                         V_state_change_timers_running = 1;
2476
2477                         error = 0;
2478                         break;
2479                 }
2480         }
2481
2482         /*
2483          * Only update the T0 state if state change is atomic,
2484          * i.e. we don't need to wait for a timer to fire before we
2485          * can consider the state change to have been communicated.
2486          */
2487         if (syncstates) {
2488                 inm_commit(inm);
2489                 CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2490                     ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2491         }
2492
2493         return (error);
2494 }
2495
2496 /*
2497  * Issue an intermediate state change during the IGMP life-cycle.
2498  */
2499 static int
2500 igmp_handle_state_change(struct in_multi *inm, struct igmp_ifsoftc *igi)
2501 {
2502         struct ifnet            *ifp;
2503         int                      retval;
2504
2505         CTR4(KTR_IGMPV3, "%s: state change for 0x%08x on ifp %p(%s)", __func__,
2506             ntohl(inm->inm_addr.s_addr), inm->inm_ifp, inm->inm_ifp->if_xname);
2507
2508         ifp = inm->inm_ifp;
2509
2510         IN_MULTI_LIST_LOCK_ASSERT();
2511         IGMP_LOCK_ASSERT();
2512
2513         KASSERT(igi && igi->igi_ifp == ifp, ("%s: inconsistent ifp", __func__));
2514
2515         if ((ifp->if_flags & IFF_LOOPBACK) ||
2516             (igi->igi_flags & IGIF_SILENT) ||
2517             !igmp_isgroupreported(inm->inm_addr) ||
2518             (igi->igi_version != IGMP_VERSION_3)) {
2519                 if (!igmp_isgroupreported(inm->inm_addr)) {
2520                         CTR1(KTR_IGMPV3,
2521 "%s: not kicking state machine for silent group", __func__);
2522                 }
2523                 CTR1(KTR_IGMPV3, "%s: nothing to do", __func__);
2524                 inm_commit(inm);
2525                 CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2526                     ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2527                 return (0);
2528         }
2529
2530         mbufq_drain(&inm->inm_scq);
2531
2532         retval = igmp_v3_enqueue_group_record(&inm->inm_scq, inm, 1, 0, 0);
2533         CTR2(KTR_IGMPV3, "%s: enqueue record = %d", __func__, retval);
2534         if (retval <= 0)
2535                 return (-retval);
2536
2537         /*
2538          * If record(s) were enqueued, start the state-change
2539          * report timer for this group.
2540          */
2541         inm->inm_scrv = ((igi->igi_flags & IGIF_LOOPBACK) ? 1 : igi->igi_rv);
2542         inm->inm_sctimer = 1;
2543         V_state_change_timers_running = 1;
2544
2545         return (0);
2546 }
2547
2548 /*
2549  * Perform the final leave for an IGMP group.
2550  *
2551  * When leaving a group:
2552  *  IGMPv1 does nothing.
2553  *  IGMPv2 sends a host leave message, if and only if we are the reporter.
2554  *  IGMPv3 enqueues a state-change report containing a transition
2555  *  to INCLUDE {} for immediate transmission.
2556  */
2557 static void
2558 igmp_final_leave(struct in_multi *inm, struct igmp_ifsoftc *igi)
2559 {
2560         int syncstates;
2561
2562         syncstates = 1;
2563
2564         CTR4(KTR_IGMPV3, "%s: final leave 0x%08x on ifp %p(%s)",
2565             __func__, ntohl(inm->inm_addr.s_addr), inm->inm_ifp,
2566             inm->inm_ifp->if_xname);
2567
2568         IN_MULTI_LIST_LOCK_ASSERT();
2569         IGMP_LOCK_ASSERT();
2570
2571         switch (inm->inm_state) {
2572         case IGMP_NOT_MEMBER:
2573         case IGMP_SILENT_MEMBER:
2574         case IGMP_LEAVING_MEMBER:
2575                 /* Already leaving or left; do nothing. */
2576                 CTR1(KTR_IGMPV3,
2577 "%s: not kicking state machine for silent group", __func__);
2578                 break;
2579         case IGMP_REPORTING_MEMBER:
2580         case IGMP_IDLE_MEMBER:
2581         case IGMP_G_QUERY_PENDING_MEMBER:
2582         case IGMP_SG_QUERY_PENDING_MEMBER:
2583                 if (igi->igi_version == IGMP_VERSION_2) {
2584 #ifdef INVARIANTS
2585                         if (inm->inm_state == IGMP_G_QUERY_PENDING_MEMBER ||
2586                             inm->inm_state == IGMP_SG_QUERY_PENDING_MEMBER)
2587                         panic("%s: IGMPv3 state reached, not IGMPv3 mode",
2588                              __func__);
2589 #endif
2590                         igmp_v1v2_queue_report(inm, IGMP_HOST_LEAVE_MESSAGE);
2591                         inm->inm_state = IGMP_NOT_MEMBER;
2592                 } else if (igi->igi_version == IGMP_VERSION_3) {
2593                         /*
2594                          * Stop group timer and all pending reports.
2595                          * Immediately enqueue a state-change report
2596                          * TO_IN {} to be sent on the next fast timeout,
2597                          * giving us an opportunity to merge reports.
2598                          */
2599                         mbufq_drain(&inm->inm_scq);
2600                         inm->inm_timer = 0;
2601                         if (igi->igi_flags & IGIF_LOOPBACK) {
2602                                 inm->inm_scrv = 1;
2603                         } else {
2604                                 inm->inm_scrv = igi->igi_rv;
2605                         }
2606                         CTR4(KTR_IGMPV3, "%s: Leaving 0x%08x/%s with %d "
2607                             "pending retransmissions.", __func__,
2608                             ntohl(inm->inm_addr.s_addr),
2609                             inm->inm_ifp->if_xname, inm->inm_scrv);
2610                         if (inm->inm_scrv == 0) {
2611                                 inm->inm_state = IGMP_NOT_MEMBER;
2612                                 inm->inm_sctimer = 0;
2613                         } else {
2614                                 int retval __unused;
2615
2616                                 inm_acquire_locked(inm);
2617
2618                                 retval = igmp_v3_enqueue_group_record(
2619                                     &inm->inm_scq, inm, 1, 0, 0);
2620                                 KASSERT(retval != 0,
2621                                     ("%s: enqueue record = %d", __func__,
2622                                      retval));
2623
2624                                 inm->inm_state = IGMP_LEAVING_MEMBER;
2625                                 inm->inm_sctimer = 1;
2626                                 V_state_change_timers_running = 1;
2627                                 syncstates = 0;
2628                         }
2629                         break;
2630                 }
2631                 break;
2632         case IGMP_LAZY_MEMBER:
2633         case IGMP_SLEEPING_MEMBER:
2634         case IGMP_AWAKENING_MEMBER:
2635                 /* Our reports are suppressed; do nothing. */
2636                 break;
2637         }
2638
2639         if (syncstates) {
2640                 inm_commit(inm);
2641                 CTR3(KTR_IGMPV3, "%s: T1 -> T0 for 0x%08x/%s", __func__,
2642                     ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2643                 inm->inm_st[1].iss_fmode = MCAST_UNDEFINED;
2644                 CTR3(KTR_IGMPV3, "%s: T1 now MCAST_UNDEFINED for 0x%08x/%s",
2645                     __func__, ntohl(inm->inm_addr.s_addr),
2646                     inm->inm_ifp->if_xname);
2647         }
2648 }
2649
2650 /*
2651  * Enqueue an IGMPv3 group record to the given output queue.
2652  *
2653  * XXX This function could do with having the allocation code
2654  * split out, and the multiple-tree-walks coalesced into a single
2655  * routine as has been done in igmp_v3_enqueue_filter_change().
2656  *
2657  * If is_state_change is zero, a current-state record is appended.
2658  * If is_state_change is non-zero, a state-change report is appended.
2659  *
2660  * If is_group_query is non-zero, an mbuf packet chain is allocated.
2661  * If is_group_query is zero, and if there is a packet with free space
2662  * at the tail of the queue, it will be appended to providing there
2663  * is enough free space.
2664  * Otherwise a new mbuf packet chain is allocated.
2665  *
2666  * If is_source_query is non-zero, each source is checked to see if
2667  * it was recorded for a Group-Source query, and will be omitted if
2668  * it is not both in-mode and recorded.
2669  *
2670  * The function will attempt to allocate leading space in the packet
2671  * for the IP/IGMP header to be prepended without fragmenting the chain.
2672  *
2673  * If successful the size of all data appended to the queue is returned,
2674  * otherwise an error code less than zero is returned, or zero if
2675  * no record(s) were appended.
2676  */
2677 static int
2678 igmp_v3_enqueue_group_record(struct mbufq *mq, struct in_multi *inm,
2679     const int is_state_change, const int is_group_query,
2680     const int is_source_query)
2681 {
2682         struct igmp_grouprec     ig;
2683         struct igmp_grouprec    *pig;
2684         struct ifnet            *ifp;
2685         struct ip_msource       *ims, *nims;
2686         struct mbuf             *m0, *m, *md;
2687         int                      is_filter_list_change;
2688         int                      minrec0len, m0srcs, msrcs, nbytes, off;
2689         int                      record_has_sources;
2690         int                      now;
2691         int                      type;
2692         in_addr_t                naddr;
2693         uint8_t                  mode;
2694
2695         IN_MULTI_LIST_LOCK_ASSERT();
2696
2697         ifp = inm->inm_ifp;
2698         is_filter_list_change = 0;
2699         m = NULL;
2700         m0 = NULL;
2701         m0srcs = 0;
2702         msrcs = 0;
2703         nbytes = 0;
2704         nims = NULL;
2705         record_has_sources = 1;
2706         pig = NULL;
2707         type = IGMP_DO_NOTHING;
2708         mode = inm->inm_st[1].iss_fmode;
2709
2710         /*
2711          * If we did not transition out of ASM mode during t0->t1,
2712          * and there are no source nodes to process, we can skip
2713          * the generation of source records.
2714          */
2715         if (inm->inm_st[0].iss_asm > 0 && inm->inm_st[1].iss_asm > 0 &&
2716             inm->inm_nsrc == 0)
2717                 record_has_sources = 0;
2718
2719         if (is_state_change) {
2720                 /*
2721                  * Queue a state change record.
2722                  * If the mode did not change, and there are non-ASM
2723                  * listeners or source filters present,
2724                  * we potentially need to issue two records for the group.
2725                  * If we are transitioning to MCAST_UNDEFINED, we need
2726                  * not send any sources.
2727                  * If there are ASM listeners, and there was no filter
2728                  * mode transition of any kind, do nothing.
2729                  */
2730                 if (mode != inm->inm_st[0].iss_fmode) {
2731                         if (mode == MCAST_EXCLUDE) {
2732                                 CTR1(KTR_IGMPV3, "%s: change to EXCLUDE",
2733                                     __func__);
2734                                 type = IGMP_CHANGE_TO_EXCLUDE_MODE;
2735                         } else {
2736                                 CTR1(KTR_IGMPV3, "%s: change to INCLUDE",
2737                                     __func__);
2738                                 type = IGMP_CHANGE_TO_INCLUDE_MODE;
2739                                 if (mode == MCAST_UNDEFINED)
2740                                         record_has_sources = 0;
2741                         }
2742                 } else {
2743                         if (record_has_sources) {
2744                                 is_filter_list_change = 1;
2745                         } else {
2746                                 type = IGMP_DO_NOTHING;
2747                         }
2748                 }
2749         } else {
2750                 /*
2751                  * Queue a current state record.
2752                  */
2753                 if (mode == MCAST_EXCLUDE) {
2754                         type = IGMP_MODE_IS_EXCLUDE;
2755                 } else if (mode == MCAST_INCLUDE) {
2756                         type = IGMP_MODE_IS_INCLUDE;
2757                         KASSERT(inm->inm_st[1].iss_asm == 0,
2758                             ("%s: inm %p is INCLUDE but ASM count is %d",
2759                              __func__, inm, inm->inm_st[1].iss_asm));
2760                 }
2761         }
2762
2763         /*
2764          * Generate the filter list changes using a separate function.
2765          */
2766         if (is_filter_list_change)
2767                 return (igmp_v3_enqueue_filter_change(mq, inm));
2768
2769         if (type == IGMP_DO_NOTHING) {
2770                 CTR3(KTR_IGMPV3, "%s: nothing to do for 0x%08x/%s", __func__,
2771                     ntohl(inm->inm_addr.s_addr), inm->inm_ifp->if_xname);
2772                 return (0);
2773         }
2774
2775         /*
2776          * If any sources are present, we must be able to fit at least
2777          * one in the trailing space of the tail packet's mbuf,
2778          * ideally more.
2779          */
2780         minrec0len = sizeof(struct igmp_grouprec);
2781         if (record_has_sources)
2782                 minrec0len += sizeof(in_addr_t);
2783
2784         CTR4(KTR_IGMPV3, "%s: queueing %s for 0x%08x/%s", __func__,
2785             igmp_rec_type_to_str(type), ntohl(inm->inm_addr.s_addr),
2786             inm->inm_ifp->if_xname);
2787
2788         /*
2789          * Check if we have a packet in the tail of the queue for this
2790          * group into which the first group record for this group will fit.
2791          * Otherwise allocate a new packet.
2792          * Always allocate leading space for IP+RA_OPT+IGMP+REPORT.
2793          * Note: Group records for G/GSR query responses MUST be sent
2794          * in their own packet.
2795          */
2796         m0 = mbufq_last(mq);
2797         if (!is_group_query &&
2798             m0 != NULL &&
2799             (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <= IGMP_V3_REPORT_MAXRECS) &&
2800             (m0->m_pkthdr.len + minrec0len) <
2801              (ifp->if_mtu - IGMP_LEADINGSPACE)) {
2802                 m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
2803                             sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2804                 m = m0;
2805                 CTR1(KTR_IGMPV3, "%s: use existing packet", __func__);
2806         } else {
2807                 if (mbufq_full(mq)) {
2808                         CTR1(KTR_IGMPV3, "%s: outbound queue full", __func__);
2809                         return (-ENOMEM);
2810                 }
2811                 m = NULL;
2812                 m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
2813                     sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2814                 if (!is_state_change && !is_group_query) {
2815                         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2816                         if (m)
2817                                 m->m_data += IGMP_LEADINGSPACE;
2818                 }
2819                 if (m == NULL) {
2820                         m = m_gethdr(M_NOWAIT, MT_DATA);
2821                         if (m)
2822                                 M_ALIGN(m, IGMP_LEADINGSPACE);
2823                 }
2824                 if (m == NULL)
2825                         return (-ENOMEM);
2826
2827                 igmp_save_context(m, ifp);
2828
2829                 CTR1(KTR_IGMPV3, "%s: allocated first packet", __func__);
2830         }
2831
2832         /*
2833          * Append group record.
2834          * If we have sources, we don't know how many yet.
2835          */
2836         ig.ig_type = type;
2837         ig.ig_datalen = 0;
2838         ig.ig_numsrc = 0;
2839         ig.ig_group = inm->inm_addr;
2840         if (!m_append(m, sizeof(struct igmp_grouprec), (void *)&ig)) {
2841                 if (m != m0)
2842                         m_freem(m);
2843                 CTR1(KTR_IGMPV3, "%s: m_append() failed.", __func__);
2844                 return (-ENOMEM);
2845         }
2846         nbytes += sizeof(struct igmp_grouprec);
2847
2848         /*
2849          * Append as many sources as will fit in the first packet.
2850          * If we are appending to a new packet, the chain allocation
2851          * may potentially use clusters; use m_getptr() in this case.
2852          * If we are appending to an existing packet, we need to obtain
2853          * a pointer to the group record after m_append(), in case a new
2854          * mbuf was allocated.
2855          * Only append sources which are in-mode at t1. If we are
2856          * transitioning to MCAST_UNDEFINED state on the group, do not
2857          * include source entries.
2858          * Only report recorded sources in our filter set when responding
2859          * to a group-source query.
2860          */
2861         if (record_has_sources) {
2862                 if (m == m0) {
2863                         md = m_last(m);
2864                         pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) +
2865                             md->m_len - nbytes);
2866                 } else {
2867                         md = m_getptr(m, 0, &off);
2868                         pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) +
2869                             off);
2870                 }
2871                 msrcs = 0;
2872                 RB_FOREACH_SAFE(ims, ip_msource_tree, &inm->inm_srcs, nims) {
2873                         CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2874                             ims->ims_haddr);
2875                         now = ims_get_mode(inm, ims, 1);
2876                         CTR2(KTR_IGMPV3, "%s: node is %d", __func__, now);
2877                         if ((now != mode) ||
2878                             (now == mode && mode == MCAST_UNDEFINED)) {
2879                                 CTR1(KTR_IGMPV3, "%s: skip node", __func__);
2880                                 continue;
2881                         }
2882                         if (is_source_query && ims->ims_stp == 0) {
2883                                 CTR1(KTR_IGMPV3, "%s: skip unrecorded node",
2884                                     __func__);
2885                                 continue;
2886                         }
2887                         CTR1(KTR_IGMPV3, "%s: append node", __func__);
2888                         naddr = htonl(ims->ims_haddr);
2889                         if (!m_append(m, sizeof(in_addr_t), (void *)&naddr)) {
2890                                 if (m != m0)
2891                                         m_freem(m);
2892                                 CTR1(KTR_IGMPV3, "%s: m_append() failed.",
2893                                     __func__);
2894                                 return (-ENOMEM);
2895                         }
2896                         nbytes += sizeof(in_addr_t);
2897                         ++msrcs;
2898                         if (msrcs == m0srcs)
2899                                 break;
2900                 }
2901                 CTR2(KTR_IGMPV3, "%s: msrcs is %d this packet", __func__,
2902                     msrcs);
2903                 pig->ig_numsrc = htons(msrcs);
2904                 nbytes += (msrcs * sizeof(in_addr_t));
2905         }
2906
2907         if (is_source_query && msrcs == 0) {
2908                 CTR1(KTR_IGMPV3, "%s: no recorded sources to report", __func__);
2909                 if (m != m0)
2910                         m_freem(m);
2911                 return (0);
2912         }
2913
2914         /*
2915          * We are good to go with first packet.
2916          */
2917         if (m != m0) {
2918                 CTR1(KTR_IGMPV3, "%s: enqueueing first packet", __func__);
2919                 m->m_pkthdr.PH_vt.vt_nrecs = 1;
2920                 mbufq_enqueue(mq, m);
2921         } else
2922                 m->m_pkthdr.PH_vt.vt_nrecs++;
2923
2924         /*
2925          * No further work needed if no source list in packet(s).
2926          */
2927         if (!record_has_sources)
2928                 return (nbytes);
2929
2930         /*
2931          * Whilst sources remain to be announced, we need to allocate
2932          * a new packet and fill out as many sources as will fit.
2933          * Always try for a cluster first.
2934          */
2935         while (nims != NULL) {
2936                 if (mbufq_full(mq)) {
2937                         CTR1(KTR_IGMPV3, "%s: outbound queue full", __func__);
2938                         return (-ENOMEM);
2939                 }
2940                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2941                 if (m)
2942                         m->m_data += IGMP_LEADINGSPACE;
2943                 if (m == NULL) {
2944                         m = m_gethdr(M_NOWAIT, MT_DATA);
2945                         if (m)
2946                                 M_ALIGN(m, IGMP_LEADINGSPACE);
2947                 }
2948                 if (m == NULL)
2949                         return (-ENOMEM);
2950                 igmp_save_context(m, ifp);
2951                 md = m_getptr(m, 0, &off);
2952                 pig = (struct igmp_grouprec *)(mtod(md, uint8_t *) + off);
2953                 CTR1(KTR_IGMPV3, "%s: allocated next packet", __func__);
2954
2955                 if (!m_append(m, sizeof(struct igmp_grouprec), (void *)&ig)) {
2956                         if (m != m0)
2957                                 m_freem(m);
2958                         CTR1(KTR_IGMPV3, "%s: m_append() failed.", __func__);
2959                         return (-ENOMEM);
2960                 }
2961                 m->m_pkthdr.PH_vt.vt_nrecs = 1;
2962                 nbytes += sizeof(struct igmp_grouprec);
2963
2964                 m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
2965                     sizeof(struct igmp_grouprec)) / sizeof(in_addr_t);
2966
2967                 msrcs = 0;
2968                 RB_FOREACH_FROM(ims, ip_msource_tree, nims) {
2969                         CTR2(KTR_IGMPV3, "%s: visit node 0x%08x", __func__,
2970                             ims->ims_haddr);
2971                         now = ims_get_mode(inm, ims, 1);
2972                         if ((now != mode) ||
2973                             (now == mode && mode == MCAST_UNDEFINED)) {
2974                                 CTR1(KTR_IGMPV3, "%s: skip node", __func__);
2975                                 continue;
2976                         }
2977                         if (is_source_query && ims->ims_stp == 0) {
2978                                 CTR1(KTR_IGMPV3, "%s: skip unrecorded node",
2979                                     __func__);
2980                                 continue;
2981                         }
2982                         CTR1(KTR_IGMPV3, "%s: append node", __func__);
2983                         naddr = htonl(ims->ims_haddr);
2984                         if (!m_append(m, sizeof(in_addr_t), (void *)&naddr)) {
2985                                 if (m != m0)
2986                                         m_freem(m);
2987                                 CTR1(KTR_IGMPV3, "%s: m_append() failed.",
2988                                     __func__);
2989                                 return (-ENOMEM);
2990                         }
2991                         ++msrcs;
2992                         if (msrcs == m0srcs)
2993                                 break;
2994                 }
2995                 pig->ig_numsrc = htons(msrcs);
2996                 nbytes += (msrcs * sizeof(in_addr_t));
2997
2998                 CTR1(KTR_IGMPV3, "%s: enqueueing next packet", __func__);
2999                 mbufq_enqueue(mq, m);
3000         }
3001
3002         return (nbytes);
3003 }
3004
3005 /*
3006  * Type used to mark record pass completion.
3007  * We exploit the fact we can cast to this easily from the
3008  * current filter modes on each ip_msource node.
3009  */
3010 typedef enum {
3011         REC_NONE = 0x00,        /* MCAST_UNDEFINED */
3012         REC_ALLOW = 0x01,       /* MCAST_INCLUDE */
3013         REC_BLOCK = 0x02,       /* MCAST_EXCLUDE */
3014         REC_FULL = REC_ALLOW | REC_BLOCK
3015 } rectype_t;
3016
3017 /*
3018  * Enqueue an IGMPv3 filter list change to the given output queue.
3019  *
3020  * Source list filter state is held in an RB-tree. When the filter list
3021  * for a group is changed without changing its mode, we need to compute
3022  * the deltas between T0 and T1 for each source in the filter set,
3023  * and enqueue the appropriate ALLOW_NEW/BLOCK_OLD records.
3024  *
3025  * As we may potentially queue two record types, and the entire R-B tree
3026  * needs to be walked at once, we break this out into its own function
3027  * so we can generate a tightly packed queue of packets.
3028  *
3029  * XXX This could be written to only use one tree walk, although that makes
3030  * serializing into the mbuf chains a bit harder. For now we do two walks
3031  * which makes things easier on us, and it may or may not be harder on
3032  * the L2 cache.
3033  *
3034  * If successful the size of all data appended to the queue is returned,
3035  * otherwise an error code less than zero is returned, or zero if
3036  * no record(s) were appended.
3037  */
3038 static int
3039 igmp_v3_enqueue_filter_change(struct mbufq *mq, struct in_multi *inm)
3040 {
3041         static const int MINRECLEN =
3042             sizeof(struct igmp_grouprec) + sizeof(in_addr_t);
3043         struct ifnet            *ifp;
3044         struct igmp_grouprec     ig;
3045         struct igmp_grouprec    *pig;
3046         struct ip_msource       *ims, *nims;
3047         struct mbuf             *m, *m0, *md;
3048         in_addr_t                naddr;
3049         int                      m0srcs, nbytes, npbytes, off, rsrcs, schanged;
3050         int                      nallow, nblock;
3051         uint8_t                  mode, now, then;
3052         rectype_t                crt, drt, nrt;
3053
3054         IN_MULTI_LIST_LOCK_ASSERT();
3055
3056         if (inm->inm_nsrc == 0 ||
3057             (inm->inm_st[0].iss_asm > 0 && inm->inm_st[1].iss_asm > 0))
3058                 return (0);
3059
3060         ifp = inm->inm_ifp;                     /* interface */
3061         mode = inm->inm_st[1].iss_fmode;        /* filter mode at t1 */
3062         crt = REC_NONE; /* current group record type */
3063         drt = REC_NONE; /* mask of completed group record types */
3064         nrt = REC_NONE; /* record type for current node */
3065         m0srcs = 0;     /* # source which will fit in current mbuf chain */
3066         nbytes = 0;     /* # of bytes appended to group's state-change queue */
3067         npbytes = 0;    /* # of bytes appended this packet */
3068         rsrcs = 0;      /* # sources encoded in current record */
3069         schanged = 0;   /* # nodes encoded in overall filter change */
3070         nallow = 0;     /* # of source entries in ALLOW_NEW */
3071         nblock = 0;     /* # of source entries in BLOCK_OLD */
3072         nims = NULL;    /* next tree node pointer */
3073
3074         /*
3075          * For each possible filter record mode.
3076          * The first kind of source we encounter tells us which
3077          * is the first kind of record we start appending.
3078          * If a node transitioned to UNDEFINED at t1, its mode is treated
3079          * as the inverse of the group's filter mode.
3080          */
3081         while (drt != REC_FULL) {
3082                 do {
3083                         m0 = mbufq_last(mq);
3084                         if (m0 != NULL &&
3085                             (m0->m_pkthdr.PH_vt.vt_nrecs + 1 <=
3086                              IGMP_V3_REPORT_MAXRECS) &&
3087                             (m0->m_pkthdr.len + MINRECLEN) <
3088                              (ifp->if_mtu - IGMP_LEADINGSPACE)) {
3089                                 m = m0;
3090                                 m0srcs = (ifp->if_mtu - m0->m_pkthdr.len -
3091                                             sizeof(struct igmp_grouprec)) /
3092                                     sizeof(in_addr_t);
3093                                 CTR1(KTR_IGMPV3,
3094                                     "%s: use previous packet", __func__);
3095                         } else {
3096                                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
3097                                 if (m)
3098                                         m->m_data += IGMP_LEADINGSPACE;
3099                                 if (m == NULL) {
3100                                         m = m_gethdr(M_NOWAIT, MT_DATA);
3101                                         if (m)
3102                                                 M_ALIGN(m, IGMP_LEADINGSPACE);
3103                                 }
3104                                 if (m == NULL) {
3105                                         CTR1(KTR_IGMPV3,
3106                                             "%s: m_get*() failed", __func__);
3107                                         return (-ENOMEM);
3108                                 }
3109                                 m->m_pkthdr.PH_vt.vt_nrecs = 0;
3110                                 igmp_save_context(m, ifp);
3111                                 m0srcs = (ifp->if_mtu - IGMP_LEADINGSPACE -
3112                                     sizeof(struct igmp_grouprec)) /
3113                                     sizeof(in_addr_t);
3114                                 npbytes = 0;
3115                                 CTR1(KTR_IGMPV3,
3116                                     "%s: allocated new packet", __func__);
3117                         }
3118                         /*
3119                          * Append the IGMP group record header to the
3120                          * current packet's data area.
3121                          * Recalculate pointer to free space for next
3122                          * group record, in case m_append() allocated
3123                          * a new mbuf or cluster.
3124                          */
3125                         memset(&ig, 0, sizeof(ig));
3126                         ig.ig_group = inm->inm_addr;
3127                         if (!m_append(m, sizeof(ig), (void *)&ig)) {
3128                                 if (m != m0)
3129                                         m_freem(m);
3130                                 CTR1(KTR_IGMPV3,
3131                                     "%s: m_append() failed", __func__);
3132                                 return (-ENOMEM);
3133                         }
3134                         npbytes += sizeof(struct igmp_grouprec);
3135                         if (m != m0) {
3136                                 /* new packet; offset in c hain */
3137                                 md = m_getptr(m, npbytes -
3138                                     sizeof(struct igmp_grouprec), &off);
3139                                 pig = (struct igmp_grouprec *)(mtod(md,
3140                                     uint8_t *) + off);
3141                         } else {
3142                                 /* current packet; offset from last append */
3143                                 md = m_last(m);
3144                                 pig = (struct igmp_grouprec *)(mtod(md,
3145                                     uint8_t *) + md->m_len -
3146                                     sizeof(struct igmp_grouprec));
3147                         }
3148                         /*
3149                          * Begin walking the tree for this record type
3150                          * pass, or continue from where we left off
3151                          * previously if we had to allocate a new packet.
3152                          * Only report deltas in-mode at t1.
3153                          * We need not report included sources as allowed
3154                          * if we are in inclusive mode on the group,
3155                          * however the converse is not true.
3156                          */
3157                         rsrcs = 0;
3158                         if (nims == NULL)
3159                                 nims = RB_MIN(ip_msource_tree, &inm->inm_srcs);
3160                         RB_FOREACH_FROM(ims, ip_msource_tree, nims) {
3161                                 CTR2(KTR_IGMPV3, "%s: visit node 0x%08x",
3162                                     __func__, ims->ims_haddr);
3163                                 now = ims_get_mode(inm, ims, 1);
3164                                 then = ims_get_mode(inm, ims, 0);
3165                                 CTR3(KTR_IGMPV3, "%s: mode: t0 %d, t1 %d",
3166                                     __func__, then, now);
3167                                 if (now == then) {
3168                                         CTR1(KTR_IGMPV3,
3169                                             "%s: skip unchanged", __func__);
3170                                         continue;
3171                                 }
3172                                 if (mode == MCAST_EXCLUDE &&
3173                                     now == MCAST_INCLUDE) {
3174                                         CTR1(KTR_IGMPV3,
3175                                             "%s: skip IN src on EX group",
3176                                             __func__);
3177                                         continue;
3178                                 }
3179                                 nrt = (rectype_t)now;
3180                                 if (nrt == REC_NONE)
3181                                         nrt = (rectype_t)(~mode & REC_FULL);
3182                                 if (schanged++ == 0) {
3183                                         crt = nrt;
3184                                 } else if (crt != nrt)
3185                                         continue;
3186                                 naddr = htonl(ims->ims_haddr);
3187                                 if (!m_append(m, sizeof(in_addr_t),
3188                                     (void *)&naddr)) {
3189                                         if (m != m0)
3190                                                 m_freem(m);
3191                                         CTR1(KTR_IGMPV3,
3192                                             "%s: m_append() failed", __func__);
3193                                         return (-ENOMEM);
3194                                 }
3195                                 nallow += !!(crt == REC_ALLOW);
3196                                 nblock += !!(crt == REC_BLOCK);
3197                                 if (++rsrcs == m0srcs)
3198                                         break;
3199                         }
3200                         /*
3201                          * If we did not append any tree nodes on this
3202                          * pass, back out of allocations.
3203                          */
3204                         if (rsrcs == 0) {
3205                                 npbytes -= sizeof(struct igmp_grouprec);
3206                                 if (m != m0) {
3207                                         CTR1(KTR_IGMPV3,
3208                                             "%s: m_free(m)", __func__);
3209                                         m_freem(m);
3210                                 } else {
3211                                         CTR1(KTR_IGMPV3,
3212                                             "%s: m_adj(m, -ig)", __func__);
3213                                         m_adj(m, -((int)sizeof(
3214                                             struct igmp_grouprec)));
3215                                 }
3216                                 continue;
3217                         }
3218                         npbytes += (rsrcs * sizeof(in_addr_t));
3219                         if (crt == REC_ALLOW)
3220                                 pig->ig_type = IGMP_ALLOW_NEW_SOURCES;
3221                         else if (crt == REC_BLOCK)
3222                                 pig->ig_type = IGMP_BLOCK_OLD_SOURCES;
3223                         pig->ig_numsrc = htons(rsrcs);
3224                         /*
3225                          * Count the new group record, and enqueue this
3226                          * packet if it wasn't already queued.
3227                          */
3228                         m->m_pkthdr.PH_vt.vt_nrecs++;
3229                         if (m != m0)
3230                                 mbufq_enqueue(mq, m);
3231                         nbytes += npbytes;
3232                 } while (nims != NULL);
3233                 drt |= crt;
3234                 crt = (~crt & REC_FULL);
3235         }
3236
3237         CTR3(KTR_IGMPV3, "%s: queued %d ALLOW_NEW, %d BLOCK_OLD", __func__,
3238             nallow, nblock);
3239
3240         return (nbytes);
3241 }
3242
3243 static int
3244 igmp_v3_merge_state_changes(struct in_multi *inm, struct mbufq *scq)
3245 {
3246         struct mbufq    *gq;
3247         struct mbuf     *m;             /* pending state-change */
3248         struct mbuf     *m0;            /* copy of pending state-change */
3249         struct mbuf     *mt;            /* last state-change in packet */
3250         int              docopy, domerge;
3251         u_int            recslen;
3252
3253         docopy = 0;
3254         domerge = 0;
3255         recslen = 0;
3256
3257         IN_MULTI_LIST_LOCK_ASSERT();
3258         IGMP_LOCK_ASSERT();
3259
3260         /*
3261          * If there are further pending retransmissions, make a writable
3262          * copy of each queued state-change message before merging.
3263          */
3264         if (inm->inm_scrv > 0)
3265                 docopy = 1;
3266
3267         gq = &inm->inm_scq;
3268 #ifdef KTR
3269         if (mbufq_first(gq) == NULL) {
3270                 CTR2(KTR_IGMPV3, "%s: WARNING: queue for inm %p is empty",
3271                     __func__, inm);
3272         }
3273 #endif
3274
3275         m = mbufq_first(gq);
3276         while (m != NULL) {
3277                 /*
3278                  * Only merge the report into the current packet if
3279                  * there is sufficient space to do so; an IGMPv3 report
3280                  * packet may only contain 65,535 group records.
3281                  * Always use a simple mbuf chain concatentation to do this,
3282                  * as large state changes for single groups may have
3283                  * allocated clusters.
3284                  */
3285                 domerge = 0;
3286                 mt = mbufq_last(scq);
3287                 if (mt != NULL) {
3288                         recslen = m_length(m, NULL);
3289
3290                         if ((mt->m_pkthdr.PH_vt.vt_nrecs +
3291                             m->m_pkthdr.PH_vt.vt_nrecs <=
3292                             IGMP_V3_REPORT_MAXRECS) &&
3293                             (mt->m_pkthdr.len + recslen <=
3294                             (inm->inm_ifp->if_mtu - IGMP_LEADINGSPACE)))
3295                                 domerge = 1;
3296                 }
3297
3298                 if (!domerge && mbufq_full(gq)) {
3299                         CTR2(KTR_IGMPV3,
3300                             "%s: outbound queue full, skipping whole packet %p",
3301                             __func__, m);
3302                         mt = m->m_nextpkt;
3303                         if (!docopy)
3304                                 m_freem(m);
3305                         m = mt;
3306                         continue;
3307                 }
3308
3309                 if (!docopy) {
3310                         CTR2(KTR_IGMPV3, "%s: dequeueing %p", __func__, m);
3311                         m0 = mbufq_dequeue(gq);
3312                         m = m0->m_nextpkt;
3313                 } else {
3314                         CTR2(KTR_IGMPV3, "%s: copying %p", __func__, m);
3315                         m0 = m_dup(m, M_NOWAIT);
3316                         if (m0 == NULL)
3317                                 return (ENOMEM);
3318                         m0->m_nextpkt = NULL;
3319                         m = m->m_nextpkt;
3320                 }
3321
3322                 if (!domerge) {
3323                         CTR3(KTR_IGMPV3, "%s: queueing %p to scq %p)",
3324                             __func__, m0, scq);
3325                         mbufq_enqueue(scq, m0);
3326                 } else {
3327                         struct mbuf *mtl;       /* last mbuf of packet mt */
3328
3329                         CTR3(KTR_IGMPV3, "%s: merging %p with scq tail %p)",
3330                             __func__, m0, mt);
3331
3332                         mtl = m_last(mt);
3333                         m0->m_flags &= ~M_PKTHDR;
3334                         mt->m_pkthdr.len += recslen;
3335                         mt->m_pkthdr.PH_vt.vt_nrecs +=
3336                             m0->m_pkthdr.PH_vt.vt_nrecs;
3337
3338                         mtl->m_next = m0;
3339                 }
3340         }
3341
3342         return (0);
3343 }
3344
3345 /*
3346  * Respond to a pending IGMPv3 General Query.
3347  */
3348 static void
3349 igmp_v3_dispatch_general_query(struct igmp_ifsoftc *igi)
3350 {
3351         struct ifmultiaddr      *ifma;
3352         struct ifnet            *ifp;
3353         struct in_multi         *inm;
3354         int                      retval __unused, loop;
3355
3356         IN_MULTI_LIST_LOCK_ASSERT();
3357         IGMP_LOCK_ASSERT();
3358         NET_EPOCH_ASSERT();
3359
3360         KASSERT(igi->igi_version == IGMP_VERSION_3,
3361             ("%s: called when version %d", __func__, igi->igi_version));
3362
3363         /*
3364          * Check that there are some packets queued. If so, send them first.
3365          * For large number of groups the reply to general query can take
3366          * many packets, we should finish sending them before starting of
3367          * queuing the new reply.
3368          */
3369         if (mbufq_len(&igi->igi_gq) != 0)
3370                 goto send;
3371
3372         ifp = igi->igi_ifp;
3373
3374         CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3375                 inm = inm_ifmultiaddr_get_inm(ifma);
3376                 if (inm == NULL)
3377                         continue;
3378                 KASSERT(ifp == inm->inm_ifp,
3379                     ("%s: inconsistent ifp", __func__));
3380
3381                 switch (inm->inm_state) {
3382                 case IGMP_NOT_MEMBER:
3383                 case IGMP_SILENT_MEMBER:
3384                         break;
3385                 case IGMP_REPORTING_MEMBER:
3386                 case IGMP_IDLE_MEMBER:
3387                 case IGMP_LAZY_MEMBER:
3388                 case IGMP_SLEEPING_MEMBER:
3389                 case IGMP_AWAKENING_MEMBER:
3390                         inm->inm_state = IGMP_REPORTING_MEMBER;
3391                         retval = igmp_v3_enqueue_group_record(&igi->igi_gq,
3392                             inm, 0, 0, 0);
3393                         CTR2(KTR_IGMPV3, "%s: enqueue record = %d",
3394                             __func__, retval);
3395                         break;
3396                 case IGMP_G_QUERY_PENDING_MEMBER:
3397                 case IGMP_SG_QUERY_PENDING_MEMBER:
3398                 case IGMP_LEAVING_MEMBER:
3399                         break;
3400                 }
3401         }
3402
3403 send:
3404         loop = (igi->igi_flags & IGIF_LOOPBACK) ? 1 : 0;
3405         igmp_dispatch_queue(&igi->igi_gq, IGMP_MAX_RESPONSE_BURST, loop);
3406
3407         /*
3408          * Slew transmission of bursts over 500ms intervals.
3409          */
3410         if (mbufq_first(&igi->igi_gq) != NULL) {
3411                 igi->igi_v3_timer = 1 + IGMP_RANDOM_DELAY(
3412                     IGMP_RESPONSE_BURST_INTERVAL);
3413                 V_interface_timers_running = 1;
3414         }
3415 }
3416
3417 /*
3418  * Transmit the next pending IGMP message in the output queue.
3419  *
3420  * We get called from netisr_processqueue(). A mutex private to igmpoq
3421  * will be acquired and released around this routine.
3422  *
3423  * VIMAGE: Needs to store/restore vnet pointer on a per-mbuf-chain basis.
3424  * MRT: Nothing needs to be done, as IGMP traffic is always local to
3425  * a link and uses a link-scope multicast address.
3426  */
3427 static void
3428 igmp_intr(struct mbuf *m)
3429 {
3430         struct ip_moptions       imo;
3431         struct ifnet            *ifp;
3432         struct mbuf             *ipopts, *m0;
3433         int                      error;
3434         uint32_t                 ifindex;
3435
3436         CTR2(KTR_IGMPV3, "%s: transmit %p", __func__, m);
3437
3438         /*
3439          * Set VNET image pointer from enqueued mbuf chain
3440          * before doing anything else. Whilst we use interface
3441          * indexes to guard against interface detach, they are
3442          * unique to each VIMAGE and must be retrieved.
3443          */
3444         CURVNET_SET((struct vnet *)(m->m_pkthdr.PH_loc.ptr));
3445         ifindex = igmp_restore_context(m);
3446
3447         /*
3448          * Check if the ifnet still exists. This limits the scope of
3449          * any race in the absence of a global ifp lock for low cost
3450          * (an array lookup).
3451          */
3452         ifp = ifnet_byindex(ifindex);
3453         if (ifp == NULL) {
3454                 CTR3(KTR_IGMPV3, "%s: dropped %p as ifindex %u went away.",
3455                     __func__, m, ifindex);
3456                 m_freem(m);
3457                 IPSTAT_INC(ips_noroute);
3458                 goto out;
3459         }
3460
3461         ipopts = V_igmp_sendra ? m_raopt : NULL;
3462
3463         imo.imo_multicast_ttl  = 1;
3464         imo.imo_multicast_vif  = -1;
3465         imo.imo_multicast_loop = (V_ip_mrouter != NULL);
3466
3467         /*
3468          * If the user requested that IGMP traffic be explicitly
3469          * redirected to the loopback interface (e.g. they are running a
3470          * MANET interface and the routing protocol needs to see the
3471          * updates), handle this now.
3472          */
3473         if (m->m_flags & M_IGMP_LOOP)
3474                 imo.imo_multicast_ifp = V_loif;
3475         else
3476                 imo.imo_multicast_ifp = ifp;
3477
3478         if (m->m_flags & M_IGMPV2) {
3479                 m0 = m;
3480         } else {
3481                 m0 = igmp_v3_encap_report(ifp, m);
3482                 if (m0 == NULL) {
3483                         CTR2(KTR_IGMPV3, "%s: dropped %p", __func__, m);
3484                         m_freem(m);
3485                         IPSTAT_INC(ips_odropped);
3486                         goto out;
3487                 }
3488         }
3489
3490         igmp_scrub_context(m0);
3491         m_clrprotoflags(m);
3492         m0->m_pkthdr.rcvif = V_loif;
3493 #ifdef MAC
3494         mac_netinet_igmp_send(ifp, m0);
3495 #endif
3496         error = ip_output(m0, ipopts, NULL, 0, &imo, NULL);
3497         if (error) {
3498                 CTR3(KTR_IGMPV3, "%s: ip_output(%p) = %d", __func__, m0, error);
3499                 goto out;
3500         }
3501
3502         IGMPSTAT_INC(igps_snd_reports);
3503
3504 out:
3505         /*
3506          * We must restore the existing vnet pointer before
3507          * continuing as we are run from netisr context.
3508          */
3509         CURVNET_RESTORE();
3510 }
3511
3512 /*
3513  * Encapsulate an IGMPv3 report.
3514  *
3515  * The internal mbuf flag M_IGMPV3_HDR is used to indicate that the mbuf
3516  * chain has already had its IP/IGMPv3 header prepended. In this case
3517  * the function will not attempt to prepend; the lengths and checksums
3518  * will however be re-computed.
3519  *
3520  * Returns a pointer to the new mbuf chain head, or NULL if the
3521  * allocation failed.
3522  */
3523 static struct mbuf *
3524 igmp_v3_encap_report(struct ifnet *ifp, struct mbuf *m)
3525 {
3526         struct rm_priotracker   in_ifa_tracker;
3527         struct igmp_report      *igmp;
3528         struct ip               *ip;
3529         int                      hdrlen, igmpreclen;
3530
3531         KASSERT((m->m_flags & M_PKTHDR),
3532             ("%s: mbuf chain %p is !M_PKTHDR", __func__, m));
3533
3534         igmpreclen = m_length(m, NULL);
3535         hdrlen = sizeof(struct ip) + sizeof(struct igmp_report);
3536
3537         if (m->m_flags & M_IGMPV3_HDR) {
3538                 igmpreclen -= hdrlen;
3539         } else {
3540                 M_PREPEND(m, hdrlen, M_NOWAIT);
3541                 if (m == NULL)
3542                         return (NULL);
3543                 m->m_flags |= M_IGMPV3_HDR;
3544         }
3545
3546         CTR2(KTR_IGMPV3, "%s: igmpreclen is %d", __func__, igmpreclen);
3547
3548         m->m_data += sizeof(struct ip);
3549         m->m_len -= sizeof(struct ip);
3550
3551         igmp = mtod(m, struct igmp_report *);
3552         igmp->ir_type = IGMP_v3_HOST_MEMBERSHIP_REPORT;
3553         igmp->ir_rsv1 = 0;
3554         igmp->ir_rsv2 = 0;
3555         igmp->ir_numgrps = htons(m->m_pkthdr.PH_vt.vt_nrecs);
3556         igmp->ir_cksum = 0;
3557         igmp->ir_cksum = in_cksum(m, sizeof(struct igmp_report) + igmpreclen);
3558         m->m_pkthdr.PH_vt.vt_nrecs = 0;
3559
3560         m->m_data -= sizeof(struct ip);
3561         m->m_len += sizeof(struct ip);
3562
3563         ip = mtod(m, struct ip *);
3564         ip->ip_tos = IPTOS_PREC_INTERNETCONTROL;
3565         ip->ip_len = htons(hdrlen + igmpreclen);
3566         ip->ip_off = htons(IP_DF);
3567         ip->ip_p = IPPROTO_IGMP;
3568         ip->ip_sum = 0;
3569
3570         ip->ip_src.s_addr = INADDR_ANY;
3571
3572         if (m->m_flags & M_IGMP_LOOP) {
3573                 struct in_ifaddr *ia;
3574
3575                 IFP_TO_IA(ifp, ia, &in_ifa_tracker);
3576                 if (ia != NULL)
3577                         ip->ip_src = ia->ia_addr.sin_addr;
3578         }
3579
3580         ip->ip_dst.s_addr = htonl(INADDR_ALLRPTS_GROUP);
3581
3582         return (m);
3583 }
3584
3585 #ifdef KTR
3586 static char *
3587 igmp_rec_type_to_str(const int type)
3588 {
3589
3590         switch (type) {
3591                 case IGMP_CHANGE_TO_EXCLUDE_MODE:
3592                         return "TO_EX";
3593                         break;
3594                 case IGMP_CHANGE_TO_INCLUDE_MODE:
3595                         return "TO_IN";
3596                         break;
3597                 case IGMP_MODE_IS_EXCLUDE:
3598                         return "MODE_EX";
3599                         break;
3600                 case IGMP_MODE_IS_INCLUDE:
3601                         return "MODE_IN";
3602                         break;
3603                 case IGMP_ALLOW_NEW_SOURCES:
3604                         return "ALLOW_NEW";
3605                         break;
3606                 case IGMP_BLOCK_OLD_SOURCES:
3607                         return "BLOCK_OLD";
3608                         break;
3609                 default:
3610                         break;
3611         }
3612         return "unknown";
3613 }
3614 #endif
3615
3616 #ifdef VIMAGE
3617 static void
3618 vnet_igmp_init(const void *unused __unused)
3619 {
3620
3621         netisr_register_vnet(&igmp_nh);
3622 }
3623 VNET_SYSINIT(vnet_igmp_init, SI_SUB_PROTO_MC, SI_ORDER_ANY,
3624     vnet_igmp_init, NULL);
3625
3626 static void
3627 vnet_igmp_uninit(const void *unused __unused)
3628 {
3629
3630         /* This can happen when we shutdown the entire network stack. */
3631         CTR1(KTR_IGMPV3, "%s: tearing down", __func__);
3632
3633         netisr_unregister_vnet(&igmp_nh);
3634 }
3635 VNET_SYSUNINIT(vnet_igmp_uninit, SI_SUB_PROTO_MC, SI_ORDER_ANY,
3636     vnet_igmp_uninit, NULL);
3637 #endif
3638
3639 #ifdef DDB
3640 DB_SHOW_COMMAND(igi_list, db_show_igi_list)
3641 {
3642         struct igmp_ifsoftc *igi, *tigi;
3643         LIST_HEAD(_igi_list, igmp_ifsoftc) *igi_head;
3644
3645         if (!have_addr) {
3646                 db_printf("usage: show igi_list <addr>\n");
3647                 return;
3648         }
3649         igi_head = (struct _igi_list *)addr;
3650
3651         LIST_FOREACH_SAFE(igi, igi_head, igi_link, tigi) {
3652                 db_printf("igmp_ifsoftc %p:\n", igi);
3653                 db_printf("    ifp %p\n", igi->igi_ifp);
3654                 db_printf("    version %u\n", igi->igi_version);
3655                 db_printf("    v1_timer %u\n", igi->igi_v1_timer);
3656                 db_printf("    v2_timer %u\n", igi->igi_v2_timer);
3657                 db_printf("    v3_timer %u\n", igi->igi_v3_timer);
3658                 db_printf("    flags %#x\n", igi->igi_flags);
3659                 db_printf("    rv %u\n", igi->igi_rv);
3660                 db_printf("    qi %u\n", igi->igi_qi);
3661                 db_printf("    qri %u\n", igi->igi_qri);
3662                 db_printf("    uri %u\n", igi->igi_uri);
3663                 /* struct mbufq    igi_gq; */
3664                 db_printf("\n");
3665         }
3666 }
3667 #endif
3668
3669 static int
3670 igmp_modevent(module_t mod, int type, void *unused __unused)
3671 {
3672
3673         switch (type) {
3674         case MOD_LOAD:
3675                 CTR1(KTR_IGMPV3, "%s: initializing", __func__);
3676                 IGMP_LOCK_INIT();
3677                 m_raopt = igmp_ra_alloc();
3678                 netisr_register(&igmp_nh);
3679                 break;
3680         case MOD_UNLOAD:
3681                 CTR1(KTR_IGMPV3, "%s: tearing down", __func__);
3682                 netisr_unregister(&igmp_nh);
3683                 m_free(m_raopt);
3684                 m_raopt = NULL;
3685                 IGMP_LOCK_DESTROY();
3686                 break;
3687         default:
3688                 return (EOPNOTSUPP);
3689         }
3690         return (0);
3691 }
3692
3693 static moduledata_t igmp_mod = {
3694     "igmp",
3695     igmp_modevent,
3696     0
3697 };
3698 DECLARE_MODULE(igmp, igmp_mod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);