1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1989 Stephen Deering
5 * Copyright (c) 1992, 1993
6 * The Regents of the University of California. All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * Stephen Deering of Stanford University.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 *
35 * @(#)ip_mroute.c 8.2 (Berkeley) 11/15/93
36 */
37
38 /*
39 * IP multicast forwarding procedures
40 *
41 * Written by David Waitzman, BBN Labs, August 1988.
42 * Modified by Steve Deering, Stanford, February 1989.
43 * Modified by Mark J. Steiglitz, Stanford, May, 1991
44 * Modified by Van Jacobson, LBL, January 1993
45 * Modified by Ajit Thyagarajan, PARC, August 1993
46 * Modified by Bill Fenner, PARC, April 1995
47 * Modified by Ahmed Helmy, SGI, June 1996
48 * Modified by George Edmond Eddy (Rusty), ISI, February 1998
49 * Modified by Pavlin Radoslavov, USC/ISI, May 1998, August 1999, October 2000
50 * Modified by Hitoshi Asaeda, WIDE, August 2000
51 * Modified by Pavlin Radoslavov, ICSI, October 2002
52 * Modified by Wojciech Macek, Semihalf, May 2021
53 *
54 * MROUTING Revision: 3.5
55 * and PIM-SMv2 and PIM-DM support, advanced API support,
56 * bandwidth metering and signaling
57 */
58
59 /*
60 * TODO: Prefix functions with ipmf_.
61 * TODO: Maintain a refcount on if_allmulti() in ifnet or in the protocol
62 * domain attachment (if_afdata) so we can track consumers of that service.
63 * TODO: Deprecate routing socket path for SIOCGETSGCNT and SIOCGETVIFCNT,
64 * move it to socket options.
65 * TODO: Cleanup LSRR removal further.
66 * TODO: Push RSVP stubs into raw_ip.c.
67 * TODO: Use bitstring.h for vif set.
68 * TODO: Fix mrt6_ioctl dangling ref when dynamically loaded.
69 * TODO: Sync ip6_mroute.c with this file.
70 */
71
72 #include <sys/cdefs.h>
73 __FBSDID("$FreeBSD$");
74
75 #include "opt_inet.h"
76 #include "opt_mrouting.h"
77
78 #define _PIM_VT 1
79
80 #include <sys/types.h>
81 #include <sys/param.h>
82 #include <sys/kernel.h>
83 #include <sys/stddef.h>
84 #include <sys/condvar.h>
85 #include <sys/eventhandler.h>
86 #include <sys/lock.h>
87 #include <sys/kthread.h>
88 #include <sys/ktr.h>
89 #include <sys/malloc.h>
90 #include <sys/mbuf.h>
91 #include <sys/module.h>
92 #include <sys/priv.h>
93 #include <sys/protosw.h>
94 #include <sys/signalvar.h>
95 #include <sys/socket.h>
96 #include <sys/socketvar.h>
97 #include <sys/sockio.h>
98 #include <sys/sx.h>
99 #include <sys/sysctl.h>
100 #include <sys/syslog.h>
101 #include <sys/systm.h>
102 #include <sys/taskqueue.h>
103 #include <sys/time.h>
104 #include <sys/counter.h>
105 #include <machine/atomic.h>
106
107 #include <net/if.h>
108 #include <net/if_var.h>
109 #include <net/if_types.h>
110 #include <net/netisr.h>
111 #include <net/route.h>
112 #include <net/vnet.h>
113
114 #include <netinet/in.h>
115 #include <netinet/igmp.h>
116 #include <netinet/in_systm.h>
117 #include <netinet/in_var.h>
118 #include <netinet/ip.h>
119 #include <netinet/ip_encap.h>
120 #include <netinet/ip_mroute.h>
121 #include <netinet/ip_var.h>
122 #include <netinet/ip_options.h>
123 #include <netinet/pim.h>
124 #include <netinet/pim_var.h>
125 #include <netinet/udp.h>
126
127 #include <machine/in_cksum.h>
128
129 #ifndef KTR_IPMF
130 #define KTR_IPMF KTR_INET
131 #endif
132
133 #define VIFI_INVALID ((vifi_t) -1)
134
135 static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast forwarding cache");
136
137 /*
138 * Locking. We use two locks: one for the virtual interface table and
139 * one for the forwarding table. These locks may be nested in which case
140 * the VIF lock must always be taken first. Note that each lock is used
141 * to cover not only the specific data structure but also related data
142 * structures.
143 */
144
145 static struct rwlock mrouter_mtx;
146 #define MRW_RLOCK() rw_rlock(&mrouter_mtx)
147 #define MRW_WLOCK() rw_wlock(&mrouter_mtx)
148 #define MRW_RUNLOCK() rw_runlock(&mrouter_mtx)
149 #define MRW_WUNLOCK() rw_wunlock(&mrouter_mtx)
150 #define MRW_UNLOCK() rw_unlock(&mrouter_mtx)
151 #define MRW_LOCK_ASSERT() rw_assert(&mrouter_mtx, RA_LOCKED)
152 #define MRW_WLOCK_ASSERT() rw_assert(&mrouter_mtx, RA_WLOCKED)
153 #define MRW_LOCK_TRY_UPGRADE() rw_try_upgrade(&mrouter_mtx)
154 #define MRW_WOWNED() rw_wowned(&mrouter_mtx)
155 #define MRW_LOCK_INIT() \
156 rw_init(&mrouter_mtx, "IPv4 multicast forwarding")
157 #define MRW_LOCK_DESTROY() rw_destroy(&mrouter_mtx)
158
159 static int ip_mrouter_cnt; /* # of vnets with active mrouters */
160 static int ip_mrouter_unloading; /* Allow no more V_ip_mrouter sockets */
161
162 VNET_PCPUSTAT_DEFINE_STATIC(struct mrtstat, mrtstat);
163 VNET_PCPUSTAT_SYSINIT(mrtstat);
164 VNET_PCPUSTAT_SYSUNINIT(mrtstat);
165 SYSCTL_VNET_PCPUSTAT(_net_inet_ip, OID_AUTO, mrtstat, struct mrtstat,
166 mrtstat, "IPv4 Multicast Forwarding Statistics (struct mrtstat, "
167 "netinet/ip_mroute.h)");
168
169 VNET_DEFINE_STATIC(u_long, mfchash);
170 #define V_mfchash VNET(mfchash)
171 #define MFCHASH(a, g) \
172 ((((a).s_addr >> 20) ^ ((a).s_addr >> 10) ^ (a).s_addr ^ \
173 ((g).s_addr >> 20) ^ ((g).s_addr >> 10) ^ (g).s_addr) & V_mfchash)
174 #define MFCHASHSIZE 256
175
176 static u_long mfchashsize; /* Hash size */
177 VNET_DEFINE_STATIC(u_char *, nexpire); /* 0..mfchashsize-1 */
178 #define V_nexpire VNET(nexpire)
179 VNET_DEFINE_STATIC(LIST_HEAD(mfchashhdr, mfc)*, mfchashtbl);
180 #define V_mfchashtbl VNET(mfchashtbl)
181 VNET_DEFINE_STATIC(struct taskqueue *, task_queue);
182 #define V_task_queue VNET(task_queue)
183 VNET_DEFINE_STATIC(struct task, task);
184 #define V_task VNET(task)
185
186 VNET_DEFINE_STATIC(vifi_t, numvifs);
187 #define V_numvifs VNET(numvifs)
188 VNET_DEFINE_STATIC(struct vif *, viftable);
189 #define V_viftable VNET(viftable)
190
191 static eventhandler_tag if_detach_event_tag = NULL;
192
193 VNET_DEFINE_STATIC(struct callout, expire_upcalls_ch);
194 #define V_expire_upcalls_ch VNET(expire_upcalls_ch)
195
196 VNET_DEFINE_STATIC(struct mtx, buf_ring_mtx);
197 #define V_buf_ring_mtx VNET(buf_ring_mtx)
198
199 #define EXPIRE_TIMEOUT (hz / 4) /* 4x / second */
200 #define UPCALL_EXPIRE 6 /* number of timeouts */
201
202 /*
203 * Bandwidth meter variables and constants
204 */
205 static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
206
207 /*
208 * Pending upcalls are stored in a ring which is flushed when
209 * full, or periodically
210 */
211 VNET_DEFINE_STATIC(struct callout, bw_upcalls_ch);
212 #define V_bw_upcalls_ch VNET(bw_upcalls_ch)
213 VNET_DEFINE_STATIC(struct buf_ring *, bw_upcalls_ring);
214 #define V_bw_upcalls_ring VNET(bw_upcalls_ring)
215 VNET_DEFINE_STATIC(struct mtx, bw_upcalls_ring_mtx);
216 #define V_bw_upcalls_ring_mtx VNET(bw_upcalls_ring_mtx)
217
218 #define BW_UPCALLS_PERIOD (hz) /* periodical flush of bw upcalls */
219
220 VNET_PCPUSTAT_DEFINE_STATIC(struct pimstat, pimstat);
221 VNET_PCPUSTAT_SYSINIT(pimstat);
222 VNET_PCPUSTAT_SYSUNINIT(pimstat);
223
224 SYSCTL_NODE(_net_inet, IPPROTO_PIM, pim, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
225 "PIM");
226 SYSCTL_VNET_PCPUSTAT(_net_inet_pim, PIMCTL_STATS, stats, struct pimstat,
227 pimstat, "PIM Statistics (struct pimstat, netinet/pim_var.h)");
228
229 static u_long pim_squelch_wholepkt = 0;
230 SYSCTL_ULONG(_net_inet_pim, OID_AUTO, squelch_wholepkt, CTLFLAG_RW,
231 &pim_squelch_wholepkt, 0,
232 "Disable IGMP_WHOLEPKT notifications if rendezvous point is unspecified");
233
234 static const struct encaptab *pim_encap_cookie;
235 static int pim_encapcheck(const struct mbuf *, int, int, void *);
236 static int pim_input(struct mbuf *, int, int, void *);
237
238 extern int in_mcast_loop;
239
240 static const struct encap_config ipv4_encap_cfg = {
241 .proto = IPPROTO_PIM,
242 .min_length = sizeof(struct ip) + PIM_MINLEN,
243 .exact_match = 8,
244 .check = pim_encapcheck,
245 .input = pim_input
246 };
247
248 /*
249 * Note: the PIM Register encapsulation adds the following in front of a
250 * data packet:
251 *
252 * struct pim_encap_hdr {
253 * struct ip ip;
254 * struct pim_encap_pimhdr pim;
255 * }
256 *
257 */
258
259 struct pim_encap_pimhdr {
260 struct pim pim;
261 uint32_t flags;
262 };
263 #define PIM_ENCAP_TTL 64
264
265 static struct ip pim_encap_iphdr = {
266 #if BYTE_ORDER == LITTLE_ENDIAN
267 sizeof(struct ip) >> 2,
268 IPVERSION,
269 #else
270 IPVERSION,
271 sizeof(struct ip) >> 2,
272 #endif
273 0, /* tos */
274 sizeof(struct ip), /* total length */
275 0, /* id */
276 0, /* frag offset */
277 PIM_ENCAP_TTL,
278 IPPROTO_PIM,
279 0, /* checksum */
280 };
281
282 static struct pim_encap_pimhdr pim_encap_pimhdr = {
283 {
284 PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
285 0, /* reserved */
286 0, /* checksum */
287 },
288 0 /* flags */
289 };
290
291 VNET_DEFINE_STATIC(vifi_t, reg_vif_num) = VIFI_INVALID;
292 #define V_reg_vif_num VNET(reg_vif_num)
293 VNET_DEFINE_STATIC(struct ifnet *, multicast_register_if);
294 #define V_multicast_register_if VNET(multicast_register_if)
295
296 /*
297 * Private variables.
298 */
299
300 static u_long X_ip_mcast_src(int);
301 static int X_ip_mforward(struct ip *, struct ifnet *, struct mbuf *,
302 struct ip_moptions *);
303 static int X_ip_mrouter_done(void);
304 static int X_ip_mrouter_get(struct socket *, struct sockopt *);
305 static int X_ip_mrouter_set(struct socket *, struct sockopt *);
306 static int X_legal_vif_num(int);
307 static int X_mrt_ioctl(u_long, caddr_t, int);
308
309 static int add_bw_upcall(struct bw_upcall *);
310 static int add_mfc(struct mfcctl2 *);
311 static int add_vif(struct vifctl *);
312 static void bw_meter_prepare_upcall(struct bw_meter *, struct timeval *);
313 static void bw_meter_geq_receive_packet(struct bw_meter *, int,
314 struct timeval *);
315 static void bw_upcalls_send(void);
316 static int del_bw_upcall(struct bw_upcall *);
317 static int del_mfc(struct mfcctl2 *);
318 static int del_vif(vifi_t);
319 static int del_vif_locked(vifi_t, struct ifnet **);
320 static void expire_bw_upcalls_send(void *);
321 static void expire_mfc(struct mfc *);
322 static void expire_upcalls(void *);
323 static void free_bw_list(struct bw_meter *);
324 static int get_sg_cnt(struct sioc_sg_req *);
325 static int get_vif_cnt(struct sioc_vif_req *);
326 static void if_detached_event(void *, struct ifnet *);
327 static int ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
328 static int ip_mrouter_init(struct socket *, int);
329 static __inline struct mfc *
330 mfc_find(struct in_addr *, struct in_addr *);
331 static void phyint_send(struct ip *, struct vif *, struct mbuf *);
332 static struct mbuf *
333 pim_register_prepare(struct ip *, struct mbuf *);
334 static int pim_register_send(struct ip *, struct vif *,
335 struct mbuf *, struct mfc *);
336 static int pim_register_send_rp(struct ip *, struct vif *,
337 struct mbuf *, struct mfc *);
338 static int pim_register_send_upcall(struct ip *, struct vif *,
339 struct mbuf *, struct mfc *);
340 static void send_packet(struct vif *, struct mbuf *);
341 static int set_api_config(uint32_t *);
342 static int set_assert(int);
343 static int socket_send(struct socket *, struct mbuf *,
344 struct sockaddr_in *);
345
346 /*
347 * Kernel multicast forwarding API capabilities and setup.
348 * If more API capabilities are added to the kernel, they should be
349 * recorded in `mrt_api_support'.
350 */
351 #define MRT_API_VERSION 0x0305
352
353 static const int mrt_api_version = MRT_API_VERSION;
354 static const uint32_t mrt_api_support = (MRT_MFC_FLAGS_DISABLE_WRONGVIF |
355 MRT_MFC_FLAGS_BORDER_VIF |
356 MRT_MFC_RP |
357 MRT_MFC_BW_UPCALL);
358 VNET_DEFINE_STATIC(uint32_t, mrt_api_config);
359 #define V_mrt_api_config VNET(mrt_api_config)
360 VNET_DEFINE_STATIC(int, pim_assert_enabled);
361 #define V_pim_assert_enabled VNET(pim_assert_enabled)
362 static struct timeval pim_assert_interval = { 3, 0 }; /* Rate limit */
363
364 /*
365 * Find a route for a given origin IP address and multicast group address.
366 * Statistics must be updated by the caller.
367 */
368 static __inline struct mfc *
369 mfc_find(struct in_addr *o, struct in_addr *g)
370 {
371 struct mfc *rt;
372
373 /*
374 * Might be called both RLOCK and WLOCK.
375 * Check if any, it's caller responsibility
376 * to choose correct option.
377 */
378 MRW_LOCK_ASSERT();
379
380 LIST_FOREACH(rt, &V_mfchashtbl[MFCHASH(*o, *g)], mfc_hash) {
381 if (in_hosteq(rt->mfc_origin, *o) &&
382 in_hosteq(rt->mfc_mcastgrp, *g) &&
383 buf_ring_empty(rt->mfc_stall_ring))
384 break;
385 }
386
387 return (rt);
388 }
389
390 static __inline struct mfc *
391 mfc_alloc(void)
392 {
393 struct mfc *rt;
394 rt = (struct mfc*) malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT | M_ZERO);
395 if (rt == NULL)
396 return rt;
397
398 rt->mfc_stall_ring = buf_ring_alloc(MAX_UPQ, M_MRTABLE,
399 M_NOWAIT, &V_buf_ring_mtx);
400 if (rt->mfc_stall_ring == NULL) {
401 free(rt, M_MRTABLE);
402 return NULL;
403 }
404
405 return rt;
406 }
407
408 /*
409 * Handle MRT setsockopt commands to modify the multicast forwarding tables.
410 */
411 static int
412 X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
413 {
414 int error, optval;
415 vifi_t vifi;
416 struct vifctl vifc;
417 struct mfcctl2 mfc;
418 struct bw_upcall bw_upcall;
419 uint32_t i;
420
421 if (so != V_ip_mrouter && sopt->sopt_name != MRT_INIT)
422 return EPERM;
423
424 error = 0;
425 switch (sopt->sopt_name) {
426 case MRT_INIT:
427 error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
428 if (error)
429 break;
430 error = ip_mrouter_init(so, optval);
431 break;
432
433 case MRT_DONE:
434 error = ip_mrouter_done();
435 break;
436
437 case MRT_ADD_VIF:
438 error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
439 if (error)
440 break;
441 error = add_vif(&vifc);
442 break;
443
444 case MRT_DEL_VIF:
445 error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
446 if (error)
447 break;
448 error = del_vif(vifi);
449 break;
450
451 case MRT_ADD_MFC:
452 case MRT_DEL_MFC:
453 /*
454 * select data size depending on API version.
455 */
456 if (sopt->sopt_name == MRT_ADD_MFC &&
457 V_mrt_api_config & MRT_API_FLAGS_ALL) {
458 error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl2),
459 sizeof(struct mfcctl2));
460 } else {
461 error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl),
462 sizeof(struct mfcctl));
463 bzero((caddr_t)&mfc + sizeof(struct mfcctl),
464 sizeof(mfc) - sizeof(struct mfcctl));
465 }
466 if (error)
467 break;
468 if (sopt->sopt_name == MRT_ADD_MFC)
469 error = add_mfc(&mfc);
470 else
471 error = del_mfc(&mfc);
472 break;
473
474 case MRT_ASSERT:
475 error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
476 if (error)
477 break;
478 set_assert(optval);
479 break;
480
481 case MRT_API_CONFIG:
482 error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
483 if (!error)
484 error = set_api_config(&i);
485 if (!error)
486 error = sooptcopyout(sopt, &i, sizeof i);
487 break;
488
489 case MRT_ADD_BW_UPCALL:
490 case MRT_DEL_BW_UPCALL:
491 error = sooptcopyin(sopt, &bw_upcall, sizeof bw_upcall,
492 sizeof bw_upcall);
493 if (error)
494 break;
495 if (sopt->sopt_name == MRT_ADD_BW_UPCALL)
496 error = add_bw_upcall(&bw_upcall);
497 else
498 error = del_bw_upcall(&bw_upcall);
499 break;
500
501 default:
502 error = EOPNOTSUPP;
503 break;
504 }
505 return error;
506 }
507
508 /*
509 * Handle MRT getsockopt commands
510 */
511 static int
512 X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
513 {
514 int error;
515
516 switch (sopt->sopt_name) {
517 case MRT_VERSION:
518 error = sooptcopyout(sopt, &mrt_api_version, sizeof mrt_api_version);
519 break;
520
521 case MRT_ASSERT:
522 error = sooptcopyout(sopt, &V_pim_assert_enabled,
523 sizeof V_pim_assert_enabled);
524 break;
525
526 case MRT_API_SUPPORT:
527 error = sooptcopyout(sopt, &mrt_api_support, sizeof mrt_api_support);
528 break;
529
530 case MRT_API_CONFIG:
531 error = sooptcopyout(sopt, &V_mrt_api_config, sizeof V_mrt_api_config);
532 break;
533
534 default:
535 error = EOPNOTSUPP;
536 break;
537 }
538 return error;
539 }
540
541 /*
542 * Handle ioctl commands to obtain information from the cache
543 */
544 static int
545 X_mrt_ioctl(u_long cmd, caddr_t data, int fibnum __unused)
546 {
547 int error = 0;
548
549 /*
550 * Currently the only function calling this ioctl routine is rtioctl_fib().
551 * Typically, only root can create the raw socket in order to execute
552 * this ioctl method, however the request might be coming from a prison
553 */
554 error = priv_check(curthread, PRIV_NETINET_MROUTE);
555 if (error)
556 return (error);
557 switch (cmd) {
558 case (SIOCGETVIFCNT):
559 error = get_vif_cnt((struct sioc_vif_req *)data);
560 break;
561
562 case (SIOCGETSGCNT):
563 error = get_sg_cnt((struct sioc_sg_req *)data);
564 break;
565
566 default:
567 error = EINVAL;
568 break;
569 }
570 return error;
571 }
572
573 /*
574 * returns the packet, byte, rpf-failure count for the source group provided
575 */
576 static int
577 get_sg_cnt(struct sioc_sg_req *req)
578 {
579 struct mfc *rt;
580
581 MRW_RLOCK();
582 rt = mfc_find(&req->src, &req->grp);
583 if (rt == NULL) {
584 MRW_RUNLOCK();
585 req->pktcnt = req->bytecnt = req->wrong_if = 0xffffffff;
586 return EADDRNOTAVAIL;
587 }
588 req->pktcnt = rt->mfc_pkt_cnt;
589 req->bytecnt = rt->mfc_byte_cnt;
590 req->wrong_if = rt->mfc_wrong_if;
591 MRW_RUNLOCK();
592 return 0;
593 }
594
595 /*
596 * returns the input and output packet and byte counts on the vif provided
597 */
598 static int
599 get_vif_cnt(struct sioc_vif_req *req)
600 {
601 vifi_t vifi = req->vifi;
602
603 MRW_RLOCK();
604 if (vifi >= V_numvifs) {
605 MRW_RUNLOCK();
606 return EINVAL;
607 }
608
609 mtx_lock_spin(&V_viftable[vifi].v_spin);
610 req->icount = V_viftable[vifi].v_pkt_in;
611 req->ocount = V_viftable[vifi].v_pkt_out;
612 req->ibytes = V_viftable[vifi].v_bytes_in;
613 req->obytes = V_viftable[vifi].v_bytes_out;
614 mtx_unlock_spin(&V_viftable[vifi].v_spin);
615 MRW_RUNLOCK();
616
617 return 0;
618 }
619
620 static void
621 if_detached_event(void *arg __unused, struct ifnet *ifp)
622 {
623 vifi_t vifi;
624 u_long i, vifi_cnt = 0;
625 struct ifnet *free_ptr;
626
627 MRW_WLOCK();
628
629 if (V_ip_mrouter == NULL) {
630 MRW_WUNLOCK();
631 return;
632 }
633
634 /*
635 * Tear down multicast forwarder state associated with this ifnet.
636 * 1. Walk the vif list, matching vifs against this ifnet.
637 * 2. Walk the multicast forwarding cache (mfc) looking for
638 * inner matches with this vif's index.
639 * 3. Expire any matching multicast forwarding cache entries.
640 * 4. Free vif state. This should disable ALLMULTI on the interface.
641 */
642 for (vifi = 0; vifi < V_numvifs; vifi++) {
643 if (V_viftable[vifi].v_ifp != ifp)
644 continue;
645 for (i = 0; i < mfchashsize; i++) {
646 struct mfc *rt, *nrt;
647
648 LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
649 if (rt->mfc_parent == vifi) {
650 expire_mfc(rt);
651 }
652 }
653 }
654 del_vif_locked(vifi, &free_ptr);
655 if (free_ptr != NULL)
656 vifi_cnt++;
657 }
658
659 MRW_WUNLOCK();
660
661 /*
662 * Free IFP. We don't have to use free_ptr here as it is the same
663 * that ifp. Perform free as many times as required in case
664 * refcount is greater than 1.
665 */
666 for (i = 0; i < vifi_cnt; i++)
667 if_free(ifp);
668 }
669
670 static void
671 ip_mrouter_upcall_thread(void *arg, int pending __unused)
672 {
673 CURVNET_SET((struct vnet *) arg);
674
675 MRW_WLOCK();
676 bw_upcalls_send();
677 MRW_WUNLOCK();
678
679 CURVNET_RESTORE();
680 }
681
682 /*
683 * Enable multicast forwarding.
684 */
685 static int
686 ip_mrouter_init(struct socket *so, int version)
687 {
688
689 CTR2(KTR_IPMF, "%s: so %p", __func__, so);
690
691 if (version != 1)
692 return ENOPROTOOPT;
693
694 MRW_WLOCK();
695
696 if (ip_mrouter_unloading) {
697 MRW_WUNLOCK();
698 return ENOPROTOOPT;
699 }
700
701 if (V_ip_mrouter != NULL) {
702 MRW_WUNLOCK();
703 return EADDRINUSE;
704 }
705
706 V_mfchashtbl = hashinit_flags(mfchashsize, M_MRTABLE, &V_mfchash,
707 HASH_NOWAIT);
708
709 /* Create upcall ring */
710 mtx_init(&V_bw_upcalls_ring_mtx, "mroute upcall buf_ring mtx", NULL, MTX_DEF);
711 V_bw_upcalls_ring = buf_ring_alloc(BW_UPCALLS_MAX, M_MRTABLE,
712 M_NOWAIT, &V_bw_upcalls_ring_mtx);
713 if (!V_bw_upcalls_ring) {
714 MRW_WUNLOCK();
715 return (ENOMEM);
716 }
717
718 TASK_INIT(&V_task, 0, ip_mrouter_upcall_thread, curvnet);
719 taskqueue_cancel(V_task_queue, &V_task, NULL);
720 taskqueue_unblock(V_task_queue);
721
722 callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
723 curvnet);
724 callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
725 curvnet);
726
727 V_ip_mrouter = so;
728 atomic_add_int(&ip_mrouter_cnt, 1);
729
730 /* This is a mutex required by buf_ring init, but not used internally */
731 mtx_init(&V_buf_ring_mtx, "mroute buf_ring mtx", NULL, MTX_DEF);
732
733 MRW_WUNLOCK();
734
735 CTR1(KTR_IPMF, "%s: done", __func__);
736
737 return 0;
738 }
739
740 /*
741 * Disable multicast forwarding.
742 */
743 static int
744 X_ip_mrouter_done(void)
745 {
746 struct ifnet **ifps;
747 int nifp;
748 u_long i;
749 vifi_t vifi;
750 struct bw_upcall *bu;
751
752 if (V_ip_mrouter == NULL)
753 return (EINVAL);
754
755 /*
756 * Detach/disable hooks to the reset of the system.
757 */
758 V_ip_mrouter = NULL;
759 atomic_subtract_int(&ip_mrouter_cnt, 1);
760 V_mrt_api_config = 0;
761
762 /*
763 * Wait for all epoch sections to complete to ensure
764 * V_ip_mrouter = NULL is visible to others.
765 */
766 epoch_wait_preempt(net_epoch_preempt);
767
768 /* Stop and drain task queue */
769 taskqueue_block(V_task_queue);
770 while (taskqueue_cancel(V_task_queue, &V_task, NULL)) {
771 taskqueue_drain(V_task_queue, &V_task);
772 }
773
774 ifps = malloc(MAXVIFS * sizeof(*ifps), M_TEMP, M_WAITOK);
775
776 MRW_WLOCK();
777 taskqueue_cancel(V_task_queue, &V_task, NULL);
778
779 /* Destroy upcall ring */
780 while ((bu = buf_ring_dequeue_mc(V_bw_upcalls_ring)) != NULL) {
781 free(bu, M_MRTABLE);
782 }
783 buf_ring_free(V_bw_upcalls_ring, M_MRTABLE);
784 mtx_destroy(&V_bw_upcalls_ring_mtx);
785
786 /*
787 * For each phyint in use, prepare to disable promiscuous reception
788 * of all IP multicasts. Defer the actual call until the lock is released;
789 * just record the list of interfaces while locked. Some interfaces use
790 * sx locks in their ioctl routines, which is not allowed while holding
791 * a non-sleepable lock.
792 */
793 KASSERT(V_numvifs <= MAXVIFS, ("More vifs than possible"));
794 for (vifi = 0, nifp = 0; vifi < V_numvifs; vifi++) {
795 if (!in_nullhost(V_viftable[vifi].v_lcl_addr) &&
796 !(V_viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
797 ifps[nifp++] = V_viftable[vifi].v_ifp;
798 }
799 }
800 bzero((caddr_t)V_viftable, sizeof(*V_viftable) * MAXVIFS);
801 V_numvifs = 0;
802 V_pim_assert_enabled = 0;
803
804 callout_stop(&V_expire_upcalls_ch);
805 callout_stop(&V_bw_upcalls_ch);
806
807 /*
808 * Free all multicast forwarding cache entries.
809 * Do not use hashdestroy(), as we must perform other cleanup.
810 */
811 for (i = 0; i < mfchashsize; i++) {
812 struct mfc *rt, *nrt;
813
814 LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
815 expire_mfc(rt);
816 }
817 }
818 free(V_mfchashtbl, M_MRTABLE);
819 V_mfchashtbl = NULL;
820
821 bzero(V_nexpire, sizeof(V_nexpire[0]) * mfchashsize);
822
823 V_reg_vif_num = VIFI_INVALID;
824
825 mtx_destroy(&V_buf_ring_mtx);
826
827 MRW_WUNLOCK();
828
829 /*
830 * Now drop our claim on promiscuous multicast on the interfaces recorded
831 * above. This is safe to do now because ALLMULTI is reference counted.
832 */
833 for (vifi = 0; vifi < nifp; vifi++)
834 if_allmulti(ifps[vifi], 0);
835 free(ifps, M_TEMP);
836
837 CTR1(KTR_IPMF, "%s: done", __func__);
838
839 return 0;
840 }
841
842 /*
843 * Set PIM assert processing global
844 */
845 static int
846 set_assert(int i)
847 {
848 if ((i != 1) && (i != 0))
849 return EINVAL;
850
851 V_pim_assert_enabled = i;
852
853 return 0;
854 }
855
856 /*
857 * Configure API capabilities
858 */
859 int
860 set_api_config(uint32_t *apival)
861 {
862 u_long i;
863
864 /*
865 * We can set the API capabilities only if it is the first operation
866 * after MRT_INIT. I.e.:
867 * - there are no vifs installed
868 * - pim_assert is not enabled
869 * - the MFC table is empty
870 */
871 if (V_numvifs > 0) {
872 *apival = 0;
873 return EPERM;
874 }
875 if (V_pim_assert_enabled) {
876 *apival = 0;
877 return EPERM;
878 }
879
880 MRW_RLOCK();
881
882 for (i = 0; i < mfchashsize; i++) {
883 if (LIST_FIRST(&V_mfchashtbl[i]) != NULL) {
884 MRW_RUNLOCK();
885 *apival = 0;
886 return EPERM;
887 }
888 }
889
890 MRW_RUNLOCK();
891
892 V_mrt_api_config = *apival & mrt_api_support;
893 *apival = V_mrt_api_config;
894
895 return 0;
896 }
897
898 /*
899 * Add a vif to the vif table
900 */
901 static int
902 add_vif(struct vifctl *vifcp)
903 {
904 struct vif *vifp = V_viftable + vifcp->vifc_vifi;
905 struct sockaddr_in sin = {sizeof sin, AF_INET};
906 struct ifaddr *ifa;
907 struct ifnet *ifp;
908 int error;
909
910
911 if (vifcp->vifc_vifi >= MAXVIFS)
912 return EINVAL;
913 /* rate limiting is no longer supported by this code */
914 if (vifcp->vifc_rate_limit != 0) {
915 log(LOG_ERR, "rate limiting is no longer supported\n");
916 return EINVAL;
917 }
918
919 if (in_nullhost(vifcp->vifc_lcl_addr))
920 return EADDRNOTAVAIL;
921
922 /* Find the interface with an address in AF_INET family */
923 if (vifcp->vifc_flags & VIFF_REGISTER) {
924 /*
925 * XXX: Because VIFF_REGISTER does not really need a valid
926 * local interface (e.g. it could be 127.0.0.2), we don't
927 * check its address.
928 */
929 ifp = NULL;
930 } else {
931 struct epoch_tracker et;
932
933 sin.sin_addr = vifcp->vifc_lcl_addr;
934 NET_EPOCH_ENTER(et);
935 ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
936 if (ifa == NULL) {
937 NET_EPOCH_EXIT(et);
938 return EADDRNOTAVAIL;
939 }
940 ifp = ifa->ifa_ifp;
941 /* XXX FIXME we need to take a ref on ifp and cleanup properly! */
942 NET_EPOCH_EXIT(et);
943 }
944
945 if ((vifcp->vifc_flags & VIFF_TUNNEL) != 0) {
946 CTR1(KTR_IPMF, "%s: tunnels are no longer supported", __func__);
947 return EOPNOTSUPP;
948 } else if (vifcp->vifc_flags & VIFF_REGISTER) {
949 ifp = V_multicast_register_if = if_alloc(IFT_LOOP);
950 CTR2(KTR_IPMF, "%s: add register vif for ifp %p", __func__, ifp);
951 if (V_reg_vif_num == VIFI_INVALID) {
952 if_initname(V_multicast_register_if, "register_vif", 0);
953 V_reg_vif_num = vifcp->vifc_vifi;
954 }
955 } else { /* Make sure the interface supports multicast */
956 if ((ifp->if_flags & IFF_MULTICAST) == 0)
957 return EOPNOTSUPP;
958
959 /* Enable promiscuous reception of all IP multicasts from the if */
960 error = if_allmulti(ifp, 1);
961 if (error)
962 return error;
963 }
964
965 MRW_WLOCK();
966
967 if (!in_nullhost(vifp->v_lcl_addr)) {
968 if (ifp)
969 V_multicast_register_if = NULL;
970 MRW_WUNLOCK();
971 if (ifp)
972 if_free(ifp);
973 return EADDRINUSE;
974 }
975
976 vifp->v_flags = vifcp->vifc_flags;
977 vifp->v_threshold = vifcp->vifc_threshold;
978 vifp->v_lcl_addr = vifcp->vifc_lcl_addr;
979 vifp->v_rmt_addr = vifcp->vifc_rmt_addr;
980 vifp->v_ifp = ifp;
981 /* initialize per vif pkt counters */
982 vifp->v_pkt_in = 0;
983 vifp->v_pkt_out = 0;
984 vifp->v_bytes_in = 0;
985 vifp->v_bytes_out = 0;
986 sprintf(vifp->v_spin_name, "BM[%d] spin", vifcp->vifc_vifi);
987 mtx_init(&vifp->v_spin, vifp->v_spin_name, NULL, MTX_SPIN);
988
989 /* Adjust numvifs up if the vifi is higher than numvifs */
990 if (V_numvifs <= vifcp->vifc_vifi)
991 V_numvifs = vifcp->vifc_vifi + 1;
992
993 MRW_WUNLOCK();
994
995 CTR4(KTR_IPMF, "%s: add vif %d laddr 0x%08x thresh %x", __func__,
996 (int)vifcp->vifc_vifi, ntohl(vifcp->vifc_lcl_addr.s_addr),
997 (int)vifcp->vifc_threshold);
998
999 return 0;
1000 }
1001
1002 /*
1003 * Delete a vif from the vif table
1004 */
1005 static int
1006 del_vif_locked(vifi_t vifi, struct ifnet **ifp_free)
1007 {
1008 struct vif *vifp;
1009
1010 *ifp_free = NULL;
1011
1012 MRW_WLOCK_ASSERT();
1013
1014 if (vifi >= V_numvifs) {
1015 return EINVAL;
1016 }
1017 vifp = &V_viftable[vifi];
1018 if (in_nullhost(vifp->v_lcl_addr)) {
1019 return EADDRNOTAVAIL;
1020 }
1021
1022 if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
1023 if_allmulti(vifp->v_ifp, 0);
1024
1025 if (vifp->v_flags & VIFF_REGISTER) {
1026 V_reg_vif_num = VIFI_INVALID;
1027 if (vifp->v_ifp) {
1028 if (vifp->v_ifp == V_multicast_register_if)
1029 V_multicast_register_if = NULL;
1030 *ifp_free = vifp->v_ifp;
1031 }
1032 }
1033
1034 mtx_destroy(&vifp->v_spin);
1035
1036 bzero((caddr_t)vifp, sizeof (*vifp));
1037
1038 CTR2(KTR_IPMF, "%s: delete vif %d", __func__, (int)vifi);
1039
1040 /* Adjust numvifs down */
1041 for (vifi = V_numvifs; vifi > 0; vifi--)
1042 if (!in_nullhost(V_viftable[vifi-1].v_lcl_addr))
1043 break;
1044 V_numvifs = vifi;
1045
1046 return 0;
1047 }
1048
1049 static int
1050 del_vif(vifi_t vifi)
1051 {
1052 int cc;
1053 struct ifnet *free_ptr;
1054
1055 MRW_WLOCK();
1056 cc = del_vif_locked(vifi, &free_ptr);
1057 MRW_WUNLOCK();
1058
1059 if (free_ptr)
1060 if_free(free_ptr);
1061
1062 return cc;
1063 }
1064
1065 /*
1066 * update an mfc entry without resetting counters and S,G addresses.
1067 */
1068 static void
1069 update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1070 {
1071 int i;
1072
1073 rt->mfc_parent = mfccp->mfcc_parent;
1074 for (i = 0; i < V_numvifs; i++) {
1075 rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1076 rt->mfc_flags[i] = mfccp->mfcc_flags[i] & V_mrt_api_config &
1077 MRT_MFC_FLAGS_ALL;
1078 }
1079 /* set the RP address */
1080 if (V_mrt_api_config & MRT_MFC_RP)
1081 rt->mfc_rp = mfccp->mfcc_rp;
1082 else
1083 rt->mfc_rp.s_addr = INADDR_ANY;
1084 }
1085
1086 /*
1087 * fully initialize an mfc entry from the parameter.
1088 */
1089 static void
1090 init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1091 {
1092 rt->mfc_origin = mfccp->mfcc_origin;
1093 rt->mfc_mcastgrp = mfccp->mfcc_mcastgrp;
1094
1095 update_mfc_params(rt, mfccp);
1096
1097 /* initialize pkt counters per src-grp */
1098 rt->mfc_pkt_cnt = 0;
1099 rt->mfc_byte_cnt = 0;
1100 rt->mfc_wrong_if = 0;
1101 timevalclear(&rt->mfc_last_assert);
1102 }
1103
1104 static void
1105 expire_mfc(struct mfc *rt)
1106 {
1107 struct rtdetq *rte;
1108
1109 MRW_WLOCK_ASSERT();
1110
1111 free_bw_list(rt->mfc_bw_meter_leq);
1112 free_bw_list(rt->mfc_bw_meter_geq);
1113
1114 while (!buf_ring_empty(rt->mfc_stall_ring)) {
1115 rte = buf_ring_dequeue_mc(rt->mfc_stall_ring);
1116 if (rte) {
1117 m_freem(rte->m);
1118 free(rte, M_MRTABLE);
1119 }
1120 }
1121 buf_ring_free(rt->mfc_stall_ring, M_MRTABLE);
1122
1123 LIST_REMOVE(rt, mfc_hash);
1124 free(rt, M_MRTABLE);
1125 }
1126
1127 /*
1128 * Add an mfc entry
1129 */
1130 static int
1131 add_mfc(struct mfcctl2 *mfccp)
1132 {
1133 struct mfc *rt;
1134 struct rtdetq *rte;
1135 u_long hash = 0;
1136 u_short nstl;
1137 struct epoch_tracker et;
1138
1139 MRW_WLOCK();
1140 rt = mfc_find(&mfccp->mfcc_origin, &mfccp->mfcc_mcastgrp);
1141
1142 /* If an entry already exists, just update the fields */
1143 if (rt) {
1144 CTR4(KTR_IPMF, "%s: update mfc orig 0x%08x group %lx parent %x",
1145 __func__, ntohl(mfccp->mfcc_origin.s_addr),
1146 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1147 mfccp->mfcc_parent);
1148 update_mfc_params(rt, mfccp);
1149 MRW_WUNLOCK();
1150 return (0);
1151 }
1152
1153 /*
1154 * Find the entry for which the upcall was made and update
1155 */
1156 nstl = 0;
1157 hash = MFCHASH(mfccp->mfcc_origin, mfccp->mfcc_mcastgrp);
1158 NET_EPOCH_ENTER(et);
1159 LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1160 if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1161 in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp) &&
1162 !buf_ring_empty(rt->mfc_stall_ring)) {
1163 CTR5(KTR_IPMF,
1164 "%s: add mfc orig 0x%08x group %lx parent %x qh %p",
1165 __func__, ntohl(mfccp->mfcc_origin.s_addr),
1166 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1167 mfccp->mfcc_parent,
1168 rt->mfc_stall_ring);
1169 if (nstl++)
1170 CTR1(KTR_IPMF, "%s: multiple matches", __func__);
1171
1172 init_mfc_params(rt, mfccp);
1173 rt->mfc_expire = 0; /* Don't clean this guy up */
1174 V_nexpire[hash]--;
1175
1176 /* Free queued packets, but attempt to forward them first. */
1177 while (!buf_ring_empty(rt->mfc_stall_ring)) {
1178 rte = buf_ring_dequeue_mc(rt->mfc_stall_ring);
1179 if (rte->ifp != NULL)
1180 ip_mdq(rte->m, rte->ifp, rt, -1);
1181 m_freem(rte->m);
1182 free(rte, M_MRTABLE);
1183 }
1184 }
1185 }
1186 NET_EPOCH_EXIT(et);
1187
1188 /*
1189 * It is possible that an entry is being inserted without an upcall
1190 */
1191 if (nstl == 0) {
1192 CTR1(KTR_IPMF, "%s: adding mfc w/o upcall", __func__);
1193 LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash) {
1194 if (in_hosteq(rt->mfc_origin, mfccp->mfcc_origin) &&
1195 in_hosteq(rt->mfc_mcastgrp, mfccp->mfcc_mcastgrp)) {
1196 init_mfc_params(rt, mfccp);
1197 if (rt->mfc_expire)
1198 V_nexpire[hash]--;
1199 rt->mfc_expire = 0;
1200 break; /* XXX */
1201 }
1202 }
1203
1204 if (rt == NULL) { /* no upcall, so make a new entry */
1205 rt = mfc_alloc();
1206 if (rt == NULL) {
1207 MRW_WUNLOCK();
1208 return (ENOBUFS);
1209 }
1210
1211 init_mfc_params(rt, mfccp);
1212
1213 rt->mfc_expire = 0;
1214 rt->mfc_bw_meter_leq = NULL;
1215 rt->mfc_bw_meter_geq = NULL;
1216
1217 /* insert new entry at head of hash chain */
1218 LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1219 }
1220 }
1221
1222 MRW_WUNLOCK();
1223
1224 return (0);
1225 }
1226
1227 /*
1228 * Delete an mfc entry
1229 */
1230 static int
1231 del_mfc(struct mfcctl2 *mfccp)
1232 {
1233 struct in_addr origin;
1234 struct in_addr mcastgrp;
1235 struct mfc *rt;
1236
1237 origin = mfccp->mfcc_origin;
1238 mcastgrp = mfccp->mfcc_mcastgrp;
1239
1240 CTR3(KTR_IPMF, "%s: delete mfc orig 0x%08x group %lx", __func__,
1241 ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
1242
1243 MRW_WLOCK();
1244
1245 rt = mfc_find(&origin, &mcastgrp);
1246 if (rt == NULL) {
1247 MRW_WUNLOCK();
1248 return EADDRNOTAVAIL;
1249 }
1250
1251 /*
1252 * free the bw_meter entries
1253 */
1254 free_bw_list(rt->mfc_bw_meter_leq);
1255 rt->mfc_bw_meter_leq = NULL;
1256 free_bw_list(rt->mfc_bw_meter_geq);
1257 rt->mfc_bw_meter_geq = NULL;
1258
1259 LIST_REMOVE(rt, mfc_hash);
1260 free(rt, M_MRTABLE);
1261
1262 MRW_WUNLOCK();
1263
1264 return (0);
1265 }
1266
1267 /*
1268 * Send a message to the routing daemon on the multicast routing socket.
1269 */
1270 static int
1271 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1272 {
1273 if (s) {
1274 SOCKBUF_LOCK(&s->so_rcv);
1275 if (sbappendaddr_locked(&s->so_rcv, (struct sockaddr *)src, mm,
1276 NULL) != 0) {
1277 sorwakeup_locked(s);
1278 return 0;
1279 }
1280 soroverflow_locked(s);
1281 }
1282 m_freem(mm);
1283 return -1;
1284 }
1285
1286 /*
1287 * IP multicast forwarding function. This function assumes that the packet
1288 * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1289 * pointed to by "ifp", and the packet is to be relayed to other networks
1290 * that have members of the packet's destination IP multicast group.
1291 *
1292 * The packet is returned unscathed to the caller, unless it is
1293 * erroneous, in which case a non-zero return value tells the caller to
1294 * discard it.
1295 */
1296
1297 #define TUNNEL_LEN 12 /* # bytes of IP option for tunnel encapsulation */
1298
1299 static int
1300 X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1301 struct ip_moptions *imo)
1302 {
1303 struct mfc *rt;
1304 int error;
1305 vifi_t vifi;
1306 struct mbuf *mb0;
1307 struct rtdetq *rte;
1308 u_long hash;
1309 int hlen;
1310
1311 CTR3(KTR_IPMF, "ip_mforward: delete mfc orig 0x%08x group %lx ifp %p",
1312 ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr), ifp);
1313
1314 if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1315 ((u_char *)(ip + 1))[1] != IPOPT_LSRR) {
1316 /*
1317 * Packet arrived via a physical interface or
1318 * an encapsulated tunnel or a register_vif.
1319 */
1320 } else {
1321 /*
1322 * Packet arrived through a source-route tunnel.
1323 * Source-route tunnels are no longer supported.
1324 */
1325 return (1);
1326 }
1327
1328 /*
1329 * BEGIN: MCAST ROUTING HOT PATH
1330 */
1331 MRW_RLOCK();
1332 if (imo && ((vifi = imo->imo_multicast_vif) < V_numvifs)) {
1333 if (ip->ip_ttl < MAXTTL)
1334 ip->ip_ttl++; /* compensate for -1 in *_send routines */
1335 error = ip_mdq(m, ifp, NULL, vifi);
1336 MRW_RUNLOCK();
1337 return error;
1338 }
1339
1340 /*
1341 * Don't forward a packet with time-to-live of zero or one,
1342 * or a packet destined to a local-only group.
1343 */
1344 if (ip->ip_ttl <= 1 || IN_LOCAL_GROUP(ntohl(ip->ip_dst.s_addr))) {
1345 MRW_RUNLOCK();
1346 return 0;
1347 }
1348
1349 mfc_find_retry:
1350 /*
1351 * Determine forwarding vifs from the forwarding cache table
1352 */
1353 MRTSTAT_INC(mrts_mfc_lookups);
1354 rt = mfc_find(&ip->ip_src, &ip->ip_dst);
1355
1356 /* Entry exists, so forward if necessary */
1357 if (rt != NULL) {
1358 error = ip_mdq(m, ifp, rt, -1);
1359 /* Generic unlock here as we might release R or W lock */
1360 MRW_UNLOCK();
1361 return error;
1362 }
1363
1364 /*
1365 * END: MCAST ROUTING HOT PATH
1366 */
1367
1368 /* Further processing must be done with WLOCK taken */
1369 if ((MRW_WOWNED() == 0) && (MRW_LOCK_TRY_UPGRADE() == 0)) {
1370 MRW_RUNLOCK();
1371 MRW_WLOCK();
1372 goto mfc_find_retry;
1373 }
1374
1375 /*
1376 * If we don't have a route for packet's origin,
1377 * Make a copy of the packet & send message to routing daemon
1378 */
1379 hlen = ip->ip_hl << 2;
1380
1381 MRTSTAT_INC(mrts_mfc_misses);
1382 MRTSTAT_INC(mrts_no_route);
1383 CTR2(KTR_IPMF, "ip_mforward: no mfc for (0x%08x,%lx)",
1384 ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr));
1385
1386 /*
1387 * Allocate mbufs early so that we don't do extra work if we are
1388 * just going to fail anyway. Make sure to pullup the header so
1389 * that other people can't step on it.
1390 */
1391 rte = (struct rtdetq*) malloc((sizeof *rte), M_MRTABLE,
1392 M_NOWAIT|M_ZERO);
1393 if (rte == NULL) {
1394 MRW_WUNLOCK();
1395 return ENOBUFS;
1396 }
1397
1398 mb0 = m_copypacket(m, M_NOWAIT);
1399 if (mb0 && (!M_WRITABLE(mb0) || mb0->m_len < hlen))
1400 mb0 = m_pullup(mb0, hlen);
1401 if (mb0 == NULL) {
1402 free(rte, M_MRTABLE);
1403 MRW_WUNLOCK();
1404 return ENOBUFS;
1405 }
1406
1407 /* is there an upcall waiting for this flow ? */
1408 hash = MFCHASH(ip->ip_src, ip->ip_dst);
1409 LIST_FOREACH(rt, &V_mfchashtbl[hash], mfc_hash)
1410 {
1411 if (in_hosteq(ip->ip_src, rt->mfc_origin) &&
1412 in_hosteq(ip->ip_dst, rt->mfc_mcastgrp) &&
1413 !buf_ring_empty(rt->mfc_stall_ring))
1414 break;
1415 }
1416
1417 if (rt == NULL) {
1418 int i;
1419 struct igmpmsg *im;
1420 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1421 struct mbuf *mm;
1422
1423 /*
1424 * Locate the vifi for the incoming interface for this packet.
1425 * If none found, drop packet.
1426 */
1427 for (vifi = 0; vifi < V_numvifs &&
1428 V_viftable[vifi].v_ifp != ifp; vifi++)
1429 ;
1430 if (vifi >= V_numvifs) /* vif not found, drop packet */
1431 goto non_fatal;
1432
1433 /* no upcall, so make a new entry */
1434 rt = mfc_alloc();
1435 if (rt == NULL)
1436 goto fail;
1437
1438 /* Make a copy of the header to send to the user level process */
1439 mm = m_copym(mb0, 0, hlen, M_NOWAIT);
1440 if (mm == NULL)
1441 goto fail1;
1442
1443 /*
1444 * Send message to routing daemon to install
1445 * a route into the kernel table
1446 */
1447
1448 im = mtod(mm, struct igmpmsg*);
1449 im->im_msgtype = IGMPMSG_NOCACHE;
1450 im->im_mbz = 0;
1451 im->im_vif = vifi;
1452
1453 MRTSTAT_INC(mrts_upcalls);
1454
1455 k_igmpsrc.sin_addr = ip->ip_src;
1456 if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1457 CTR0(KTR_IPMF, "ip_mforward: socket queue full");
1458 MRTSTAT_INC(mrts_upq_sockfull);
1459 fail1: free(rt, M_MRTABLE);
1460 fail: free(rte, M_MRTABLE);
1461 m_freem(mb0);
1462 MRW_WUNLOCK();
1463 return ENOBUFS;
1464 }
1465
1466 /* insert new entry at head of hash chain */
1467 rt->mfc_origin.s_addr = ip->ip_src.s_addr;
1468 rt->mfc_mcastgrp.s_addr = ip->ip_dst.s_addr;
1469 rt->mfc_expire = UPCALL_EXPIRE;
1470 V_nexpire[hash]++;
1471 for (i = 0; i < V_numvifs; i++) {
1472 rt->mfc_ttls[i] = 0;
1473 rt->mfc_flags[i] = 0;
1474 }
1475 rt->mfc_parent = -1;
1476
1477 /* clear the RP address */
1478 rt->mfc_rp.s_addr = INADDR_ANY;
1479 rt->mfc_bw_meter_leq = NULL;
1480 rt->mfc_bw_meter_geq = NULL;
1481
1482 /* initialize pkt counters per src-grp */
1483 rt->mfc_pkt_cnt = 0;
1484 rt->mfc_byte_cnt = 0;
1485 rt->mfc_wrong_if = 0;
1486 timevalclear(&rt->mfc_last_assert);
1487
1488 buf_ring_enqueue(rt->mfc_stall_ring, rte);
1489
1490 /* Add RT to hashtable as it didn't exist before */
1491 LIST_INSERT_HEAD(&V_mfchashtbl[hash], rt, mfc_hash);
1492 } else {
1493 /* determine if queue has overflowed */
1494 if (buf_ring_full(rt->mfc_stall_ring)) {
1495 MRTSTAT_INC(mrts_upq_ovflw);
1496 non_fatal: free(rte, M_MRTABLE);
1497 m_freem(mb0);
1498 MRW_WUNLOCK();
1499 return (0);
1500 }
1501
1502 buf_ring_enqueue(rt->mfc_stall_ring, rte);
1503 }
1504
1505 rte->m = mb0;
1506 rte->ifp = ifp;
1507
1508 MRW_WUNLOCK();
1509
1510 return 0;
1511 }
1512
1513 /*
1514 * Clean up the cache entry if upcall is not serviced
1515 */
1516 static void
1517 expire_upcalls(void *arg)
1518 {
1519 u_long i;
1520
1521 CURVNET_SET((struct vnet *) arg);
1522
1523 /*This callout is always run with MRW_WLOCK taken. */
1524
1525 for (i = 0; i < mfchashsize; i++) {
1526 struct mfc *rt, *nrt;
1527
1528 if (V_nexpire[i] == 0)
1529 continue;
1530
1531 LIST_FOREACH_SAFE(rt, &V_mfchashtbl[i], mfc_hash, nrt) {
1532 if (buf_ring_empty(rt->mfc_stall_ring))
1533 continue;
1534
1535 if (rt->mfc_expire == 0 || --rt->mfc_expire > 0)
1536 continue;
1537
1538 MRTSTAT_INC(mrts_cache_cleanups);
1539 CTR3(KTR_IPMF, "%s: expire (%lx, %lx)", __func__,
1540 (u_long)ntohl(rt->mfc_origin.s_addr),
1541 (u_long)ntohl(rt->mfc_mcastgrp.s_addr));
1542
1543 expire_mfc(rt);
1544 }
1545 }
1546
1547 callout_reset(&V_expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls,
1548 curvnet);
1549
1550 CURVNET_RESTORE();
1551 }
1552
1553 /*
1554 * Packet forwarding routine once entry in the cache is made
1555 */
1556 static int
1557 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1558 {
1559 struct ip *ip = mtod(m, struct ip *);
1560 vifi_t vifi;
1561 int plen = ntohs(ip->ip_len);
1562
1563 MRW_LOCK_ASSERT();
1564 NET_EPOCH_ASSERT();
1565
1566 /*
1567 * If xmt_vif is not -1, send on only the requested vif.
1568 *
1569 * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1570 */
1571 if (xmt_vif < V_numvifs) {
1572 if (V_viftable[xmt_vif].v_flags & VIFF_REGISTER)
1573 pim_register_send(ip, V_viftable + xmt_vif, m, rt);
1574 else
1575 phyint_send(ip, V_viftable + xmt_vif, m);
1576 return 1;
1577 }
1578
1579 /*
1580 * Don't forward if it didn't arrive from the parent vif for its origin.
1581 */
1582 vifi = rt->mfc_parent;
1583 if ((vifi >= V_numvifs) || (V_viftable[vifi].v_ifp != ifp)) {
1584 CTR4(KTR_IPMF, "%s: rx on wrong ifp %p (vifi %d, v_ifp %p)",
1585 __func__, ifp, (int)vifi, V_viftable[vifi].v_ifp);
1586 MRTSTAT_INC(mrts_wrong_if);
1587 ++rt->mfc_wrong_if;
1588 /*
1589 * If we are doing PIM assert processing, send a message
1590 * to the routing daemon.
1591 *
1592 * XXX: A PIM-SM router needs the WRONGVIF detection so it
1593 * can complete the SPT switch, regardless of the type
1594 * of the iif (broadcast media, GRE tunnel, etc).
1595 */
1596 if (V_pim_assert_enabled && (vifi < V_numvifs) &&
1597 V_viftable[vifi].v_ifp) {
1598 if (ifp == V_multicast_register_if)
1599 PIMSTAT_INC(pims_rcv_registers_wrongiif);
1600
1601 /* Get vifi for the incoming packet */
1602 for (vifi = 0; vifi < V_numvifs && V_viftable[vifi].v_ifp != ifp;
1603 vifi++)
1604 ;
1605 if (vifi >= V_numvifs)
1606 return 0; /* The iif is not found: ignore the packet. */
1607
1608 if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1609 return 0; /* WRONGVIF disabled: ignore the packet */
1610
1611 if (ratecheck(&rt->mfc_last_assert, &pim_assert_interval)) {
1612 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1613 struct igmpmsg *im;
1614 int hlen = ip->ip_hl << 2;
1615 struct mbuf *mm = m_copym(m, 0, hlen, M_NOWAIT);
1616
1617 if (mm && (!M_WRITABLE(mm) || mm->m_len < hlen))
1618 mm = m_pullup(mm, hlen);
1619 if (mm == NULL)
1620 return ENOBUFS;
1621
1622 im = mtod(mm, struct igmpmsg *);
1623 im->im_msgtype = IGMPMSG_WRONGVIF;
1624 im->im_mbz = 0;
1625 im->im_vif = vifi;
1626
1627 MRTSTAT_INC(mrts_upcalls);
1628
1629 k_igmpsrc.sin_addr = im->im_src;
1630 if (socket_send(V_ip_mrouter, mm, &k_igmpsrc) < 0) {
1631 CTR1(KTR_IPMF, "%s: socket queue full", __func__);
1632 MRTSTAT_INC(mrts_upq_sockfull);
1633 return ENOBUFS;
1634 }
1635 }
1636 }
1637 return 0;
1638 }
1639
1640 /* If I sourced this packet, it counts as output, else it was input. */
1641 mtx_lock_spin(&V_viftable[vifi].v_spin);
1642 if (in_hosteq(ip->ip_src, V_viftable[vifi].v_lcl_addr)) {
1643 V_viftable[vifi].v_pkt_out++;
1644 V_viftable[vifi].v_bytes_out += plen;
1645 } else {
1646 V_viftable[vifi].v_pkt_in++;
1647 V_viftable[vifi].v_bytes_in += plen;
1648 }
1649 mtx_unlock_spin(&V_viftable[vifi].v_spin);
1650
1651 rt->mfc_pkt_cnt++;
1652 rt->mfc_byte_cnt += plen;
1653
1654 /*
1655 * For each vif, decide if a copy of the packet should be forwarded.
1656 * Forward if:
1657 * - the ttl exceeds the vif's threshold
1658 * - there are group members downstream on interface
1659 */
1660 for (vifi = 0; vifi < V_numvifs; vifi++)
1661 if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1662 V_viftable[vifi].v_pkt_out++;
1663 V_viftable[vifi].v_bytes_out += plen;
1664 if (V_viftable[vifi].v_flags & VIFF_REGISTER)
1665 pim_register_send(ip, V_viftable + vifi, m, rt);
1666 else
1667 phyint_send(ip, V_viftable + vifi, m);
1668 }
1669
1670 /*
1671 * Perform upcall-related bw measuring.
1672 */
1673 if ((rt->mfc_bw_meter_geq != NULL) || (rt->mfc_bw_meter_leq != NULL)) {
1674 struct bw_meter *x;
1675 struct timeval now;
1676
1677 microtime(&now);
1678 /* Process meters for Greater-or-EQual case */
1679 for (x = rt->mfc_bw_meter_geq; x != NULL; x = x->bm_mfc_next)
1680 bw_meter_geq_receive_packet(x, plen, &now);
1681
1682 /* Process meters for Lower-or-EQual case */
1683 for (x = rt->mfc_bw_meter_leq; x != NULL; x = x->bm_mfc_next) {
1684 /*
1685 * Record that a packet is received.
1686 * Spin lock has to be taken as callout context
1687 * (expire_bw_meter_leq) might modify these fields
1688 * as well
1689 */
1690 mtx_lock_spin(&x->bm_spin);
1691 x->bm_measured.b_packets++;
1692 x->bm_measured.b_bytes += plen;
1693 mtx_unlock_spin(&x->bm_spin);
1694 }
1695 }
1696
1697 return 0;
1698 }
1699
1700 /*
1701 * Check if a vif number is legal/ok. This is used by in_mcast.c.
1702 */
1703 static int
1704 X_legal_vif_num(int vif)
1705 {
1706 int ret;
1707
1708 ret = 0;
1709 if (vif < 0)
1710 return (ret);
1711
1712 MRW_RLOCK();
1713 if (vif < V_numvifs)
1714 ret = 1;
1715 MRW_RUNLOCK();
1716
1717 return (ret);
1718 }
1719
1720 /*
1721 * Return the local address used by this vif
1722 */
1723 static u_long
1724 X_ip_mcast_src(int vifi)
1725 {
1726 in_addr_t addr;
1727
1728 addr = INADDR_ANY;
1729 if (vifi < 0)
1730 return (addr);
1731
1732 MRW_RLOCK();
1733 if (vifi < V_numvifs)
1734 addr = V_viftable[vifi].v_lcl_addr.s_addr;
1735 MRW_RUNLOCK();
1736
1737 return (addr);
1738 }
1739
1740 static void
1741 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1742 {
1743 struct mbuf *mb_copy;
1744 int hlen = ip->ip_hl << 2;
1745
1746 MRW_LOCK_ASSERT();
1747
1748 /*
1749 * Make a new reference to the packet; make sure that
1750 * the IP header is actually copied, not just referenced,
1751 * so that ip_output() only scribbles on the copy.
1752 */
1753 mb_copy = m_copypacket(m, M_NOWAIT);
1754 if (mb_copy && (!M_WRITABLE(mb_copy) || mb_copy->m_len < hlen))
1755 mb_copy = m_pullup(mb_copy, hlen);
1756 if (mb_copy == NULL)
1757 return;
1758
1759 send_packet(vifp, mb_copy);
1760 }
1761
1762 static void
1763 send_packet(struct vif *vifp, struct mbuf *m)
1764 {
1765 struct ip_moptions imo;
1766 int error __unused;
1767
1768 MRW_LOCK_ASSERT();
1769 NET_EPOCH_ASSERT();
1770
1771 imo.imo_multicast_ifp = vifp->v_ifp;
1772 imo.imo_multicast_ttl = mtod(m, struct ip *)->ip_ttl - 1;
1773 imo.imo_multicast_loop = !!in_mcast_loop;
1774 imo.imo_multicast_vif = -1;
1775 STAILQ_INIT(&imo.imo_head);
1776
1777 /*
1778 * Re-entrancy should not be a problem here, because
1779 * the packets that we send out and are looped back at us
1780 * should get rejected because they appear to come from
1781 * the loopback interface, thus preventing looping.
1782 */
1783 error = ip_output(m, NULL, NULL, IP_FORWARDING, &imo, NULL);
1784 CTR3(KTR_IPMF, "%s: vif %td err %d", __func__,
1785 (ptrdiff_t)(vifp - V_viftable), error);
1786 }
1787
1788 /*
1789 * Stubs for old RSVP socket shim implementation.
1790 */
1791
1792 static int
1793 X_ip_rsvp_vif(struct socket *so __unused, struct sockopt *sopt __unused)
1794 {
1795
1796 return (EOPNOTSUPP);
1797 }
1798
1799 static void
1800 X_ip_rsvp_force_done(struct socket *so __unused)
1801 {
1802
1803 }
1804
1805 static int
1806 X_rsvp_input(struct mbuf **mp, int *offp, int proto)
1807 {
1808 struct mbuf *m;
1809
1810 m = *mp;
1811 *mp = NULL;
1812 if (!V_rsvp_on)
1813 m_freem(m);
1814 return (IPPROTO_DONE);
1815 }
1816
1817 /*
1818 * Code for bandwidth monitors
1819 */
1820
1821 /*
1822 * Define common interface for timeval-related methods
1823 */
1824 #define BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
1825 #define BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
1826 #define BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
1827
1828 static uint32_t
1829 compute_bw_meter_flags(struct bw_upcall *req)
1830 {
1831 uint32_t flags = 0;
1832
1833 if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
1834 flags |= BW_METER_UNIT_PACKETS;
1835 if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
1836 flags |= BW_METER_UNIT_BYTES;
1837 if (req->bu_flags & BW_UPCALL_GEQ)
1838 flags |= BW_METER_GEQ;
1839 if (req->bu_flags & BW_UPCALL_LEQ)
1840 flags |= BW_METER_LEQ;
1841
1842 return flags;
1843 }
1844
1845 static void
1846 expire_bw_meter_leq(void *arg)
1847 {
1848 struct bw_meter *x = arg;
1849 struct timeval now;
1850 /*
1851 * INFO:
1852 * callout is always executed with MRW_WLOCK taken
1853 */
1854
1855 CURVNET_SET((struct vnet *)x->arg);
1856
1857 microtime(&now);
1858
1859 /*
1860 * Test if we should deliver an upcall
1861 */
1862 if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
1863 (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
1864 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
1865 (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
1866 /* Prepare an upcall for delivery */
1867 bw_meter_prepare_upcall(x, &now);
1868 }
1869
1870 /* Send all upcalls that are pending delivery */
1871 taskqueue_enqueue(V_task_queue, &V_task);
1872
1873 /* Reset counters */
1874 x->bm_start_time = now;
1875 /* Spin lock has to be taken as ip_forward context
1876 * might modify these fields as well
1877 */
1878 mtx_lock_spin(&x->bm_spin);
1879 x->bm_measured.b_bytes = 0;
1880 x->bm_measured.b_packets = 0;
1881 mtx_unlock_spin(&x->bm_spin);
1882
1883 callout_schedule(&x->bm_meter_callout, tvtohz(&x->bm_threshold.b_time));
1884
1885 CURVNET_RESTORE();
1886 }
1887
1888 /*
1889 * Add a bw_meter entry
1890 */
1891 static int
1892 add_bw_upcall(struct bw_upcall *req)
1893 {
1894 struct mfc *mfc;
1895 struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
1896 BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
1897 struct timeval now;
1898 struct bw_meter *x, **bwm_ptr;
1899 uint32_t flags;
1900
1901 if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
1902 return EOPNOTSUPP;
1903
1904 /* Test if the flags are valid */
1905 if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
1906 return EINVAL;
1907 if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
1908 return EINVAL;
1909 if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
1910 == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
1911 return EINVAL;
1912
1913 /* Test if the threshold time interval is valid */
1914 if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
1915 return EINVAL;
1916
1917 flags = compute_bw_meter_flags(req);
1918
1919 /*
1920 * Find if we have already same bw_meter entry
1921 */
1922 MRW_WLOCK();
1923 mfc = mfc_find(&req->bu_src, &req->bu_dst);
1924 if (mfc == NULL) {
1925 MRW_WUNLOCK();
1926 return EADDRNOTAVAIL;
1927 }
1928
1929 /* Choose an appropriate bw_meter list */
1930 if (req->bu_flags & BW_UPCALL_GEQ)
1931 bwm_ptr = &mfc->mfc_bw_meter_geq;
1932 else
1933 bwm_ptr = &mfc->mfc_bw_meter_leq;
1934
1935 for (x = *bwm_ptr; x != NULL; x = x->bm_mfc_next) {
1936 if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
1937 &req->bu_threshold.b_time, ==))
1938 && (x->bm_threshold.b_packets
1939 == req->bu_threshold.b_packets)
1940 && (x->bm_threshold.b_bytes
1941 == req->bu_threshold.b_bytes)
1942 && (x->bm_flags & BW_METER_USER_FLAGS)
1943 == flags) {
1944 MRW_WUNLOCK();
1945 return 0; /* XXX Already installed */
1946 }
1947 }
1948
1949 /* Allocate the new bw_meter entry */
1950 x = (struct bw_meter*) malloc(sizeof(*x), M_BWMETER,
1951 M_ZERO | M_NOWAIT);
1952 if (x == NULL) {
1953 MRW_WUNLOCK();
1954 return ENOBUFS;
1955 }
1956
1957 /* Set the new bw_meter entry */
1958 x->bm_threshold.b_time = req->bu_threshold.b_time;
1959 microtime(&now);
1960 x->bm_start_time = now;
1961 x->bm_threshold.b_packets = req->bu_threshold.b_packets;
1962 x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
1963 x->bm_measured.b_packets = 0;
1964 x->bm_measured.b_bytes = 0;
1965 x->bm_flags = flags;
1966 x->bm_time_next = NULL;
1967 x->bm_mfc = mfc;
1968 x->arg = curvnet;
1969 sprintf(x->bm_spin_name, "BM spin %p", x);
1970 mtx_init(&x->bm_spin, x->bm_spin_name, NULL, MTX_SPIN);
1971
1972 /* For LEQ case create periodic callout */
1973 if (req->bu_flags & BW_UPCALL_LEQ) {
1974 callout_init_rw(&x->bm_meter_callout, &mrouter_mtx, CALLOUT_SHAREDLOCK);
1975 callout_reset(&x->bm_meter_callout, tvtohz(&x->bm_threshold.b_time),
1976 expire_bw_meter_leq, x);
1977 }
1978
1979 /* Add the new bw_meter entry to the front of entries for this MFC */
1980 x->bm_mfc_next = *bwm_ptr;
1981 *bwm_ptr = x;
1982
1983 MRW_WUNLOCK();
1984
1985 return 0;
1986 }
1987
1988 static void
1989 free_bw_list(struct bw_meter *list)
1990 {
1991 while (list != NULL) {
1992 struct bw_meter *x = list;
1993
1994 /* MRW_WLOCK must be held here */
1995 if (x->bm_flags & BW_METER_LEQ) {
1996 callout_drain(&x->bm_meter_callout);
1997 mtx_destroy(&x->bm_spin);
1998 }
1999
2000 list = list->bm_mfc_next;
2001 free(x, M_BWMETER);
2002 }
2003 }
2004
2005 /*
2006 * Delete one or multiple bw_meter entries
2007 */
2008 static int
2009 del_bw_upcall(struct bw_upcall *req)
2010 {
2011 struct mfc *mfc;
2012 struct bw_meter *x, **bwm_ptr;
2013
2014 if (!(V_mrt_api_config & MRT_MFC_BW_UPCALL))
2015 return EOPNOTSUPP;
2016
2017 MRW_WLOCK();
2018
2019 /* Find the corresponding MFC entry */
2020 mfc = mfc_find(&req->bu_src, &req->bu_dst);
2021 if (mfc == NULL) {
2022 MRW_WUNLOCK();
2023 return EADDRNOTAVAIL;
2024 } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2025 /*
2026 * Delete all bw_meter entries for this mfc
2027 */
2028 struct bw_meter *list;
2029
2030 /* Free LEQ list */
2031 list = mfc->mfc_bw_meter_leq;
2032 mfc->mfc_bw_meter_leq = NULL;
2033 free_bw_list(list);
2034
2035 /* Free GEQ list */
2036 list = mfc->mfc_bw_meter_geq;
2037 mfc->mfc_bw_meter_geq = NULL;
2038 free_bw_list(list);
2039 MRW_WUNLOCK();
2040 return 0;
2041 } else { /* Delete a single bw_meter entry */
2042 struct bw_meter *prev;
2043 uint32_t flags = 0;
2044
2045 flags = compute_bw_meter_flags(req);
2046
2047 /* Choose an appropriate bw_meter list */
2048 if (req->bu_flags & BW_UPCALL_GEQ)
2049 bwm_ptr = &mfc->mfc_bw_meter_geq;
2050 else
2051 bwm_ptr = &mfc->mfc_bw_meter_leq;
2052
2053 /* Find the bw_meter entry to delete */
2054 for (prev = NULL, x = *bwm_ptr; x != NULL;
2055 prev = x, x = x->bm_mfc_next) {
2056 if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2057 &req->bu_threshold.b_time, ==)) &&
2058 (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2059 (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2060 (x->bm_flags & BW_METER_USER_FLAGS) == flags)
2061 break;
2062 }
2063 if (x != NULL) { /* Delete entry from the list for this MFC */
2064 if (prev != NULL)
2065 prev->bm_mfc_next = x->bm_mfc_next; /* remove from middle*/
2066 else
2067 *bwm_ptr = x->bm_mfc_next;/* new head of list */
2068
2069 if (req->bu_flags & BW_UPCALL_LEQ)
2070 callout_stop(&x->bm_meter_callout);
2071
2072 MRW_WUNLOCK();
2073 /* Free the bw_meter entry */
2074 free(x, M_BWMETER);
2075 return 0;
2076 } else {
2077 MRW_WUNLOCK();
2078 return EINVAL;
2079 }
2080 }
2081 /* NOTREACHED */
2082 }
2083
2084 /*
2085 * Perform bandwidth measurement processing that may result in an upcall
2086 */
2087 static void
2088 bw_meter_geq_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2089 {
2090 struct timeval delta;
2091
2092 MRW_LOCK_ASSERT();
2093
2094 delta = *nowp;
2095 BW_TIMEVALDECR(&delta, &x->bm_start_time);
2096
2097 /*
2098 * Processing for ">=" type of bw_meter entry.
2099 * bm_spin does not have to be hold here as in GEQ
2100 * case this is the only context accessing bm_measured.
2101 */
2102 if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2103 /* Reset the bw_meter entry */
2104 x->bm_start_time = *nowp;
2105 x->bm_measured.b_packets = 0;
2106 x->bm_measured.b_bytes = 0;
2107 x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2108 }
2109
2110 /* Record that a packet is received */
2111 x->bm_measured.b_packets++;
2112 x->bm_measured.b_bytes += plen;
2113
2114 /*
2115 * Test if we should deliver an upcall
2116 */
2117 if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2118 if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2119 (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2120 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2121 (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2122 /* Prepare an upcall for delivery */
2123 bw_meter_prepare_upcall(x, nowp);
2124 x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2125 }
2126 }
2127 }
2128
2129 /*
2130 * Prepare a bandwidth-related upcall
2131 */
2132 static void
2133 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2134 {
2135 struct timeval delta;
2136 struct bw_upcall *u;
2137
2138 MRW_LOCK_ASSERT();
2139
2140 /*
2141 * Compute the measured time interval
2142 */
2143 delta = *nowp;
2144 BW_TIMEVALDECR(&delta, &x->bm_start_time);
2145
2146 /*
2147 * Set the bw_upcall entry
2148 */
2149 u = malloc(sizeof(struct bw_upcall), M_MRTABLE, M_NOWAIT | M_ZERO);
2150 if (!u) {
2151 log(LOG_WARNING, "bw_meter_prepare_upcall: cannot allocate entry\n");
2152 return;
2153 }
2154 u->bu_src = x->bm_mfc->mfc_origin;
2155 u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2156 u->bu_threshold.b_time = x->bm_threshold.b_time;
2157 u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2158 u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2159 u->bu_measured.b_time = delta;
2160 u->bu_measured.b_packets = x->bm_measured.b_packets;
2161 u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2162 u->bu_flags = 0;
2163 if (x->bm_flags & BW_METER_UNIT_PACKETS)
2164 u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2165 if (x->bm_flags & BW_METER_UNIT_BYTES)
2166 u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2167 if (x->bm_flags & BW_METER_GEQ)
2168 u->bu_flags |= BW_UPCALL_GEQ;
2169 if (x->bm_flags & BW_METER_LEQ)
2170 u->bu_flags |= BW_UPCALL_LEQ;
2171
2172 if (buf_ring_enqueue(V_bw_upcalls_ring, u))
2173 log(LOG_WARNING, "bw_meter_prepare_upcall: cannot enqueue upcall\n");
2174 if (buf_ring_count(V_bw_upcalls_ring) > (BW_UPCALLS_MAX / 2)) {
2175 taskqueue_enqueue(V_task_queue, &V_task);
2176 }
2177 }
2178 /*
2179 * Send the pending bandwidth-related upcalls
2180 */
2181 static void
2182 bw_upcalls_send(void)
2183 {
2184 struct mbuf *m;
2185 int len = 0;
2186 struct bw_upcall *bu;
2187 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2188 static struct igmpmsg igmpmsg = { 0, /* unused1 */
2189 0, /* unused2 */
2190 IGMPMSG_BW_UPCALL,/* im_msgtype */
2191 0, /* im_mbz */
2192 0, /* im_vif */
2193 0, /* unused3 */
2194 { 0 }, /* im_src */
2195 { 0 } }; /* im_dst */
2196
2197 MRW_LOCK_ASSERT();
2198
2199 if (buf_ring_empty(V_bw_upcalls_ring))
2200 return;
2201
2202 /*
2203 * Allocate a new mbuf, initialize it with the header and
2204 * the payload for the pending calls.
2205 */
2206 m = m_gethdr(M_NOWAIT, MT_DATA);
2207 if (m == NULL) {
2208 log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2209 return;
2210 }
2211
2212 m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2213 len += sizeof(struct igmpmsg);
2214 while ((bu = buf_ring_dequeue_mc(V_bw_upcalls_ring)) != NULL) {
2215 m_copyback(m, len, sizeof(struct bw_upcall), (caddr_t)bu);
2216 len += sizeof(struct bw_upcall);
2217 free(bu, M_MRTABLE);
2218 }
2219
2220 /*
2221 * Send the upcalls
2222 * XXX do we need to set the address in k_igmpsrc ?
2223 */
2224 MRTSTAT_INC(mrts_upcalls);
2225 if (socket_send(V_ip_mrouter, m, &k_igmpsrc) < 0) {
2226 log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2227 MRTSTAT_INC(mrts_upq_sockfull);
2228 }
2229 }
2230
2231 /*
2232 * A periodic function for sending all upcalls that are pending delivery
2233 */
2234 static void
2235 expire_bw_upcalls_send(void *arg)
2236 {
2237 CURVNET_SET((struct vnet *) arg);
2238
2239 /* This callout is run with MRW_RLOCK taken */
2240
2241 bw_upcalls_send();
2242
2243 callout_reset(&V_bw_upcalls_ch, BW_UPCALLS_PERIOD, expire_bw_upcalls_send,
2244 curvnet);
2245 CURVNET_RESTORE();
2246 }
2247
2248 /*
2249 * End of bandwidth monitoring code
2250 */
2251
2252 /*
2253 * Send the packet up to the user daemon, or eventually do kernel encapsulation
2254 *
2255 */
2256 static int
2257 pim_register_send(struct ip *ip, struct vif *vifp, struct mbuf *m,
2258 struct mfc *rt)
2259 {
2260 struct mbuf *mb_copy, *mm;
2261
2262 /*
2263 * Do not send IGMP_WHOLEPKT notifications to userland, if the
2264 * rendezvous point was unspecified, and we were told not to.
2265 */
2266 if (pim_squelch_wholepkt != 0 && (V_mrt_api_config & MRT_MFC_RP) &&
2267 in_nullhost(rt->mfc_rp))
2268 return 0;
2269
2270 mb_copy = pim_register_prepare(ip, m);
2271 if (mb_copy == NULL)
2272 return ENOBUFS;
2273
2274 /*
2275 * Send all the fragments. Note that the mbuf for each fragment
2276 * is freed by the sending machinery.
2277 */
2278 for (mm = mb_copy; mm; mm = mb_copy) {
2279 mb_copy = mm->m_nextpkt;
2280 mm->m_nextpkt = 0;
2281 mm = m_pullup(mm, sizeof(struct ip));
2282 if (mm != NULL) {
2283 ip = mtod(mm, struct ip *);
2284 if ((V_mrt_api_config & MRT_MFC_RP) && !in_nullhost(rt->mfc_rp)) {
2285 pim_register_send_rp(ip, vifp, mm, rt);
2286 } else {
2287 pim_register_send_upcall(ip, vifp, mm, rt);
2288 }
2289 }
2290 }
2291
2292 return 0;
2293 }
2294
2295 /*
2296 * Return a copy of the data packet that is ready for PIM Register
2297 * encapsulation.
2298 * XXX: Note that in the returned copy the IP header is a valid one.
2299 */
2300 static struct mbuf *
2301 pim_register_prepare(struct ip *ip, struct mbuf *m)
2302 {
2303 struct mbuf *mb_copy = NULL;
2304 int mtu;
2305
2306 /* Take care of delayed checksums */
2307 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2308 in_delayed_cksum(m);
2309 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2310 }
2311
2312 /*
2313 * Copy the old packet & pullup its IP header into the
2314 * new mbuf so we can modify it.
2315 */
2316 mb_copy = m_copypacket(m, M_NOWAIT);
2317 if (mb_copy == NULL)
2318 return NULL;
2319 mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2320 if (mb_copy == NULL)
2321 return NULL;
2322
2323 /* take care of the TTL */
2324 ip = mtod(mb_copy, struct ip *);
2325 --ip->ip_ttl;
2326
2327 /* Compute the MTU after the PIM Register encapsulation */
2328 mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2329
2330 if (ntohs(ip->ip_len) <= mtu) {
2331 /* Turn the IP header into a valid one */
2332 ip->ip_sum = 0;
2333 ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2334 } else {
2335 /* Fragment the packet */
2336 mb_copy->m_pkthdr.csum_flags |= CSUM_IP;
2337 if (ip_fragment(ip, &mb_copy, mtu, 0) != 0) {
2338 m_freem(mb_copy);
2339 return NULL;
2340 }
2341 }
2342 return mb_copy;
2343 }
2344
2345 /*
2346 * Send an upcall with the data packet to the user-level process.
2347 */
2348 static int
2349 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2350 struct mbuf *mb_copy, struct mfc *rt)
2351 {
2352 struct mbuf *mb_first;
2353 int len = ntohs(ip->ip_len);
2354 struct igmpmsg *im;
2355 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2356
2357 MRW_LOCK_ASSERT();
2358
2359 /*
2360 * Add a new mbuf with an upcall header
2361 */
2362 mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2363 if (mb_first == NULL) {
2364 m_freem(mb_copy);
2365 return ENOBUFS;
2366 }
2367 mb_first->m_data += max_linkhdr;
2368 mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2369 mb_first->m_len = sizeof(struct igmpmsg);
2370 mb_first->m_next = mb_copy;
2371
2372 /* Send message to routing daemon */
2373 im = mtod(mb_first, struct igmpmsg *);
2374 im->im_msgtype = IGMPMSG_WHOLEPKT;
2375 im->im_mbz = 0;
2376 im->im_vif = vifp - V_viftable;
2377 im->im_src = ip->ip_src;
2378 im->im_dst = ip->ip_dst;
2379
2380 k_igmpsrc.sin_addr = ip->ip_src;
2381
2382 MRTSTAT_INC(mrts_upcalls);
2383
2384 if (socket_send(V_ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2385 CTR1(KTR_IPMF, "%s: socket queue full", __func__);
2386 MRTSTAT_INC(mrts_upq_sockfull);
2387 return ENOBUFS;
2388 }
2389
2390 /* Keep statistics */
2391 PIMSTAT_INC(pims_snd_registers_msgs);
2392 PIMSTAT_ADD(pims_snd_registers_bytes, len);
2393
2394 return 0;
2395 }
2396
2397 /*
2398 * Encapsulate the data packet in PIM Register message and send it to the RP.
2399 */
2400 static int
2401 pim_register_send_rp(struct ip *ip, struct vif *vifp, struct mbuf *mb_copy,
2402 struct mfc *rt)
2403 {
2404 struct mbuf *mb_first;
2405 struct ip *ip_outer;
2406 struct pim_encap_pimhdr *pimhdr;
2407 int len = ntohs(ip->ip_len);
2408 vifi_t vifi = rt->mfc_parent;
2409
2410 MRW_LOCK_ASSERT();
2411
2412 if ((vifi >= V_numvifs) || in_nullhost(V_viftable[vifi].v_lcl_addr)) {
2413 m_freem(mb_copy);
2414 return EADDRNOTAVAIL; /* The iif vif is invalid */
2415 }
2416
2417 /*
2418 * Add a new mbuf with the encapsulating header
2419 */
2420 mb_first = m_gethdr(M_NOWAIT, MT_DATA);
2421 if (mb_first == NULL) {
2422 m_freem(mb_copy);
2423 return ENOBUFS;
2424 }
2425 mb_first->m_data += max_linkhdr;
2426 mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2427 mb_first->m_next = mb_copy;
2428
2429 mb_first->m_pkthdr.len = len + mb_first->m_len;
2430
2431 /*
2432 * Fill in the encapsulating IP and PIM header
2433 */
2434 ip_outer = mtod(mb_first, struct ip *);
2435 *ip_outer = pim_encap_iphdr;
2436 ip_outer->ip_len = htons(len + sizeof(pim_encap_iphdr) +
2437 sizeof(pim_encap_pimhdr));
2438 ip_outer->ip_src = V_viftable[vifi].v_lcl_addr;
2439 ip_outer->ip_dst = rt->mfc_rp;
2440 /*
2441 * Copy the inner header TOS to the outer header, and take care of the
2442 * IP_DF bit.
2443 */
2444 ip_outer->ip_tos = ip->ip_tos;
2445 if (ip->ip_off & htons(IP_DF))
2446 ip_outer->ip_off |= htons(IP_DF);
2447 ip_fillid(ip_outer);
2448 pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2449 + sizeof(pim_encap_iphdr));
2450 *pimhdr = pim_encap_pimhdr;
2451 /* If the iif crosses a border, set the Border-bit */
2452 if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & V_mrt_api_config)
2453 pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
2454
2455 mb_first->m_data += sizeof(pim_encap_iphdr);
2456 pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
2457 mb_first->m_data -= sizeof(pim_encap_iphdr);
2458
2459 send_packet(vifp, mb_first);
2460
2461 /* Keep statistics */
2462 PIMSTAT_INC(pims_snd_registers_msgs);
2463 PIMSTAT_ADD(pims_snd_registers_bytes, len);
2464
2465 return 0;
2466 }
2467
2468 /*
2469 * pim_encapcheck() is called by the encap4_input() path at runtime to
2470 * determine if a packet is for PIM; allowing PIM to be dynamically loaded
2471 * into the kernel.
2472 */
2473 static int
2474 pim_encapcheck(const struct mbuf *m __unused, int off __unused,
2475 int proto __unused, void *arg __unused)
2476 {
2477
2478 KASSERT(proto == IPPROTO_PIM, ("not for IPPROTO_PIM"));
2479 return (8); /* claim the datagram. */
2480 }
2481
2482 /*
2483 * PIM-SMv2 and PIM-DM messages processing.
2484 * Receives and verifies the PIM control messages, and passes them
2485 * up to the listening socket, using rip_input().
2486 * The only message with special processing is the PIM_REGISTER message
2487 * (used by PIM-SM): the PIM header is stripped off, and the inner packet
2488 * is passed to if_simloop().
2489 */
2490 static int
2491 pim_input(struct mbuf *m, int off, int proto, void *arg __unused)
2492 {
2493 struct ip *ip = mtod(m, struct ip *);
2494 struct pim *pim;
2495 int iphlen = off;
2496 int minlen;
2497 int datalen = ntohs(ip->ip_len) - iphlen;
2498 int ip_tos;
2499
2500 /* Keep statistics */
2501 PIMSTAT_INC(pims_rcv_total_msgs);
2502 PIMSTAT_ADD(pims_rcv_total_bytes, datalen);
2503
2504 /*
2505 * Validate lengths
2506 */
2507 if (datalen < PIM_MINLEN) {
2508 PIMSTAT_INC(pims_rcv_tooshort);
2509 CTR3(KTR_IPMF, "%s: short packet (%d) from 0x%08x",
2510 __func__, datalen, ntohl(ip->ip_src.s_addr));
2511 m_freem(m);
2512 return (IPPROTO_DONE);
2513 }
2514
2515 /*
2516 * If the packet is at least as big as a REGISTER, go agead
2517 * and grab the PIM REGISTER header size, to avoid another
2518 * possible m_pullup() later.
2519 *
2520 * PIM_MINLEN == pimhdr + u_int32_t == 4 + 4 = 8
2521 * PIM_REG_MINLEN == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
2522 */
2523 minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
2524 /*
2525 * Get the IP and PIM headers in contiguous memory, and
2526 * possibly the PIM REGISTER header.
2527 */
2528 if (m->m_len < minlen && (m = m_pullup(m, minlen)) == NULL) {
2529 CTR1(KTR_IPMF, "%s: m_pullup() failed", __func__);
2530 return (IPPROTO_DONE);
2531 }
2532
2533 /* m_pullup() may have given us a new mbuf so reset ip. */
2534 ip = mtod(m, struct ip *);
2535 ip_tos = ip->ip_tos;
2536
2537 /* adjust mbuf to point to the PIM header */
2538 m->m_data += iphlen;
2539 m->m_len -= iphlen;
2540 pim = mtod(m, struct pim *);
2541
2542 /*
2543 * Validate checksum. If PIM REGISTER, exclude the data packet.
2544 *
2545 * XXX: some older PIMv2 implementations don't make this distinction,
2546 * so for compatibility reason perform the checksum over part of the
2547 * message, and if error, then over the whole message.
2548 */
2549 if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
2550 /* do nothing, checksum okay */
2551 } else if (in_cksum(m, datalen)) {
2552 PIMSTAT_INC(pims_rcv_badsum);
2553 CTR1(KTR_IPMF, "%s: invalid checksum", __func__);
2554 m_freem(m);
2555 return (IPPROTO_DONE);
2556 }
2557
2558 /* PIM version check */
2559 if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
2560 PIMSTAT_INC(pims_rcv_badversion);
2561 CTR3(KTR_IPMF, "%s: bad version %d expect %d", __func__,
2562 (int)PIM_VT_V(pim->pim_vt), PIM_VERSION);
2563 m_freem(m);
2564 return (IPPROTO_DONE);
2565 }
2566
2567 /* restore mbuf back to the outer IP */
2568 m->m_data -= iphlen;
2569 m->m_len += iphlen;
2570
2571 if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
2572 /*
2573 * Since this is a REGISTER, we'll make a copy of the register
2574 * headers ip + pim + u_int32 + encap_ip, to be passed up to the
2575 * routing daemon.
2576 */
2577 struct sockaddr_in dst = { sizeof(dst), AF_INET };
2578 struct mbuf *mcp;
2579 struct ip *encap_ip;
2580 u_int32_t *reghdr;
2581 struct ifnet *vifp;
2582
2583 MRW_RLOCK();
2584 if ((V_reg_vif_num >= V_numvifs) || (V_reg_vif_num == VIFI_INVALID)) {
2585 MRW_RUNLOCK();
2586 CTR2(KTR_IPMF, "%s: register vif not set: %d", __func__,
2587 (int)V_reg_vif_num);
2588 m_freem(m);
2589 return (IPPROTO_DONE);
2590 }
2591 /* XXX need refcnt? */
2592 vifp = V_viftable[V_reg_vif_num].v_ifp;
2593 MRW_RUNLOCK();
2594
2595 /*
2596 * Validate length
2597 */
2598 if (datalen < PIM_REG_MINLEN) {
2599 PIMSTAT_INC(pims_rcv_tooshort);
2600 PIMSTAT_INC(pims_rcv_badregisters);
2601 CTR1(KTR_IPMF, "%s: register packet size too small", __func__);
2602 m_freem(m);
2603 return (IPPROTO_DONE);
2604 }
2605
2606 reghdr = (u_int32_t *)(pim + 1);
2607 encap_ip = (struct ip *)(reghdr + 1);
2608
2609 CTR3(KTR_IPMF, "%s: register: encap ip src 0x%08x len %d",
2610 __func__, ntohl(encap_ip->ip_src.s_addr),
2611 ntohs(encap_ip->ip_len));
2612
2613 /* verify the version number of the inner packet */
2614 if (encap_ip->ip_v != IPVERSION) {
2615 PIMSTAT_INC(pims_rcv_badregisters);
2616 CTR1(KTR_IPMF, "%s: bad encap ip version", __func__);
2617 m_freem(m);
2618 return (IPPROTO_DONE);
2619 }
2620
2621 /* verify the inner packet is destined to a mcast group */
2622 if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
2623 PIMSTAT_INC(pims_rcv_badregisters);
2624 CTR2(KTR_IPMF, "%s: bad encap ip dest 0x%08x", __func__,
2625 ntohl(encap_ip->ip_dst.s_addr));
2626 m_freem(m);
2627 return (IPPROTO_DONE);
2628 }
2629
2630 /* If a NULL_REGISTER, pass it to the daemon */
2631 if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
2632 goto pim_input_to_daemon;
2633
2634 /*
2635 * Copy the TOS from the outer IP header to the inner IP header.
2636 */
2637 if (encap_ip->ip_tos != ip_tos) {
2638 /* Outer TOS -> inner TOS */
2639 encap_ip->ip_tos = ip_tos;
2640 /* Recompute the inner header checksum. Sigh... */
2641
2642 /* adjust mbuf to point to the inner IP header */
2643 m->m_data += (iphlen + PIM_MINLEN);
2644 m->m_len -= (iphlen + PIM_MINLEN);
2645
2646 encap_ip->ip_sum = 0;
2647 encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
2648
2649 /* restore mbuf to point back to the outer IP header */
2650 m->m_data -= (iphlen + PIM_MINLEN);
2651 m->m_len += (iphlen + PIM_MINLEN);
2652 }
2653
2654 /*
2655 * Decapsulate the inner IP packet and loopback to forward it
2656 * as a normal multicast packet. Also, make a copy of the
2657 * outer_iphdr + pimhdr + reghdr + encap_iphdr
2658 * to pass to the daemon later, so it can take the appropriate
2659 * actions (e.g., send back PIM_REGISTER_STOP).
2660 * XXX: here m->m_data points to the outer IP header.
2661 */
2662 mcp = m_copym(m, 0, iphlen + PIM_REG_MINLEN, M_NOWAIT);
2663 if (mcp == NULL) {
2664 CTR1(KTR_IPMF, "%s: m_copym() failed", __func__);
2665 m_freem(m);
2666 return (IPPROTO_DONE);
2667 }
2668
2669 /* Keep statistics */
2670 /* XXX: registers_bytes include only the encap. mcast pkt */
2671 PIMSTAT_INC(pims_rcv_registers_msgs);
2672 PIMSTAT_ADD(pims_rcv_registers_bytes, ntohs(encap_ip->ip_len));
2673
2674 /*
2675 * forward the inner ip packet; point m_data at the inner ip.
2676 */
2677 m_adj(m, iphlen + PIM_MINLEN);
2678
2679 CTR4(KTR_IPMF,
2680 "%s: forward decap'd REGISTER: src %lx dst %lx vif %d",
2681 __func__,
2682 (u_long)ntohl(encap_ip->ip_src.s_addr),
2683 (u_long)ntohl(encap_ip->ip_dst.s_addr),
2684 (int)V_reg_vif_num);
2685
2686 /* NB: vifp was collected above; can it change on us? */
2687 if_simloop(vifp, m, dst.sin_family, 0);
2688
2689 /* prepare the register head to send to the mrouting daemon */
2690 m = mcp;
2691 }
2692
2693 pim_input_to_daemon:
2694 /*
2695 * Pass the PIM message up to the daemon; if it is a Register message,
2696 * pass the 'head' only up to the daemon. This includes the
2697 * outer IP header, PIM header, PIM-Register header and the
2698 * inner IP header.
2699 * XXX: the outer IP header pkt size of a Register is not adjust to
2700 * reflect the fact that the inner multicast data is truncated.
2701 */
2702 return (rip_input(&m, &off, proto));
2703 }
2704
2705 static int
2706 sysctl_mfctable(SYSCTL_HANDLER_ARGS)
2707 {
2708 struct mfc *rt;
2709 int error, i;
2710
2711 if (req->newptr)
2712 return (EPERM);
2713 if (V_mfchashtbl == NULL) /* XXX unlocked */
2714 return (0);
2715 error = sysctl_wire_old_buffer(req, 0);
2716 if (error)
2717 return (error);
2718
2719 MRW_RLOCK();
2720 for (i = 0; i < mfchashsize; i++) {
2721 LIST_FOREACH(rt, &V_mfchashtbl[i], mfc_hash) {
2722 error = SYSCTL_OUT(req, rt, sizeof(struct mfc));
2723 if (error)
2724 goto out_locked;
2725 }
2726 }
2727 out_locked:
2728 MRW_RUNLOCK();
2729 return (error);
2730 }
2731
2732 static SYSCTL_NODE(_net_inet_ip, OID_AUTO, mfctable,
2733 CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_mfctable,
2734 "IPv4 Multicast Forwarding Table "
2735 "(struct *mfc[mfchashsize], netinet/ip_mroute.h)");
2736
2737 static int
2738 sysctl_viflist(SYSCTL_HANDLER_ARGS)
2739 {
2740 int error, i;
2741
2742 if (req->newptr)
2743 return (EPERM);
2744 if (V_viftable == NULL) /* XXX unlocked */
2745 return (0);
2746 error = sysctl_wire_old_buffer(req, MROUTE_VIF_SYSCTL_LEN * MAXVIFS);
2747 if (error)
2748 return (error);
2749
2750 MRW_RLOCK();
2751 /* Copy out user-visible portion of vif entry. */
2752 for (i = 0; i < MAXVIFS; i++) {
2753 error = SYSCTL_OUT(req, &V_viftable[i], MROUTE_VIF_SYSCTL_LEN);
2754 if (error)
2755 break;
2756 }
2757 MRW_RUNLOCK();
2758 return (error);
2759 }
2760
2761 SYSCTL_PROC(_net_inet_ip, OID_AUTO, viftable,
2762 CTLTYPE_OPAQUE | CTLFLAG_VNET | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2763 sysctl_viflist, "S,vif[MAXVIFS]",
2764 "IPv4 Multicast Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
2765
2766 static void
2767 vnet_mroute_init(const void *unused __unused)
2768 {
2769
2770 V_nexpire = malloc(mfchashsize, M_MRTABLE, M_WAITOK|M_ZERO);
2771
2772 V_viftable = mallocarray(MAXVIFS, sizeof(*V_viftable),
2773 M_MRTABLE, M_WAITOK|M_ZERO);
2774
2775 callout_init_rw(&V_expire_upcalls_ch, &mrouter_mtx, 0);
2776 callout_init_rw(&V_bw_upcalls_ch, &mrouter_mtx, 0);
2777
2778 /* Prepare taskqueue */
2779 V_task_queue = taskqueue_create_fast("ip_mroute_tskq", M_NOWAIT,
2780 taskqueue_thread_enqueue, &V_task_queue);
2781 taskqueue_start_threads(&V_task_queue, 1, PI_NET, "ip_mroute_tskq task");
2782 }
2783
2784 VNET_SYSINIT(vnet_mroute_init, SI_SUB_PROTO_MC, SI_ORDER_ANY, vnet_mroute_init,
2785 NULL);
2786
2787 static void
2788 vnet_mroute_uninit(const void *unused __unused)
2789 {
2790
2791 /* Taskqueue should be cancelled and drained before freeing */
2792 taskqueue_free(V_task_queue);
2793
2794 free(V_viftable, M_MRTABLE);
2795 free(V_nexpire, M_MRTABLE);
2796 V_nexpire = NULL;
2797 }
2798
2799 VNET_SYSUNINIT(vnet_mroute_uninit, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE,
2800 vnet_mroute_uninit, NULL);
2801
2802 static int
2803 ip_mroute_modevent(module_t mod, int type, void *unused)
2804 {
2805
2806 switch (type) {
2807 case MOD_LOAD:
2808 MRW_LOCK_INIT();
2809
2810 if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event,
2811 if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
2812 if (if_detach_event_tag == NULL) {
2813 printf("ip_mroute: unable to register "
2814 "ifnet_departure_event handler\n");
2815 MRW_LOCK_DESTROY();
2816 return (EINVAL);
2817 }
2818
2819 mfchashsize = MFCHASHSIZE;
2820 if (TUNABLE_ULONG_FETCH("net.inet.ip.mfchashsize", &mfchashsize) &&
2821 !powerof2(mfchashsize)) {
2822 printf("WARNING: %s not a power of 2; using default\n",
2823 "net.inet.ip.mfchashsize");
2824 mfchashsize = MFCHASHSIZE;
2825 }
2826
2827 pim_squelch_wholepkt = 0;
2828 TUNABLE_ULONG_FETCH("net.inet.pim.squelch_wholepkt",
2829 &pim_squelch_wholepkt);
2830
2831 pim_encap_cookie = ip_encap_attach(&ipv4_encap_cfg, NULL, M_WAITOK);
2832 if (pim_encap_cookie == NULL) {
2833 printf("ip_mroute: unable to attach pim encap\n");
2834 MRW_LOCK_DESTROY();
2835 return (EINVAL);
2836 }
2837
2838 ip_mcast_src = X_ip_mcast_src;
2839 ip_mforward = X_ip_mforward;
2840 ip_mrouter_done = X_ip_mrouter_done;
2841 ip_mrouter_get = X_ip_mrouter_get;
2842 ip_mrouter_set = X_ip_mrouter_set;
2843
2844 ip_rsvp_force_done = X_ip_rsvp_force_done;
2845 ip_rsvp_vif = X_ip_rsvp_vif;
2846
2847 legal_vif_num = X_legal_vif_num;
2848 mrt_ioctl = X_mrt_ioctl;
2849 rsvp_input_p = X_rsvp_input;
2850 break;
2851
2852 case MOD_UNLOAD:
2853 /*
2854 * Typically module unload happens after the user-level
2855 * process has shutdown the kernel services (the check
2856 * below insures someone can't just yank the module out
2857 * from under a running process). But if the module is
2858 * just loaded and then unloaded w/o starting up a user
2859 * process we still need to cleanup.
2860 */
2861 MRW_WLOCK();
2862 if (ip_mrouter_cnt != 0) {
2863 MRW_WUNLOCK();
2864 return (EINVAL);
2865 }
2866 ip_mrouter_unloading = 1;
2867 MRW_WUNLOCK();
2868
2869 EVENTHANDLER_DEREGISTER(ifnet_departure_event, if_detach_event_tag);
2870
2871 if (pim_encap_cookie) {
2872 ip_encap_detach(pim_encap_cookie);
2873 pim_encap_cookie = NULL;
2874 }
2875
2876 ip_mcast_src = NULL;
2877 ip_mforward = NULL;
2878 ip_mrouter_done = NULL;
2879 ip_mrouter_get = NULL;
2880 ip_mrouter_set = NULL;
2881
2882 ip_rsvp_force_done = NULL;
2883 ip_rsvp_vif = NULL;
2884
2885 legal_vif_num = NULL;
2886 mrt_ioctl = NULL;
2887 rsvp_input_p = NULL;
2888
2889 MRW_LOCK_DESTROY();
2890 break;
2891
2892 default:
2893 return EOPNOTSUPP;
2894 }
2895 return 0;
2896 }
2897
2898 static moduledata_t ip_mroutemod = {
2899 "ip_mroute",
2900 ip_mroute_modevent,
2901 0
2902 };
2903
2904 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PROTO_MC, SI_ORDER_MIDDLE);
Cache object: 8eb484c508a46110c7b87dc55b5c6e82
|