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