]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_mroute.c
This commit was generated by cvs2svn to compensate for changes in r163976,
[FreeBSD/FreeBSD.git] / sys / netinet / ip_mroute.c
1 /*-
2  * Copyright (c) 1989 Stephen Deering
3  * Copyright (c) 1992, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Stephen Deering of Stanford University.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)ip_mroute.c 8.2 (Berkeley) 11/15/93
34  */
35
36 /*
37  * IP multicast forwarding procedures
38  *
39  * Written by David Waitzman, BBN Labs, August 1988.
40  * Modified by Steve Deering, Stanford, February 1989.
41  * Modified by Mark J. Steiglitz, Stanford, May, 1991
42  * Modified by Van Jacobson, LBL, January 1993
43  * Modified by Ajit Thyagarajan, PARC, August 1993
44  * Modified by Bill Fenner, PARC, April 1995
45  * Modified by Ahmed Helmy, SGI, June 1996
46  * Modified by George Edmond Eddy (Rusty), ISI, February 1998
47  * Modified by Pavlin Radoslavov, USC/ISI, May 1998, August 1999, October 2000
48  * Modified by Hitoshi Asaeda, WIDE, August 2000
49  * Modified by Pavlin Radoslavov, ICSI, October 2002
50  *
51  * MROUTING Revision: 3.5
52  * and PIM-SMv2 and PIM-DM support, advanced API support,
53  * bandwidth metering and signaling
54  *
55  * $FreeBSD$
56  */
57
58 #include "opt_mac.h"
59 #include "opt_mrouting.h"
60
61 #ifdef PIM
62 #define _PIM_VT 1
63 #endif
64
65 #include <sys/param.h>
66 #include <sys/kernel.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mbuf.h>
70 #include <sys/module.h>
71 #include <sys/protosw.h>
72 #include <sys/signalvar.h>
73 #include <sys/socket.h>
74 #include <sys/socketvar.h>
75 #include <sys/sockio.h>
76 #include <sys/sx.h>
77 #include <sys/sysctl.h>
78 #include <sys/syslog.h>
79 #include <sys/systm.h>
80 #include <sys/time.h>
81 #include <net/if.h>
82 #include <net/netisr.h>
83 #include <net/route.h>
84 #include <netinet/in.h>
85 #include <netinet/igmp.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/in_var.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_encap.h>
90 #include <netinet/ip_mroute.h>
91 #include <netinet/ip_var.h>
92 #include <netinet/ip_options.h>
93 #ifdef PIM
94 #include <netinet/pim.h>
95 #include <netinet/pim_var.h>
96 #endif
97 #include <netinet/udp.h>
98 #include <machine/in_cksum.h>
99
100 #include <security/mac/mac_framework.h>
101
102 /*
103  * Control debugging code for rsvp and multicast routing code.
104  * Can only set them with the debugger.
105  */
106 static u_int    rsvpdebug;              /* non-zero enables debugging   */
107
108 static u_int    mrtdebug;               /* any set of the flags below   */
109 #define         DEBUG_MFC       0x02
110 #define         DEBUG_FORWARD   0x04
111 #define         DEBUG_EXPIRE    0x08
112 #define         DEBUG_XMIT      0x10
113 #define         DEBUG_PIM       0x20
114
115 #define         VIFI_INVALID    ((vifi_t) -1)
116
117 #define M_HASCL(m)      ((m)->m_flags & M_EXT)
118
119 static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast routing tables");
120
121 /*
122  * Locking.  We use two locks: one for the virtual interface table and
123  * one for the forwarding table.  These locks may be nested in which case
124  * the VIF lock must always be taken first.  Note that each lock is used
125  * to cover not only the specific data structure but also related data
126  * structures.  It may be better to add more fine-grained locking later;
127  * it's not clear how performance-critical this code is.
128  *
129  * XXX: This module could particularly benefit from being cleaned
130  *      up to use the <sys/queue.h> macros.
131  *
132  */
133
134 static struct mrtstat   mrtstat;
135 SYSCTL_STRUCT(_net_inet_ip, OID_AUTO, mrtstat, CTLFLAG_RW,
136     &mrtstat, mrtstat,
137     "Multicast Routing Statistics (struct mrtstat, netinet/ip_mroute.h)");
138
139 static struct mfc       *mfctable[MFCTBLSIZ];
140 SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, mfctable, CTLFLAG_RD,
141     &mfctable, sizeof(mfctable), "S,*mfc[MFCTBLSIZ]",
142     "Multicast Forwarding Table (struct *mfc[MFCTBLSIZ], netinet/ip_mroute.h)");
143
144 static struct mtx mfc_mtx;
145 #define MFC_LOCK()      mtx_lock(&mfc_mtx)
146 #define MFC_UNLOCK()    mtx_unlock(&mfc_mtx)
147 #define MFC_LOCK_ASSERT()       do {                                    \
148         mtx_assert(&mfc_mtx, MA_OWNED);                                 \
149         NET_ASSERT_GIANT();                                             \
150 } while (0)
151 #define MFC_LOCK_INIT() mtx_init(&mfc_mtx, "mroute mfc table", NULL, MTX_DEF)
152 #define MFC_LOCK_DESTROY()      mtx_destroy(&mfc_mtx)
153
154 static struct vif       viftable[MAXVIFS];
155 SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, viftable, CTLFLAG_RD,
156     &viftable, sizeof(viftable), "S,vif[MAXVIFS]",
157     "Multicast Virtual Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
158
159 static struct mtx vif_mtx;
160 #define VIF_LOCK()      mtx_lock(&vif_mtx)
161 #define VIF_UNLOCK()    mtx_unlock(&vif_mtx)
162 #define VIF_LOCK_ASSERT()       mtx_assert(&vif_mtx, MA_OWNED)
163 #define VIF_LOCK_INIT() mtx_init(&vif_mtx, "mroute vif table", NULL, MTX_DEF)
164 #define VIF_LOCK_DESTROY()      mtx_destroy(&vif_mtx)
165
166 static u_char           nexpire[MFCTBLSIZ];
167
168 static eventhandler_tag if_detach_event_tag = NULL;
169
170 static struct callout expire_upcalls_ch;
171
172 #define         EXPIRE_TIMEOUT  (hz / 4)        /* 4x / second          */
173 #define         UPCALL_EXPIRE   6               /* number of timeouts   */
174
175 /*
176  * Define the token bucket filter structures
177  * tbftable -> each vif has one of these for storing info
178  */
179
180 static struct tbf tbftable[MAXVIFS];
181 #define         TBF_REPROCESS   (hz / 100)      /* 100x / second */
182
183 /*
184  * 'Interfaces' associated with decapsulator (so we can tell
185  * packets that went through it from ones that get reflected
186  * by a broken gateway).  These interfaces are never linked into
187  * the system ifnet list & no routes point to them.  I.e., packets
188  * can't be sent this way.  They only exist as a placeholder for
189  * multicast source verification.
190  */
191 static struct ifnet multicast_decap_if[MAXVIFS];
192
193 #define ENCAP_TTL 64
194 #define ENCAP_PROTO IPPROTO_IPIP        /* 4 */
195
196 /* prototype IP hdr for encapsulated packets */
197 static struct ip multicast_encap_iphdr = {
198 #if BYTE_ORDER == LITTLE_ENDIAN
199         sizeof(struct ip) >> 2, IPVERSION,
200 #else
201         IPVERSION, sizeof(struct ip) >> 2,
202 #endif
203         0,                              /* tos */
204         sizeof(struct ip),              /* total length */
205         0,                              /* id */
206         0,                              /* frag offset */
207         ENCAP_TTL, ENCAP_PROTO,
208         0,                              /* checksum */
209 };
210
211 /*
212  * Bandwidth meter variables and constants
213  */
214 static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
215 /*
216  * Pending timeouts are stored in a hash table, the key being the
217  * expiration time. Periodically, the entries are analysed and processed.
218  */
219 #define BW_METER_BUCKETS        1024
220 static struct bw_meter *bw_meter_timers[BW_METER_BUCKETS];
221 static struct callout bw_meter_ch;
222 #define BW_METER_PERIOD (hz)            /* periodical handling of bw meters */
223
224 /*
225  * Pending upcalls are stored in a vector which is flushed when
226  * full, or periodically
227  */
228 static struct bw_upcall bw_upcalls[BW_UPCALLS_MAX];
229 static u_int    bw_upcalls_n; /* # of pending upcalls */
230 static struct callout bw_upcalls_ch;
231 #define BW_UPCALLS_PERIOD (hz)          /* periodical flush of bw upcalls */
232
233 #ifdef PIM
234 static struct pimstat pimstat;
235 SYSCTL_STRUCT(_net_inet_pim, PIMCTL_STATS, stats, CTLFLAG_RD,
236     &pimstat, pimstat,
237     "PIM Statistics (struct pimstat, netinet/pim_var.h)");
238
239 /*
240  * Note: the PIM Register encapsulation adds the following in front of a
241  * data packet:
242  *
243  * struct pim_encap_hdr {
244  *    struct ip ip;
245  *    struct pim_encap_pimhdr  pim;
246  * }
247  *
248  */
249
250 struct pim_encap_pimhdr {
251         struct pim pim;
252         uint32_t   flags;
253 };
254
255 static struct ip pim_encap_iphdr = {
256 #if BYTE_ORDER == LITTLE_ENDIAN
257         sizeof(struct ip) >> 2,
258         IPVERSION,
259 #else
260         IPVERSION,
261         sizeof(struct ip) >> 2,
262 #endif
263         0,                      /* tos */
264         sizeof(struct ip),      /* total length */
265         0,                      /* id */
266         0,                      /* frag offset */
267         ENCAP_TTL,
268         IPPROTO_PIM,
269         0,                      /* checksum */
270 };
271
272 static struct pim_encap_pimhdr pim_encap_pimhdr = {
273     {
274         PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
275         0,                      /* reserved */
276         0,                      /* checksum */
277     },
278     0                           /* flags */
279 };
280
281 static struct ifnet multicast_register_if;
282 static vifi_t reg_vif_num = VIFI_INVALID;
283 #endif /* PIM */
284
285 /*
286  * Private variables.
287  */
288 static vifi_t      numvifs;
289 static const struct encaptab *encap_cookie;
290
291 /*
292  * one-back cache used by mroute_encapcheck to locate a tunnel's vif
293  * given a datagram's src ip address.
294  */
295 static u_long last_encap_src;
296 static struct vif *last_encap_vif;
297
298 /*
299  * Callout for queue processing.
300  */
301 static struct callout tbf_reprocess_ch;
302
303 static u_long   X_ip_mcast_src(int vifi);
304 static int      X_ip_mforward(struct ip *ip, struct ifnet *ifp,
305                         struct mbuf *m, struct ip_moptions *imo);
306 static int      X_ip_mrouter_done(void);
307 static int      X_ip_mrouter_get(struct socket *so, struct sockopt *m);
308 static int      X_ip_mrouter_set(struct socket *so, struct sockopt *m);
309 static int      X_legal_vif_num(int vif);
310 static int      X_mrt_ioctl(int cmd, caddr_t data);
311
312 static int get_sg_cnt(struct sioc_sg_req *);
313 static int get_vif_cnt(struct sioc_vif_req *);
314 static void if_detached_event(void *arg __unused, struct ifnet *);
315 static int ip_mrouter_init(struct socket *, int);
316 static int add_vif(struct vifctl *);
317 static int del_vif_locked(vifi_t);
318 static int del_vif(vifi_t);
319 static int add_mfc(struct mfcctl2 *);
320 static int del_mfc(struct mfcctl2 *);
321 static int set_api_config(uint32_t *); /* chose API capabilities */
322 static int socket_send(struct socket *, struct mbuf *, struct sockaddr_in *);
323 static int set_assert(int);
324 static void expire_upcalls(void *);
325 static int ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
326 static void phyint_send(struct ip *, struct vif *, struct mbuf *);
327 static void encap_send(struct ip *, struct vif *, struct mbuf *);
328 static void tbf_control(struct vif *, struct mbuf *, struct ip *, u_long);
329 static void tbf_queue(struct vif *, struct mbuf *);
330 static void tbf_process_q(struct vif *);
331 static void tbf_reprocess_q(void *);
332 static int tbf_dq_sel(struct vif *, struct ip *);
333 static void tbf_send_packet(struct vif *, struct mbuf *);
334 static void tbf_update_tokens(struct vif *);
335 static int priority(struct vif *, struct ip *);
336
337 /*
338  * Bandwidth monitoring
339  */
340 static void free_bw_list(struct bw_meter *list);
341 static int add_bw_upcall(struct bw_upcall *);
342 static int del_bw_upcall(struct bw_upcall *);
343 static void bw_meter_receive_packet(struct bw_meter *x, int plen,
344                 struct timeval *nowp);
345 static void bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp);
346 static void bw_upcalls_send(void);
347 static void schedule_bw_meter(struct bw_meter *x, struct timeval *nowp);
348 static void unschedule_bw_meter(struct bw_meter *x);
349 static void bw_meter_process(void);
350 static void expire_bw_upcalls_send(void *);
351 static void expire_bw_meter_process(void *);
352
353 #ifdef PIM
354 static int pim_register_send(struct ip *, struct vif *,
355                 struct mbuf *, struct mfc *);
356 static int pim_register_send_rp(struct ip *, struct vif *,
357                 struct mbuf *, struct mfc *);
358 static int pim_register_send_upcall(struct ip *, struct vif *,
359                 struct mbuf *, struct mfc *);
360 static struct mbuf *pim_register_prepare(struct ip *, struct mbuf *);
361 #endif
362
363 /*
364  * whether or not special PIM assert processing is enabled.
365  */
366 static int pim_assert;
367 /*
368  * Rate limit for assert notification messages, in usec
369  */
370 #define ASSERT_MSG_TIME         3000000
371
372 /*
373  * Kernel multicast routing API capabilities and setup.
374  * If more API capabilities are added to the kernel, they should be
375  * recorded in `mrt_api_support'.
376  */
377 static const uint32_t mrt_api_support = (MRT_MFC_FLAGS_DISABLE_WRONGVIF |
378                                          MRT_MFC_FLAGS_BORDER_VIF |
379                                          MRT_MFC_RP |
380                                          MRT_MFC_BW_UPCALL);
381 static uint32_t mrt_api_config = 0;
382
383 /*
384  * Hash function for a source, group entry
385  */
386 #define MFCHASH(a, g) MFCHASHMOD(((a) >> 20) ^ ((a) >> 10) ^ (a) ^ \
387                         ((g) >> 20) ^ ((g) >> 10) ^ (g))
388
389 /*
390  * Find a route for a given origin IP address and Multicast group address
391  * Type of service parameter to be added in the future!!!
392  * Statistics are updated by the caller if needed
393  * (mrtstat.mrts_mfc_lookups and mrtstat.mrts_mfc_misses)
394  */
395 static struct mfc *
396 mfc_find(in_addr_t o, in_addr_t g)
397 {
398     struct mfc *rt;
399
400     MFC_LOCK_ASSERT();
401
402     for (rt = mfctable[MFCHASH(o,g)]; rt; rt = rt->mfc_next)
403         if ((rt->mfc_origin.s_addr == o) &&
404                 (rt->mfc_mcastgrp.s_addr == g) && (rt->mfc_stall == NULL))
405             break;
406     return rt;
407 }
408
409 /*
410  * Macros to compute elapsed time efficiently
411  * Borrowed from Van Jacobson's scheduling code
412  */
413 #define TV_DELTA(a, b, delta) {                                 \
414         int xxs;                                                \
415         delta = (a).tv_usec - (b).tv_usec;                      \
416         if ((xxs = (a).tv_sec - (b).tv_sec)) {                  \
417                 switch (xxs) {                                  \
418                 case 2:                                         \
419                       delta += 1000000;                         \
420                       /* FALLTHROUGH */                         \
421                 case 1:                                         \
422                       delta += 1000000;                         \
423                       break;                                    \
424                 default:                                        \
425                       delta += (1000000 * xxs);                 \
426                 }                                               \
427         }                                                       \
428 }
429
430 #define TV_LT(a, b) (((a).tv_usec < (b).tv_usec && \
431               (a).tv_sec <= (b).tv_sec) || (a).tv_sec < (b).tv_sec)
432
433 /*
434  * Handle MRT setsockopt commands to modify the multicast routing tables.
435  */
436 static int
437 X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
438 {
439     int error, optval;
440     vifi_t      vifi;
441     struct      vifctl vifc;
442     struct      mfcctl2 mfc;
443     struct      bw_upcall bw_upcall;
444     uint32_t    i;
445
446     if (so != ip_mrouter && sopt->sopt_name != MRT_INIT)
447         return EPERM;
448
449     error = 0;
450     switch (sopt->sopt_name) {
451     case MRT_INIT:
452         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
453         if (error)
454             break;
455         error = ip_mrouter_init(so, optval);
456         break;
457
458     case MRT_DONE:
459         error = ip_mrouter_done();
460         break;
461
462     case MRT_ADD_VIF:
463         error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
464         if (error)
465             break;
466         error = add_vif(&vifc);
467         break;
468
469     case MRT_DEL_VIF:
470         error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
471         if (error)
472             break;
473         error = del_vif(vifi);
474         break;
475
476     case MRT_ADD_MFC:
477     case MRT_DEL_MFC:
478         /*
479          * select data size depending on API version.
480          */
481         if (sopt->sopt_name == MRT_ADD_MFC &&
482                 mrt_api_config & MRT_API_FLAGS_ALL) {
483             error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl2),
484                                 sizeof(struct mfcctl2));
485         } else {
486             error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl),
487                                 sizeof(struct mfcctl));
488             bzero((caddr_t)&mfc + sizeof(struct mfcctl),
489                         sizeof(mfc) - sizeof(struct mfcctl));
490         }
491         if (error)
492             break;
493         if (sopt->sopt_name == MRT_ADD_MFC)
494             error = add_mfc(&mfc);
495         else
496             error = del_mfc(&mfc);
497         break;
498
499     case MRT_ASSERT:
500         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
501         if (error)
502             break;
503         set_assert(optval);
504         break;
505
506     case MRT_API_CONFIG:
507         error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
508         if (!error)
509             error = set_api_config(&i);
510         if (!error)
511             error = sooptcopyout(sopt, &i, sizeof i);
512         break;
513
514     case MRT_ADD_BW_UPCALL:
515     case MRT_DEL_BW_UPCALL:
516         error = sooptcopyin(sopt, &bw_upcall, sizeof bw_upcall,
517                                 sizeof bw_upcall);
518         if (error)
519             break;
520         if (sopt->sopt_name == MRT_ADD_BW_UPCALL)
521             error = add_bw_upcall(&bw_upcall);
522         else
523             error = del_bw_upcall(&bw_upcall);
524         break;
525
526     default:
527         error = EOPNOTSUPP;
528         break;
529     }
530     return error;
531 }
532
533 /*
534  * Handle MRT getsockopt commands
535  */
536 static int
537 X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
538 {
539     int error;
540     static int version = 0x0305; /* !!! why is this here? XXX */
541
542     switch (sopt->sopt_name) {
543     case MRT_VERSION:
544         error = sooptcopyout(sopt, &version, sizeof version);
545         break;
546
547     case MRT_ASSERT:
548         error = sooptcopyout(sopt, &pim_assert, sizeof pim_assert);
549         break;
550
551     case MRT_API_SUPPORT:
552         error = sooptcopyout(sopt, &mrt_api_support, sizeof mrt_api_support);
553         break;
554
555     case MRT_API_CONFIG:
556         error = sooptcopyout(sopt, &mrt_api_config, sizeof mrt_api_config);
557         break;
558
559     default:
560         error = EOPNOTSUPP;
561         break;
562     }
563     return error;
564 }
565
566 /*
567  * Handle ioctl commands to obtain information from the cache
568  */
569 static int
570 X_mrt_ioctl(int cmd, caddr_t data)
571 {
572     int error = 0;
573
574     /*
575      * Currently the only function calling this ioctl routine is rtioctl().
576      * Typically, only root can create the raw socket in order to execute
577      * this ioctl method, however the request might be coming from a prison
578      */
579     error = suser(curthread);
580     if (error)
581         return (error);
582     switch (cmd) {
583     case (SIOCGETVIFCNT):
584         error = get_vif_cnt((struct sioc_vif_req *)data);
585         break;
586
587     case (SIOCGETSGCNT):
588         error = get_sg_cnt((struct sioc_sg_req *)data);
589         break;
590
591     default:
592         error = EINVAL;
593         break;
594     }
595     return error;
596 }
597
598 /*
599  * returns the packet, byte, rpf-failure count for the source group provided
600  */
601 static int
602 get_sg_cnt(struct sioc_sg_req *req)
603 {
604     struct mfc *rt;
605
606     MFC_LOCK();
607     rt = mfc_find(req->src.s_addr, req->grp.s_addr);
608     if (rt == NULL) {
609         MFC_UNLOCK();
610         req->pktcnt = req->bytecnt = req->wrong_if = 0xffffffff;
611         return EADDRNOTAVAIL;
612     }
613     req->pktcnt = rt->mfc_pkt_cnt;
614     req->bytecnt = rt->mfc_byte_cnt;
615     req->wrong_if = rt->mfc_wrong_if;
616     MFC_UNLOCK();
617     return 0;
618 }
619
620 /*
621  * returns the input and output packet and byte counts on the vif provided
622  */
623 static int
624 get_vif_cnt(struct sioc_vif_req *req)
625 {
626     vifi_t vifi = req->vifi;
627
628     VIF_LOCK();
629     if (vifi >= numvifs) {
630         VIF_UNLOCK();
631         return EINVAL;
632     }
633
634     req->icount = viftable[vifi].v_pkt_in;
635     req->ocount = viftable[vifi].v_pkt_out;
636     req->ibytes = viftable[vifi].v_bytes_in;
637     req->obytes = viftable[vifi].v_bytes_out;
638     VIF_UNLOCK();
639
640     return 0;
641 }
642
643 static void
644 ip_mrouter_reset(void)
645 {
646     bzero((caddr_t)mfctable, sizeof(mfctable));
647     bzero((caddr_t)nexpire, sizeof(nexpire));
648
649     pim_assert = 0;
650     mrt_api_config = 0;
651
652     callout_init(&expire_upcalls_ch, NET_CALLOUT_MPSAFE);
653
654     bw_upcalls_n = 0;
655     bzero((caddr_t)bw_meter_timers, sizeof(bw_meter_timers));
656     callout_init(&bw_upcalls_ch, NET_CALLOUT_MPSAFE);
657     callout_init(&bw_meter_ch, NET_CALLOUT_MPSAFE);
658
659     callout_init(&tbf_reprocess_ch, NET_CALLOUT_MPSAFE);
660 }
661
662 static struct mtx mrouter_mtx;          /* used to synch init/done work */
663
664 static void
665 if_detached_event(void *arg __unused, struct ifnet *ifp)
666 {
667     vifi_t vifi;
668     int i;
669     struct mfc *mfc;
670     struct mfc *nmfc;
671     struct mfc **ppmfc; /* Pointer to previous node's next-pointer */
672     struct rtdetq *pq;
673     struct rtdetq *npq;
674
675     mtx_lock(&mrouter_mtx);
676     if (ip_mrouter == NULL) {
677         mtx_unlock(&mrouter_mtx);
678     }
679
680     /*
681      * Tear down multicast forwarder state associated with this ifnet.
682      * 1. Walk the vif list, matching vifs against this ifnet.
683      * 2. Walk the multicast forwarding cache (mfc) looking for
684      *    inner matches with this vif's index.
685      * 3. Free any pending mbufs for this mfc.
686      * 4. Free the associated mfc entry and state associated with this vif.
687      *    Be very careful about unlinking from a singly-linked list whose
688      *    "head node" is a pointer in a simple array.
689      * 5. Free vif state. This should disable ALLMULTI on the interface.
690      */
691     VIF_LOCK();
692     MFC_LOCK();
693     for (vifi = 0; vifi < numvifs; vifi++) {
694         if (viftable[vifi].v_ifp != ifp)
695                 continue;
696         for (i = 0; i < MFCTBLSIZ; i++) {
697             ppmfc = &mfctable[i];
698             for (mfc = mfctable[i]; mfc != NULL; ) {
699                 nmfc = mfc->mfc_next;
700                 if (mfc->mfc_parent == vifi) {
701                     for (pq = mfc->mfc_stall; pq != NULL; ) {
702                         npq = pq->next;
703                         m_freem(pq->m);
704                         free(pq, M_MRTABLE);
705                         pq = npq;
706                     }
707                     free_bw_list(mfc->mfc_bw_meter);
708                     free(mfc, M_MRTABLE);
709                     *ppmfc = nmfc;
710                 } else {
711                     ppmfc = &mfc->mfc_next;
712                 }
713                 mfc = nmfc;
714             }
715         }
716         del_vif_locked(vifi);
717     }
718     MFC_UNLOCK();
719     VIF_UNLOCK();
720
721     mtx_unlock(&mrouter_mtx);
722 }
723                         
724 /*
725  * Enable multicast routing
726  */
727 static int
728 ip_mrouter_init(struct socket *so, int version)
729 {
730     if (mrtdebug)
731         log(LOG_DEBUG, "ip_mrouter_init: so_type = %d, pr_protocol = %d\n",
732             so->so_type, so->so_proto->pr_protocol);
733
734     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_IGMP)
735         return EOPNOTSUPP;
736
737     if (version != 1)
738         return ENOPROTOOPT;
739
740     mtx_lock(&mrouter_mtx);
741
742     if (ip_mrouter != NULL) {
743         mtx_unlock(&mrouter_mtx);
744         return EADDRINUSE;
745     }
746
747     if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event, 
748         if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
749     if (if_detach_event_tag == NULL)
750         return (ENOMEM);
751
752     callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
753
754     callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
755         expire_bw_upcalls_send, NULL);
756     callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
757
758     ip_mrouter = so;
759
760     mtx_unlock(&mrouter_mtx);
761
762     if (mrtdebug)
763         log(LOG_DEBUG, "ip_mrouter_init\n");
764
765     return 0;
766 }
767
768 /*
769  * Disable multicast routing
770  */
771 static int
772 X_ip_mrouter_done(void)
773 {
774     vifi_t vifi;
775     int i;
776     struct ifnet *ifp;
777     struct ifreq ifr;
778     struct mfc *rt;
779     struct rtdetq *rte;
780
781     mtx_lock(&mrouter_mtx);
782
783     if (ip_mrouter == NULL) {
784         mtx_unlock(&mrouter_mtx);
785         return EINVAL;
786     }
787
788     /*
789      * Detach/disable hooks to the reset of the system.
790      */
791     ip_mrouter = NULL;
792     mrt_api_config = 0;
793
794     VIF_LOCK();
795     if (encap_cookie) {
796         const struct encaptab *c = encap_cookie;
797         encap_cookie = NULL;
798         encap_detach(c);
799     }
800     VIF_UNLOCK();
801
802     callout_stop(&tbf_reprocess_ch);
803
804     VIF_LOCK();
805     /*
806      * For each phyint in use, disable promiscuous reception of all IP
807      * multicasts.
808      */
809     for (vifi = 0; vifi < numvifs; vifi++) {
810         if (viftable[vifi].v_lcl_addr.s_addr != 0 &&
811                 !(viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
812             struct sockaddr_in *so = (struct sockaddr_in *)&(ifr.ifr_addr);
813
814             so->sin_len = sizeof(struct sockaddr_in);
815             so->sin_family = AF_INET;
816             so->sin_addr.s_addr = INADDR_ANY;
817             ifp = viftable[vifi].v_ifp;
818             if_allmulti(ifp, 0);
819         }
820     }
821     bzero((caddr_t)tbftable, sizeof(tbftable));
822     bzero((caddr_t)viftable, sizeof(viftable));
823     numvifs = 0;
824     pim_assert = 0;
825     VIF_UNLOCK();
826     EVENTHANDLER_DEREGISTER(ifnet_departure_event, if_detach_event_tag);
827
828     /*
829      * Free all multicast forwarding cache entries.
830      */
831     callout_stop(&expire_upcalls_ch);
832     callout_stop(&bw_upcalls_ch);
833     callout_stop(&bw_meter_ch);
834
835     MFC_LOCK();
836     for (i = 0; i < MFCTBLSIZ; i++) {
837         for (rt = mfctable[i]; rt != NULL; ) {
838             struct mfc *nr = rt->mfc_next;
839
840             for (rte = rt->mfc_stall; rte != NULL; ) {
841                 struct rtdetq *n = rte->next;
842
843                 m_freem(rte->m);
844                 free(rte, M_MRTABLE);
845                 rte = n;
846             }
847             free_bw_list(rt->mfc_bw_meter);
848             free(rt, M_MRTABLE);
849             rt = nr;
850         }
851     }
852     bzero((caddr_t)mfctable, sizeof(mfctable));
853     bzero((caddr_t)nexpire, sizeof(nexpire));
854     bw_upcalls_n = 0;
855     bzero(bw_meter_timers, sizeof(bw_meter_timers));
856     MFC_UNLOCK();
857
858     /*
859      * Reset de-encapsulation cache
860      */
861     last_encap_src = INADDR_ANY;
862     last_encap_vif = NULL;
863 #ifdef PIM
864     reg_vif_num = VIFI_INVALID;
865 #endif
866
867     mtx_unlock(&mrouter_mtx);
868
869     if (mrtdebug)
870         log(LOG_DEBUG, "ip_mrouter_done\n");
871
872     return 0;
873 }
874
875 /*
876  * Set PIM assert processing global
877  */
878 static int
879 set_assert(int i)
880 {
881     if ((i != 1) && (i != 0))
882         return EINVAL;
883
884     pim_assert = i;
885
886     return 0;
887 }
888
889 /*
890  * Configure API capabilities
891  */
892 int
893 set_api_config(uint32_t *apival)
894 {
895     int i;
896
897     /*
898      * We can set the API capabilities only if it is the first operation
899      * after MRT_INIT. I.e.:
900      *  - there are no vifs installed
901      *  - pim_assert is not enabled
902      *  - the MFC table is empty
903      */
904     if (numvifs > 0) {
905         *apival = 0;
906         return EPERM;
907     }
908     if (pim_assert) {
909         *apival = 0;
910         return EPERM;
911     }
912     for (i = 0; i < MFCTBLSIZ; i++) {
913         if (mfctable[i] != NULL) {
914             *apival = 0;
915             return EPERM;
916         }
917     }
918
919     mrt_api_config = *apival & mrt_api_support;
920     *apival = mrt_api_config;
921
922     return 0;
923 }
924
925 /*
926  * Decide if a packet is from a tunnelled peer.
927  * Return 0 if not, 64 if so.  XXX yuck.. 64 ???
928  */
929 static int
930 mroute_encapcheck(const struct mbuf *m, int off, int proto, void *arg)
931 {
932     struct ip *ip = mtod(m, struct ip *);
933     int hlen = ip->ip_hl << 2;
934
935     /*
936      * don't claim the packet if it's not to a multicast destination or if
937      * we don't have an encapsulating tunnel with the source.
938      * Note:  This code assumes that the remote site IP address
939      * uniquely identifies the tunnel (i.e., that this site has
940      * at most one tunnel with the remote site).
941      */
942     if (!IN_MULTICAST(ntohl(((struct ip *)((char *)ip+hlen))->ip_dst.s_addr)))
943         return 0;
944     if (ip->ip_src.s_addr != last_encap_src) {
945         struct vif *vifp = viftable;
946         struct vif *vife = vifp + numvifs;
947
948         last_encap_src = ip->ip_src.s_addr;
949         last_encap_vif = NULL;
950         for ( ; vifp < vife; ++vifp)
951             if (vifp->v_rmt_addr.s_addr == ip->ip_src.s_addr) {
952                 if ((vifp->v_flags & (VIFF_TUNNEL|VIFF_SRCRT)) == VIFF_TUNNEL)
953                     last_encap_vif = vifp;
954                 break;
955             }
956     }
957     if (last_encap_vif == NULL) {
958         last_encap_src = INADDR_ANY;
959         return 0;
960     }
961     return 64;
962 }
963
964 /*
965  * De-encapsulate a packet and feed it back through ip input (this
966  * routine is called whenever IP gets a packet that mroute_encap_func()
967  * claimed).
968  */
969 static void
970 mroute_encap_input(struct mbuf *m, int off)
971 {
972     struct ip *ip = mtod(m, struct ip *);
973     int hlen = ip->ip_hl << 2;
974
975     if (hlen > sizeof(struct ip))
976         ip_stripoptions(m, (struct mbuf *) 0);
977     m->m_data += sizeof(struct ip);
978     m->m_len -= sizeof(struct ip);
979     m->m_pkthdr.len -= sizeof(struct ip);
980
981     m->m_pkthdr.rcvif = last_encap_vif->v_ifp;
982
983     netisr_queue(NETISR_IP, m);         /* mbuf is free'd on failure. */
984     /*
985      * normally we would need a "schednetisr(NETISR_IP)"
986      * here but we were called by ip_input and it is going
987      * to loop back & try to dequeue the packet we just
988      * queued as soon as we return so we avoid the
989      * unnecessary software interrrupt.
990      *
991      * XXX
992      * This no longer holds - we may have direct-dispatched the packet,
993      * or there may be a queue processing limit.
994      */
995 }
996
997 extern struct domain inetdomain;
998 static struct protosw mroute_encap_protosw =
999 {
1000         .pr_type =              SOCK_RAW,
1001         .pr_domain =            &inetdomain,
1002         .pr_protocol =          IPPROTO_IPV4,
1003         .pr_flags =             PR_ATOMIC|PR_ADDR,
1004         .pr_input =             mroute_encap_input,
1005         .pr_ctloutput =         rip_ctloutput,
1006         .pr_usrreqs =           &rip_usrreqs
1007 };
1008
1009 /*
1010  * Add a vif to the vif table
1011  */
1012 static int
1013 add_vif(struct vifctl *vifcp)
1014 {
1015     struct vif *vifp = viftable + vifcp->vifc_vifi;
1016     struct sockaddr_in sin = {sizeof sin, AF_INET};
1017     struct ifaddr *ifa;
1018     struct ifnet *ifp;
1019     int error;
1020     struct tbf *v_tbf = tbftable + vifcp->vifc_vifi;
1021
1022     VIF_LOCK();
1023     if (vifcp->vifc_vifi >= MAXVIFS) {
1024         VIF_UNLOCK();
1025         return EINVAL;
1026     }
1027     if (vifp->v_lcl_addr.s_addr != INADDR_ANY) {
1028         VIF_UNLOCK();
1029         return EADDRINUSE;
1030     }
1031     if (vifcp->vifc_lcl_addr.s_addr == INADDR_ANY) {
1032         VIF_UNLOCK();
1033         return EADDRNOTAVAIL;
1034     }
1035
1036     /* Find the interface with an address in AF_INET family */
1037 #ifdef PIM
1038     if (vifcp->vifc_flags & VIFF_REGISTER) {
1039         /*
1040          * XXX: Because VIFF_REGISTER does not really need a valid
1041          * local interface (e.g. it could be 127.0.0.2), we don't
1042          * check its address.
1043          */
1044         ifp = NULL;
1045     } else
1046 #endif
1047     {
1048         sin.sin_addr = vifcp->vifc_lcl_addr;
1049         ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
1050         if (ifa == NULL) {
1051             VIF_UNLOCK();
1052             return EADDRNOTAVAIL;
1053         }
1054         ifp = ifa->ifa_ifp;
1055     }
1056
1057     if (vifcp->vifc_flags & VIFF_TUNNEL) {
1058         if ((vifcp->vifc_flags & VIFF_SRCRT) == 0) {
1059             /*
1060              * An encapsulating tunnel is wanted.  Tell
1061              * mroute_encap_input() to start paying attention
1062              * to encapsulated packets.
1063              */
1064             if (encap_cookie == NULL) {
1065                 int i;
1066
1067                 encap_cookie = encap_attach_func(AF_INET, IPPROTO_IPV4,
1068                                 mroute_encapcheck,
1069                                 (struct protosw *)&mroute_encap_protosw, NULL);
1070
1071                 if (encap_cookie == NULL) {
1072                     printf("ip_mroute: unable to attach encap\n");
1073                     VIF_UNLOCK();
1074                     return EIO; /* XXX */
1075                 }
1076                 for (i = 0; i < MAXVIFS; ++i) {
1077                     if_initname(&multicast_decap_if[i], "mdecap", i);
1078                 }
1079             }
1080             /*
1081              * Set interface to fake encapsulator interface
1082              */
1083             ifp = &multicast_decap_if[vifcp->vifc_vifi];
1084             /*
1085              * Prepare cached route entry
1086              */
1087             bzero(&vifp->v_route, sizeof(vifp->v_route));
1088         } else {
1089             log(LOG_ERR, "source routed tunnels not supported\n");
1090             VIF_UNLOCK();
1091             return EOPNOTSUPP;
1092         }
1093 #ifdef PIM
1094     } else if (vifcp->vifc_flags & VIFF_REGISTER) {
1095         ifp = &multicast_register_if;
1096         if (mrtdebug)
1097             log(LOG_DEBUG, "Adding a register vif, ifp: %p\n",
1098                     (void *)&multicast_register_if);
1099         if (reg_vif_num == VIFI_INVALID) {
1100             if_initname(&multicast_register_if, "register_vif", 0);
1101             multicast_register_if.if_flags = IFF_LOOPBACK;
1102             bzero(&vifp->v_route, sizeof(vifp->v_route));
1103             reg_vif_num = vifcp->vifc_vifi;
1104         }
1105 #endif
1106     } else {            /* Make sure the interface supports multicast */
1107         if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1108             VIF_UNLOCK();
1109             return EOPNOTSUPP;
1110         }
1111
1112         /* Enable promiscuous reception of all IP multicasts from the if */
1113         error = if_allmulti(ifp, 1);
1114         if (error) {
1115             VIF_UNLOCK();
1116             return error;
1117         }
1118     }
1119
1120     /* define parameters for the tbf structure */
1121     vifp->v_tbf = v_tbf;
1122     GET_TIME(vifp->v_tbf->tbf_last_pkt_t);
1123     vifp->v_tbf->tbf_n_tok = 0;
1124     vifp->v_tbf->tbf_q_len = 0;
1125     vifp->v_tbf->tbf_max_q_len = MAXQSIZE;
1126     vifp->v_tbf->tbf_q = vifp->v_tbf->tbf_t = NULL;
1127
1128     vifp->v_flags     = vifcp->vifc_flags;
1129     vifp->v_threshold = vifcp->vifc_threshold;
1130     vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
1131     vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
1132     vifp->v_ifp       = ifp;
1133     /* scaling up here allows division by 1024 in critical code */
1134     vifp->v_rate_limit= vifcp->vifc_rate_limit * 1024 / 1000;
1135     vifp->v_rsvp_on   = 0;
1136     vifp->v_rsvpd     = NULL;
1137     /* initialize per vif pkt counters */
1138     vifp->v_pkt_in    = 0;
1139     vifp->v_pkt_out   = 0;
1140     vifp->v_bytes_in  = 0;
1141     vifp->v_bytes_out = 0;
1142
1143     /* Adjust numvifs up if the vifi is higher than numvifs */
1144     if (numvifs <= vifcp->vifc_vifi) numvifs = vifcp->vifc_vifi + 1;
1145
1146     VIF_UNLOCK();
1147
1148     if (mrtdebug)
1149         log(LOG_DEBUG, "add_vif #%d, lcladdr %lx, %s %lx, thresh %x, rate %d\n",
1150             vifcp->vifc_vifi,
1151             (u_long)ntohl(vifcp->vifc_lcl_addr.s_addr),
1152             (vifcp->vifc_flags & VIFF_TUNNEL) ? "rmtaddr" : "mask",
1153             (u_long)ntohl(vifcp->vifc_rmt_addr.s_addr),
1154             vifcp->vifc_threshold,
1155             vifcp->vifc_rate_limit);
1156
1157     return 0;
1158 }
1159
1160 /*
1161  * Delete a vif from the vif table
1162  */
1163 static int
1164 del_vif_locked(vifi_t vifi)
1165 {
1166     struct vif *vifp;
1167
1168     VIF_LOCK_ASSERT();
1169
1170     if (vifi >= numvifs) {
1171         return EINVAL;
1172     }
1173     vifp = &viftable[vifi];
1174     if (vifp->v_lcl_addr.s_addr == INADDR_ANY) {
1175         return EADDRNOTAVAIL;
1176     }
1177
1178     if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
1179         if_allmulti(vifp->v_ifp, 0);
1180
1181     if (vifp == last_encap_vif) {
1182         last_encap_vif = NULL;
1183         last_encap_src = INADDR_ANY;
1184     }
1185
1186     /*
1187      * Free packets queued at the interface
1188      */
1189     while (vifp->v_tbf->tbf_q) {
1190         struct mbuf *m = vifp->v_tbf->tbf_q;
1191
1192         vifp->v_tbf->tbf_q = m->m_act;
1193         m_freem(m);
1194     }
1195
1196 #ifdef PIM
1197     if (vifp->v_flags & VIFF_REGISTER)
1198         reg_vif_num = VIFI_INVALID;
1199 #endif
1200
1201     bzero((caddr_t)vifp->v_tbf, sizeof(*(vifp->v_tbf)));
1202     bzero((caddr_t)vifp, sizeof (*vifp));
1203
1204     if (mrtdebug)
1205         log(LOG_DEBUG, "del_vif %d, numvifs %d\n", vifi, numvifs);
1206
1207     /* Adjust numvifs down */
1208     for (vifi = numvifs; vifi > 0; vifi--)
1209         if (viftable[vifi-1].v_lcl_addr.s_addr != INADDR_ANY)
1210             break;
1211     numvifs = vifi;
1212
1213     return 0;
1214 }
1215
1216 static int
1217 del_vif(vifi_t vifi)
1218 {
1219     int cc;
1220
1221     VIF_LOCK();
1222     cc = del_vif_locked(vifi);
1223     VIF_UNLOCK();
1224
1225     return cc;
1226 }
1227
1228 /*
1229  * update an mfc entry without resetting counters and S,G addresses.
1230  */
1231 static void
1232 update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1233 {
1234     int i;
1235
1236     rt->mfc_parent = mfccp->mfcc_parent;
1237     for (i = 0; i < numvifs; i++) {
1238         rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1239         rt->mfc_flags[i] = mfccp->mfcc_flags[i] & mrt_api_config &
1240             MRT_MFC_FLAGS_ALL;
1241     }
1242     /* set the RP address */
1243     if (mrt_api_config & MRT_MFC_RP)
1244         rt->mfc_rp = mfccp->mfcc_rp;
1245     else
1246         rt->mfc_rp.s_addr = INADDR_ANY;
1247 }
1248
1249 /*
1250  * fully initialize an mfc entry from the parameter.
1251  */
1252 static void
1253 init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1254 {
1255     rt->mfc_origin     = mfccp->mfcc_origin;
1256     rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
1257
1258     update_mfc_params(rt, mfccp);
1259
1260     /* initialize pkt counters per src-grp */
1261     rt->mfc_pkt_cnt    = 0;
1262     rt->mfc_byte_cnt   = 0;
1263     rt->mfc_wrong_if   = 0;
1264     rt->mfc_last_assert.tv_sec = rt->mfc_last_assert.tv_usec = 0;
1265 }
1266
1267
1268 /*
1269  * Add an mfc entry
1270  */
1271 static int
1272 add_mfc(struct mfcctl2 *mfccp)
1273 {
1274     struct mfc *rt;
1275     u_long hash;
1276     struct rtdetq *rte;
1277     u_short nstl;
1278
1279     VIF_LOCK();
1280     MFC_LOCK();
1281
1282     rt = mfc_find(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
1283
1284     /* If an entry already exists, just update the fields */
1285     if (rt) {
1286         if (mrtdebug & DEBUG_MFC)
1287             log(LOG_DEBUG,"add_mfc update o %lx g %lx p %x\n",
1288                 (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1289                 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1290                 mfccp->mfcc_parent);
1291
1292         update_mfc_params(rt, mfccp);
1293         MFC_UNLOCK();
1294         VIF_UNLOCK();
1295         return 0;
1296     }
1297
1298     /*
1299      * Find the entry for which the upcall was made and update
1300      */
1301     hash = MFCHASH(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
1302     for (rt = mfctable[hash], nstl = 0; rt; rt = rt->mfc_next) {
1303
1304         if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1305                 (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr) &&
1306                 (rt->mfc_stall != NULL)) {
1307
1308             if (nstl++)
1309                 log(LOG_ERR, "add_mfc %s o %lx g %lx p %x dbx %p\n",
1310                     "multiple kernel entries",
1311                     (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1312                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1313                     mfccp->mfcc_parent, (void *)rt->mfc_stall);
1314
1315             if (mrtdebug & DEBUG_MFC)
1316                 log(LOG_DEBUG,"add_mfc o %lx g %lx p %x dbg %p\n",
1317                     (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1318                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1319                     mfccp->mfcc_parent, (void *)rt->mfc_stall);
1320
1321             init_mfc_params(rt, mfccp);
1322
1323             rt->mfc_expire = 0; /* Don't clean this guy up */
1324             nexpire[hash]--;
1325
1326             /* free packets Qed at the end of this entry */
1327             for (rte = rt->mfc_stall; rte != NULL; ) {
1328                 struct rtdetq *n = rte->next;
1329
1330                 ip_mdq(rte->m, rte->ifp, rt, -1);
1331                 m_freem(rte->m);
1332                 free(rte, M_MRTABLE);
1333                 rte = n;
1334             }
1335             rt->mfc_stall = NULL;
1336         }
1337     }
1338
1339     /*
1340      * It is possible that an entry is being inserted without an upcall
1341      */
1342     if (nstl == 0) {
1343         if (mrtdebug & DEBUG_MFC)
1344             log(LOG_DEBUG,"add_mfc no upcall h %lu o %lx g %lx p %x\n",
1345                 hash, (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1346                 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1347                 mfccp->mfcc_parent);
1348
1349         for (rt = mfctable[hash]; rt != NULL; rt = rt->mfc_next) {
1350             if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1351                     (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr)) {
1352                 init_mfc_params(rt, mfccp);
1353                 if (rt->mfc_expire)
1354                     nexpire[hash]--;
1355                 rt->mfc_expire = 0;
1356                 break; /* XXX */
1357             }
1358         }
1359         if (rt == NULL) {               /* no upcall, so make a new entry */
1360             rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1361             if (rt == NULL) {
1362                 MFC_UNLOCK();
1363                 VIF_UNLOCK();
1364                 return ENOBUFS;
1365             }
1366
1367             init_mfc_params(rt, mfccp);
1368             rt->mfc_expire     = 0;
1369             rt->mfc_stall      = NULL;
1370
1371             rt->mfc_bw_meter = NULL;
1372             /* insert new entry at head of hash chain */
1373             rt->mfc_next = mfctable[hash];
1374             mfctable[hash] = rt;
1375         }
1376     }
1377     MFC_UNLOCK();
1378     VIF_UNLOCK();
1379     return 0;
1380 }
1381
1382 /*
1383  * Delete an mfc entry
1384  */
1385 static int
1386 del_mfc(struct mfcctl2 *mfccp)
1387 {
1388     struct in_addr      origin;
1389     struct in_addr      mcastgrp;
1390     struct mfc          *rt;
1391     struct mfc          **nptr;
1392     u_long              hash;
1393     struct bw_meter     *list;
1394
1395     origin = mfccp->mfcc_origin;
1396     mcastgrp = mfccp->mfcc_mcastgrp;
1397
1398     if (mrtdebug & DEBUG_MFC)
1399         log(LOG_DEBUG,"del_mfc orig %lx mcastgrp %lx\n",
1400             (u_long)ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
1401
1402     MFC_LOCK();
1403
1404     hash = MFCHASH(origin.s_addr, mcastgrp.s_addr);
1405     for (nptr = &mfctable[hash]; (rt = *nptr) != NULL; nptr = &rt->mfc_next)
1406         if (origin.s_addr == rt->mfc_origin.s_addr &&
1407                 mcastgrp.s_addr == rt->mfc_mcastgrp.s_addr &&
1408                 rt->mfc_stall == NULL)
1409             break;
1410     if (rt == NULL) {
1411         MFC_UNLOCK();
1412         return EADDRNOTAVAIL;
1413     }
1414
1415     *nptr = rt->mfc_next;
1416
1417     /*
1418      * free the bw_meter entries
1419      */
1420     list = rt->mfc_bw_meter;
1421     rt->mfc_bw_meter = NULL;
1422
1423     free(rt, M_MRTABLE);
1424
1425     free_bw_list(list);
1426
1427     MFC_UNLOCK();
1428
1429     return 0;
1430 }
1431
1432 /*
1433  * Send a message to the routing daemon on the multicast routing socket
1434  */
1435 static int
1436 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1437 {
1438     if (s) {
1439         SOCKBUF_LOCK(&s->so_rcv);
1440         if (sbappendaddr_locked(&s->so_rcv, (struct sockaddr *)src, mm,
1441             NULL) != 0) {
1442             sorwakeup_locked(s);
1443             return 0;
1444         }
1445         SOCKBUF_UNLOCK(&s->so_rcv);
1446     }
1447     m_freem(mm);
1448     return -1;
1449 }
1450
1451 /*
1452  * IP multicast forwarding function. This function assumes that the packet
1453  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1454  * pointed to by "ifp", and the packet is to be relayed to other networks
1455  * that have members of the packet's destination IP multicast group.
1456  *
1457  * The packet is returned unscathed to the caller, unless it is
1458  * erroneous, in which case a non-zero return value tells the caller to
1459  * discard it.
1460  */
1461
1462 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1463
1464 static int
1465 X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1466     struct ip_moptions *imo)
1467 {
1468     struct mfc *rt;
1469     int error;
1470     vifi_t vifi;
1471
1472     if (mrtdebug & DEBUG_FORWARD)
1473         log(LOG_DEBUG, "ip_mforward: src %lx, dst %lx, ifp %p\n",
1474             (u_long)ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr),
1475             (void *)ifp);
1476
1477     if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1478                 ((u_char *)(ip + 1))[1] != IPOPT_LSRR ) {
1479         /*
1480          * Packet arrived via a physical interface or
1481          * an encapsulated tunnel or a register_vif.
1482          */
1483     } else {
1484         /*
1485          * Packet arrived through a source-route tunnel.
1486          * Source-route tunnels are no longer supported.
1487          */
1488         static int last_log;
1489         if (last_log != time_uptime) {
1490             last_log = time_uptime;
1491             log(LOG_ERR,
1492                 "ip_mforward: received source-routed packet from %lx\n",
1493                 (u_long)ntohl(ip->ip_src.s_addr));
1494         }
1495         return 1;
1496     }
1497
1498     VIF_LOCK();
1499     MFC_LOCK();
1500     if (imo && ((vifi = imo->imo_multicast_vif) < numvifs)) {
1501         if (ip->ip_ttl < 255)
1502             ip->ip_ttl++;       /* compensate for -1 in *_send routines */
1503         if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1504             struct vif *vifp = viftable + vifi;
1505
1506             printf("Sending IPPROTO_RSVP from %lx to %lx on vif %d (%s%s)\n",
1507                 (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr),
1508                 vifi,
1509                 (vifp->v_flags & VIFF_TUNNEL) ? "tunnel on " : "",
1510                 vifp->v_ifp->if_xname);
1511         }
1512         error = ip_mdq(m, ifp, NULL, vifi);
1513         MFC_UNLOCK();
1514         VIF_UNLOCK();
1515         return error;
1516     }
1517     if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1518         printf("Warning: IPPROTO_RSVP from %lx to %lx without vif option\n",
1519             (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr));
1520         if (!imo)
1521             printf("In fact, no options were specified at all\n");
1522     }
1523
1524     /*
1525      * Don't forward a packet with time-to-live of zero or one,
1526      * or a packet destined to a local-only group.
1527      */
1528     if (ip->ip_ttl <= 1 || ntohl(ip->ip_dst.s_addr) <= INADDR_MAX_LOCAL_GROUP) {
1529         MFC_UNLOCK();
1530         VIF_UNLOCK();
1531         return 0;
1532     }
1533
1534     /*
1535      * Determine forwarding vifs from the forwarding cache table
1536      */
1537     ++mrtstat.mrts_mfc_lookups;
1538     rt = mfc_find(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1539
1540     /* Entry exists, so forward if necessary */
1541     if (rt != NULL) {
1542         error = ip_mdq(m, ifp, rt, -1);
1543         MFC_UNLOCK();
1544         VIF_UNLOCK();
1545         return error;
1546     } else {
1547         /*
1548          * If we don't have a route for packet's origin,
1549          * Make a copy of the packet & send message to routing daemon
1550          */
1551
1552         struct mbuf *mb0;
1553         struct rtdetq *rte;
1554         u_long hash;
1555         int hlen = ip->ip_hl << 2;
1556
1557         ++mrtstat.mrts_mfc_misses;
1558
1559         mrtstat.mrts_no_route++;
1560         if (mrtdebug & (DEBUG_FORWARD | DEBUG_MFC))
1561             log(LOG_DEBUG, "ip_mforward: no rte s %lx g %lx\n",
1562                 (u_long)ntohl(ip->ip_src.s_addr),
1563                 (u_long)ntohl(ip->ip_dst.s_addr));
1564
1565         /*
1566          * Allocate mbufs early so that we don't do extra work if we are
1567          * just going to fail anyway.  Make sure to pullup the header so
1568          * that other people can't step on it.
1569          */
1570         rte = (struct rtdetq *)malloc((sizeof *rte), M_MRTABLE, M_NOWAIT);
1571         if (rte == NULL) {
1572             MFC_UNLOCK();
1573             VIF_UNLOCK();
1574             return ENOBUFS;
1575         }
1576         mb0 = m_copypacket(m, M_DONTWAIT);
1577         if (mb0 && (M_HASCL(mb0) || mb0->m_len < hlen))
1578             mb0 = m_pullup(mb0, hlen);
1579         if (mb0 == NULL) {
1580             free(rte, M_MRTABLE);
1581             MFC_UNLOCK();
1582             VIF_UNLOCK();
1583             return ENOBUFS;
1584         }
1585
1586         /* is there an upcall waiting for this flow ? */
1587         hash = MFCHASH(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1588         for (rt = mfctable[hash]; rt; rt = rt->mfc_next) {
1589             if ((ip->ip_src.s_addr == rt->mfc_origin.s_addr) &&
1590                     (ip->ip_dst.s_addr == rt->mfc_mcastgrp.s_addr) &&
1591                     (rt->mfc_stall != NULL))
1592                 break;
1593         }
1594
1595         if (rt == NULL) {
1596             int i;
1597             struct igmpmsg *im;
1598             struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1599             struct mbuf *mm;
1600
1601             /*
1602              * Locate the vifi for the incoming interface for this packet.
1603              * If none found, drop packet.
1604              */
1605             for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1606                 ;
1607             if (vifi >= numvifs)        /* vif not found, drop packet */
1608                 goto non_fatal;
1609
1610             /* no upcall, so make a new entry */
1611             rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1612             if (rt == NULL)
1613                 goto fail;
1614             /* Make a copy of the header to send to the user level process */
1615             mm = m_copy(mb0, 0, hlen);
1616             if (mm == NULL)
1617                 goto fail1;
1618
1619             /*
1620              * Send message to routing daemon to install
1621              * a route into the kernel table
1622              */
1623
1624             im = mtod(mm, struct igmpmsg *);
1625             im->im_msgtype = IGMPMSG_NOCACHE;
1626             im->im_mbz = 0;
1627             im->im_vif = vifi;
1628
1629             mrtstat.mrts_upcalls++;
1630
1631             k_igmpsrc.sin_addr = ip->ip_src;
1632             if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1633                 log(LOG_WARNING, "ip_mforward: ip_mrouter socket queue full\n");
1634                 ++mrtstat.mrts_upq_sockfull;
1635 fail1:
1636                 free(rt, M_MRTABLE);
1637 fail:
1638                 free(rte, M_MRTABLE);
1639                 m_freem(mb0);
1640                 MFC_UNLOCK();
1641                 VIF_UNLOCK();
1642                 return ENOBUFS;
1643             }
1644
1645             /* insert new entry at head of hash chain */
1646             rt->mfc_origin.s_addr     = ip->ip_src.s_addr;
1647             rt->mfc_mcastgrp.s_addr   = ip->ip_dst.s_addr;
1648             rt->mfc_expire            = UPCALL_EXPIRE;
1649             nexpire[hash]++;
1650             for (i = 0; i < numvifs; i++) {
1651                 rt->mfc_ttls[i] = 0;
1652                 rt->mfc_flags[i] = 0;
1653             }
1654             rt->mfc_parent = -1;
1655
1656             rt->mfc_rp.s_addr = INADDR_ANY; /* clear the RP address */
1657
1658             rt->mfc_bw_meter = NULL;
1659
1660             /* link into table */
1661             rt->mfc_next   = mfctable[hash];
1662             mfctable[hash] = rt;
1663             rt->mfc_stall = rte;
1664
1665         } else {
1666             /* determine if q has overflowed */
1667             int npkts = 0;
1668             struct rtdetq **p;
1669
1670             /*
1671              * XXX ouch! we need to append to the list, but we
1672              * only have a pointer to the front, so we have to
1673              * scan the entire list every time.
1674              */
1675             for (p = &rt->mfc_stall; *p != NULL; p = &(*p)->next)
1676                 npkts++;
1677
1678             if (npkts > MAX_UPQ) {
1679                 mrtstat.mrts_upq_ovflw++;
1680 non_fatal:
1681                 free(rte, M_MRTABLE);
1682                 m_freem(mb0);
1683                 MFC_UNLOCK();
1684                 VIF_UNLOCK();
1685                 return 0;
1686             }
1687
1688             /* Add this entry to the end of the queue */
1689             *p = rte;
1690         }
1691
1692         rte->m                  = mb0;
1693         rte->ifp                = ifp;
1694         rte->next               = NULL;
1695
1696         MFC_UNLOCK();
1697         VIF_UNLOCK();
1698
1699         return 0;
1700     }
1701 }
1702
1703 /*
1704  * Clean up the cache entry if upcall is not serviced
1705  */
1706 static void
1707 expire_upcalls(void *unused)
1708 {
1709     struct rtdetq *rte;
1710     struct mfc *mfc, **nptr;
1711     int i;
1712
1713     MFC_LOCK();
1714     for (i = 0; i < MFCTBLSIZ; i++) {
1715         if (nexpire[i] == 0)
1716             continue;
1717         nptr = &mfctable[i];
1718         for (mfc = *nptr; mfc != NULL; mfc = *nptr) {
1719             /*
1720              * Skip real cache entries
1721              * Make sure it wasn't marked to not expire (shouldn't happen)
1722              * If it expires now
1723              */
1724             if (mfc->mfc_stall != NULL && mfc->mfc_expire != 0 &&
1725                     --mfc->mfc_expire == 0) {
1726                 if (mrtdebug & DEBUG_EXPIRE)
1727                     log(LOG_DEBUG, "expire_upcalls: expiring (%lx %lx)\n",
1728                         (u_long)ntohl(mfc->mfc_origin.s_addr),
1729                         (u_long)ntohl(mfc->mfc_mcastgrp.s_addr));
1730                 /*
1731                  * drop all the packets
1732                  * free the mbuf with the pkt, if, timing info
1733                  */
1734                 for (rte = mfc->mfc_stall; rte; ) {
1735                     struct rtdetq *n = rte->next;
1736
1737                     m_freem(rte->m);
1738                     free(rte, M_MRTABLE);
1739                     rte = n;
1740                 }
1741                 ++mrtstat.mrts_cache_cleanups;
1742                 nexpire[i]--;
1743
1744                 /*
1745                  * free the bw_meter entries
1746                  */
1747                 while (mfc->mfc_bw_meter != NULL) {
1748                     struct bw_meter *x = mfc->mfc_bw_meter;
1749
1750                     mfc->mfc_bw_meter = x->bm_mfc_next;
1751                     free(x, M_BWMETER);
1752                 }
1753
1754                 *nptr = mfc->mfc_next;
1755                 free(mfc, M_MRTABLE);
1756             } else {
1757                 nptr = &mfc->mfc_next;
1758             }
1759         }
1760     }
1761     MFC_UNLOCK();
1762
1763     callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
1764 }
1765
1766 /*
1767  * Packet forwarding routine once entry in the cache is made
1768  */
1769 static int
1770 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1771 {
1772     struct ip  *ip = mtod(m, struct ip *);
1773     vifi_t vifi;
1774     int plen = ip->ip_len;
1775
1776     VIF_LOCK_ASSERT();
1777 /*
1778  * Macro to send packet on vif.  Since RSVP packets don't get counted on
1779  * input, they shouldn't get counted on output, so statistics keeping is
1780  * separate.
1781  */
1782 #define MC_SEND(ip,vifp,m) {                            \
1783                 if ((vifp)->v_flags & VIFF_TUNNEL)      \
1784                     encap_send((ip), (vifp), (m));      \
1785                 else                                    \
1786                     phyint_send((ip), (vifp), (m));     \
1787 }
1788
1789     /*
1790      * If xmt_vif is not -1, send on only the requested vif.
1791      *
1792      * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1793      */
1794     if (xmt_vif < numvifs) {
1795 #ifdef PIM
1796         if (viftable[xmt_vif].v_flags & VIFF_REGISTER)
1797             pim_register_send(ip, viftable + xmt_vif, m, rt);
1798         else
1799 #endif
1800         MC_SEND(ip, viftable + xmt_vif, m);
1801         return 1;
1802     }
1803
1804     /*
1805      * Don't forward if it didn't arrive from the parent vif for its origin.
1806      */
1807     vifi = rt->mfc_parent;
1808     if ((vifi >= numvifs) || (viftable[vifi].v_ifp != ifp)) {
1809         /* came in the wrong interface */
1810         if (mrtdebug & DEBUG_FORWARD)
1811             log(LOG_DEBUG, "wrong if: ifp %p vifi %d vififp %p\n",
1812                 (void *)ifp, vifi, (void *)viftable[vifi].v_ifp);
1813         ++mrtstat.mrts_wrong_if;
1814         ++rt->mfc_wrong_if;
1815         /*
1816          * If we are doing PIM assert processing, send a message
1817          * to the routing daemon.
1818          *
1819          * XXX: A PIM-SM router needs the WRONGVIF detection so it
1820          * can complete the SPT switch, regardless of the type
1821          * of the iif (broadcast media, GRE tunnel, etc).
1822          */
1823         if (pim_assert && (vifi < numvifs) && viftable[vifi].v_ifp) {
1824             struct timeval now;
1825             u_long delta;
1826
1827 #ifdef PIM
1828             if (ifp == &multicast_register_if)
1829                 pimstat.pims_rcv_registers_wrongiif++;
1830 #endif
1831
1832             /* Get vifi for the incoming packet */
1833             for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1834                 ;
1835             if (vifi >= numvifs)
1836                 return 0;       /* The iif is not found: ignore the packet. */
1837
1838             if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1839                 return 0;       /* WRONGVIF disabled: ignore the packet */
1840
1841             GET_TIME(now);
1842
1843             TV_DELTA(now, rt->mfc_last_assert, delta);
1844
1845             if (delta > ASSERT_MSG_TIME) {
1846                 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1847                 struct igmpmsg *im;
1848                 int hlen = ip->ip_hl << 2;
1849                 struct mbuf *mm = m_copy(m, 0, hlen);
1850
1851                 if (mm && (M_HASCL(mm) || mm->m_len < hlen))
1852                     mm = m_pullup(mm, hlen);
1853                 if (mm == NULL)
1854                     return ENOBUFS;
1855
1856                 rt->mfc_last_assert = now;
1857
1858                 im = mtod(mm, struct igmpmsg *);
1859                 im->im_msgtype  = IGMPMSG_WRONGVIF;
1860                 im->im_mbz              = 0;
1861                 im->im_vif              = vifi;
1862
1863                 mrtstat.mrts_upcalls++;
1864
1865                 k_igmpsrc.sin_addr = im->im_src;
1866                 if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1867                     log(LOG_WARNING,
1868                         "ip_mforward: ip_mrouter socket queue full\n");
1869                     ++mrtstat.mrts_upq_sockfull;
1870                     return ENOBUFS;
1871                 }
1872             }
1873         }
1874         return 0;
1875     }
1876
1877     /* If I sourced this packet, it counts as output, else it was input. */
1878     if (ip->ip_src.s_addr == viftable[vifi].v_lcl_addr.s_addr) {
1879         viftable[vifi].v_pkt_out++;
1880         viftable[vifi].v_bytes_out += plen;
1881     } else {
1882         viftable[vifi].v_pkt_in++;
1883         viftable[vifi].v_bytes_in += plen;
1884     }
1885     rt->mfc_pkt_cnt++;
1886     rt->mfc_byte_cnt += plen;
1887
1888     /*
1889      * For each vif, decide if a copy of the packet should be forwarded.
1890      * Forward if:
1891      *          - the ttl exceeds the vif's threshold
1892      *          - there are group members downstream on interface
1893      */
1894     for (vifi = 0; vifi < numvifs; vifi++)
1895         if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1896             viftable[vifi].v_pkt_out++;
1897             viftable[vifi].v_bytes_out += plen;
1898 #ifdef PIM
1899             if (viftable[vifi].v_flags & VIFF_REGISTER)
1900                 pim_register_send(ip, viftable + vifi, m, rt);
1901             else
1902 #endif
1903             MC_SEND(ip, viftable+vifi, m);
1904         }
1905
1906     /*
1907      * Perform upcall-related bw measuring.
1908      */
1909     if (rt->mfc_bw_meter != NULL) {
1910         struct bw_meter *x;
1911         struct timeval now;
1912
1913         GET_TIME(now);
1914         MFC_LOCK_ASSERT();
1915         for (x = rt->mfc_bw_meter; x != NULL; x = x->bm_mfc_next)
1916             bw_meter_receive_packet(x, plen, &now);
1917     }
1918
1919     return 0;
1920 }
1921
1922 /*
1923  * check if a vif number is legal/ok. This is used by ip_output.
1924  */
1925 static int
1926 X_legal_vif_num(int vif)
1927 {
1928     /* XXX unlocked, matter? */
1929     return (vif >= 0 && vif < numvifs);
1930 }
1931
1932 /*
1933  * Return the local address used by this vif
1934  */
1935 static u_long
1936 X_ip_mcast_src(int vifi)
1937 {
1938     /* XXX unlocked, matter? */
1939     if (vifi >= 0 && vifi < numvifs)
1940         return viftable[vifi].v_lcl_addr.s_addr;
1941     else
1942         return INADDR_ANY;
1943 }
1944
1945 static void
1946 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1947 {
1948     struct mbuf *mb_copy;
1949     int hlen = ip->ip_hl << 2;
1950
1951     VIF_LOCK_ASSERT();
1952
1953     /*
1954      * Make a new reference to the packet; make sure that
1955      * the IP header is actually copied, not just referenced,
1956      * so that ip_output() only scribbles on the copy.
1957      */
1958     mb_copy = m_copypacket(m, M_DONTWAIT);
1959     if (mb_copy && (M_HASCL(mb_copy) || mb_copy->m_len < hlen))
1960         mb_copy = m_pullup(mb_copy, hlen);
1961     if (mb_copy == NULL)
1962         return;
1963
1964     if (vifp->v_rate_limit == 0)
1965         tbf_send_packet(vifp, mb_copy);
1966     else
1967         tbf_control(vifp, mb_copy, mtod(mb_copy, struct ip *), ip->ip_len);
1968 }
1969
1970 static void
1971 encap_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1972 {
1973     struct mbuf *mb_copy;
1974     struct ip *ip_copy;
1975     int i, len = ip->ip_len;
1976
1977     VIF_LOCK_ASSERT();
1978
1979     /* Take care of delayed checksums */
1980     if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1981         in_delayed_cksum(m);
1982         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1983     }
1984
1985     /*
1986      * copy the old packet & pullup its IP header into the
1987      * new mbuf so we can modify it.  Try to fill the new
1988      * mbuf since if we don't the ethernet driver will.
1989      */
1990     MGETHDR(mb_copy, M_DONTWAIT, MT_DATA);
1991     if (mb_copy == NULL)
1992         return;
1993 #ifdef MAC
1994     mac_create_mbuf_multicast_encap(m, vifp->v_ifp, mb_copy);
1995 #endif
1996     mb_copy->m_data += max_linkhdr;
1997     mb_copy->m_len = sizeof(multicast_encap_iphdr);
1998
1999     if ((mb_copy->m_next = m_copypacket(m, M_DONTWAIT)) == NULL) {
2000         m_freem(mb_copy);
2001         return;
2002     }
2003     i = MHLEN - M_LEADINGSPACE(mb_copy);
2004     if (i > len)
2005         i = len;
2006     mb_copy = m_pullup(mb_copy, i);
2007     if (mb_copy == NULL)
2008         return;
2009     mb_copy->m_pkthdr.len = len + sizeof(multicast_encap_iphdr);
2010
2011     /*
2012      * fill in the encapsulating IP header.
2013      */
2014     ip_copy = mtod(mb_copy, struct ip *);
2015     *ip_copy = multicast_encap_iphdr;
2016     ip_copy->ip_id = ip_newid();
2017     ip_copy->ip_len += len;
2018     ip_copy->ip_src = vifp->v_lcl_addr;
2019     ip_copy->ip_dst = vifp->v_rmt_addr;
2020
2021     /*
2022      * turn the encapsulated IP header back into a valid one.
2023      */
2024     ip = (struct ip *)((caddr_t)ip_copy + sizeof(multicast_encap_iphdr));
2025     --ip->ip_ttl;
2026     ip->ip_len = htons(ip->ip_len);
2027     ip->ip_off = htons(ip->ip_off);
2028     ip->ip_sum = 0;
2029     mb_copy->m_data += sizeof(multicast_encap_iphdr);
2030     ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2031     mb_copy->m_data -= sizeof(multicast_encap_iphdr);
2032
2033     if (vifp->v_rate_limit == 0)
2034         tbf_send_packet(vifp, mb_copy);
2035     else
2036         tbf_control(vifp, mb_copy, ip, ip_copy->ip_len);
2037 }
2038
2039 /*
2040  * Token bucket filter module
2041  */
2042
2043 static void
2044 tbf_control(struct vif *vifp, struct mbuf *m, struct ip *ip, u_long p_len)
2045 {
2046     struct tbf *t = vifp->v_tbf;
2047
2048     VIF_LOCK_ASSERT();
2049
2050     if (p_len > MAX_BKT_SIZE) {         /* drop if packet is too large */
2051         mrtstat.mrts_pkt2large++;
2052         m_freem(m);
2053         return;
2054     }
2055
2056     tbf_update_tokens(vifp);
2057
2058     if (t->tbf_q_len == 0) {            /* queue empty...               */
2059         if (p_len <= t->tbf_n_tok) {    /* send packet if enough tokens */
2060             t->tbf_n_tok -= p_len;
2061             tbf_send_packet(vifp, m);
2062         } else {                        /* no, queue packet and try later */
2063             tbf_queue(vifp, m);
2064             callout_reset(&tbf_reprocess_ch, TBF_REPROCESS,
2065                 tbf_reprocess_q, vifp);
2066         }
2067     } else if (t->tbf_q_len < t->tbf_max_q_len) {
2068         /* finite queue length, so queue pkts and process queue */
2069         tbf_queue(vifp, m);
2070         tbf_process_q(vifp);
2071     } else {
2072         /* queue full, try to dq and queue and process */
2073         if (!tbf_dq_sel(vifp, ip)) {
2074             mrtstat.mrts_q_overflow++;
2075             m_freem(m);
2076         } else {
2077             tbf_queue(vifp, m);
2078             tbf_process_q(vifp);
2079         }
2080     }
2081 }
2082
2083 /*
2084  * adds a packet to the queue at the interface
2085  */
2086 static void
2087 tbf_queue(struct vif *vifp, struct mbuf *m)
2088 {
2089     struct tbf *t = vifp->v_tbf;
2090
2091     VIF_LOCK_ASSERT();
2092
2093     if (t->tbf_t == NULL)       /* Queue was empty */
2094         t->tbf_q = m;
2095     else                        /* Insert at tail */
2096         t->tbf_t->m_act = m;
2097
2098     t->tbf_t = m;               /* Set new tail pointer */
2099
2100 #ifdef DIAGNOSTIC
2101     /* Make sure we didn't get fed a bogus mbuf */
2102     if (m->m_act)
2103         panic("tbf_queue: m_act");
2104 #endif
2105     m->m_act = NULL;
2106
2107     t->tbf_q_len++;
2108 }
2109
2110 /*
2111  * processes the queue at the interface
2112  */
2113 static void
2114 tbf_process_q(struct vif *vifp)
2115 {
2116     struct tbf *t = vifp->v_tbf;
2117
2118     VIF_LOCK_ASSERT();
2119
2120     /* loop through the queue at the interface and send as many packets
2121      * as possible
2122      */
2123     while (t->tbf_q_len > 0) {
2124         struct mbuf *m = t->tbf_q;
2125         int len = mtod(m, struct ip *)->ip_len;
2126
2127         /* determine if the packet can be sent */
2128         if (len > t->tbf_n_tok) /* not enough tokens, we are done */
2129             break;
2130         /* ok, reduce no of tokens, dequeue and send the packet. */
2131         t->tbf_n_tok -= len;
2132
2133         t->tbf_q = m->m_act;
2134         if (--t->tbf_q_len == 0)
2135             t->tbf_t = NULL;
2136
2137         m->m_act = NULL;
2138         tbf_send_packet(vifp, m);
2139     }
2140 }
2141
2142 static void
2143 tbf_reprocess_q(void *xvifp)
2144 {
2145     struct vif *vifp = xvifp;
2146
2147     if (ip_mrouter == NULL)
2148         return;
2149     VIF_LOCK();
2150     tbf_update_tokens(vifp);
2151     tbf_process_q(vifp);
2152     if (vifp->v_tbf->tbf_q_len)
2153         callout_reset(&tbf_reprocess_ch, TBF_REPROCESS, tbf_reprocess_q, vifp);
2154     VIF_UNLOCK();
2155 }
2156
2157 /* function that will selectively discard a member of the queue
2158  * based on the precedence value and the priority
2159  */
2160 static int
2161 tbf_dq_sel(struct vif *vifp, struct ip *ip)
2162 {
2163     u_int p;
2164     struct mbuf *m, *last;
2165     struct mbuf **np;
2166     struct tbf *t = vifp->v_tbf;
2167
2168     VIF_LOCK_ASSERT();
2169
2170     p = priority(vifp, ip);
2171
2172     np = &t->tbf_q;
2173     last = NULL;
2174     while ((m = *np) != NULL) {
2175         if (p > priority(vifp, mtod(m, struct ip *))) {
2176             *np = m->m_act;
2177             /* If we're removing the last packet, fix the tail pointer */
2178             if (m == t->tbf_t)
2179                 t->tbf_t = last;
2180             m_freem(m);
2181             /* It's impossible for the queue to be empty, but check anyways. */
2182             if (--t->tbf_q_len == 0)
2183                 t->tbf_t = NULL;
2184             mrtstat.mrts_drop_sel++;
2185             return 1;
2186         }
2187         np = &m->m_act;
2188         last = m;
2189     }
2190     return 0;
2191 }
2192
2193 static void
2194 tbf_send_packet(struct vif *vifp, struct mbuf *m)
2195 {
2196     VIF_LOCK_ASSERT();
2197
2198     if (vifp->v_flags & VIFF_TUNNEL)    /* If tunnel options */
2199         ip_output(m, NULL, &vifp->v_route, IP_FORWARDING, NULL, NULL);
2200     else {
2201         struct ip_moptions imo;
2202         struct in_multi *imm[2];
2203         int error;
2204         static struct route ro; /* XXX check this */
2205
2206         imo.imo_multicast_ifp  = vifp->v_ifp;
2207         imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
2208         imo.imo_multicast_loop = 1;
2209         imo.imo_multicast_vif  = -1;
2210         imo.imo_num_memberships = 0;
2211         imo.imo_max_memberships = 2;
2212         imo.imo_membership  = &imm[0];
2213
2214         /*
2215          * Re-entrancy should not be a problem here, because
2216          * the packets that we send out and are looped back at us
2217          * should get rejected because they appear to come from
2218          * the loopback interface, thus preventing looping.
2219          */
2220         error = ip_output(m, NULL, &ro, IP_FORWARDING, &imo, NULL);
2221
2222         if (mrtdebug & DEBUG_XMIT)
2223             log(LOG_DEBUG, "phyint_send on vif %td err %d\n",
2224                 vifp - viftable, error);
2225     }
2226 }
2227
2228 /* determine the current time and then
2229  * the elapsed time (between the last time and time now)
2230  * in milliseconds & update the no. of tokens in the bucket
2231  */
2232 static void
2233 tbf_update_tokens(struct vif *vifp)
2234 {
2235     struct timeval tp;
2236     u_long tm;
2237     struct tbf *t = vifp->v_tbf;
2238
2239     VIF_LOCK_ASSERT();
2240
2241     GET_TIME(tp);
2242
2243     TV_DELTA(tp, t->tbf_last_pkt_t, tm);
2244
2245     /*
2246      * This formula is actually
2247      * "time in seconds" * "bytes/second".
2248      *
2249      * (tm / 1000000) * (v_rate_limit * 1000 * (1000/1024) / 8)
2250      *
2251      * The (1000/1024) was introduced in add_vif to optimize
2252      * this divide into a shift.
2253      */
2254     t->tbf_n_tok += tm * vifp->v_rate_limit / 1024 / 8;
2255     t->tbf_last_pkt_t = tp;
2256
2257     if (t->tbf_n_tok > MAX_BKT_SIZE)
2258         t->tbf_n_tok = MAX_BKT_SIZE;
2259 }
2260
2261 static int
2262 priority(struct vif *vifp, struct ip *ip)
2263 {
2264     int prio = 50; /* the lowest priority -- default case */
2265
2266     /* temporary hack; may add general packet classifier some day */
2267
2268     /*
2269      * The UDP port space is divided up into four priority ranges:
2270      * [0, 16384)     : unclassified - lowest priority
2271      * [16384, 32768) : audio - highest priority
2272      * [32768, 49152) : whiteboard - medium priority
2273      * [49152, 65536) : video - low priority
2274      *
2275      * Everything else gets lowest priority.
2276      */
2277     if (ip->ip_p == IPPROTO_UDP) {
2278         struct udphdr *udp = (struct udphdr *)(((char *)ip) + (ip->ip_hl << 2));
2279         switch (ntohs(udp->uh_dport) & 0xc000) {
2280         case 0x4000:
2281             prio = 70;
2282             break;
2283         case 0x8000:
2284             prio = 60;
2285             break;
2286         case 0xc000:
2287             prio = 55;
2288             break;
2289         }
2290     }
2291     return prio;
2292 }
2293
2294 /*
2295  * End of token bucket filter modifications
2296  */
2297
2298 static int
2299 X_ip_rsvp_vif(struct socket *so, struct sockopt *sopt)
2300 {
2301     int error, vifi;
2302
2303     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
2304         return EOPNOTSUPP;
2305
2306     error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
2307     if (error)
2308         return error;
2309
2310     VIF_LOCK();
2311
2312     if (vifi < 0 || vifi >= numvifs) {  /* Error if vif is invalid */
2313         VIF_UNLOCK();
2314         return EADDRNOTAVAIL;
2315     }
2316
2317     if (sopt->sopt_name == IP_RSVP_VIF_ON) {
2318         /* Check if socket is available. */
2319         if (viftable[vifi].v_rsvpd != NULL) {
2320             VIF_UNLOCK();
2321             return EADDRINUSE;
2322         }
2323
2324         viftable[vifi].v_rsvpd = so;
2325         /* This may seem silly, but we need to be sure we don't over-increment
2326          * the RSVP counter, in case something slips up.
2327          */
2328         if (!viftable[vifi].v_rsvp_on) {
2329             viftable[vifi].v_rsvp_on = 1;
2330             rsvp_on++;
2331         }
2332     } else { /* must be VIF_OFF */
2333         /*
2334          * XXX as an additional consistency check, one could make sure
2335          * that viftable[vifi].v_rsvpd == so, otherwise passing so as
2336          * first parameter is pretty useless.
2337          */
2338         viftable[vifi].v_rsvpd = NULL;
2339         /*
2340          * This may seem silly, but we need to be sure we don't over-decrement
2341          * the RSVP counter, in case something slips up.
2342          */
2343         if (viftable[vifi].v_rsvp_on) {
2344             viftable[vifi].v_rsvp_on = 0;
2345             rsvp_on--;
2346         }
2347     }
2348     VIF_UNLOCK();
2349     return 0;
2350 }
2351
2352 static void
2353 X_ip_rsvp_force_done(struct socket *so)
2354 {
2355     int vifi;
2356
2357     /* Don't bother if it is not the right type of socket. */
2358     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
2359         return;
2360
2361     VIF_LOCK();
2362
2363     /* The socket may be attached to more than one vif...this
2364      * is perfectly legal.
2365      */
2366     for (vifi = 0; vifi < numvifs; vifi++) {
2367         if (viftable[vifi].v_rsvpd == so) {
2368             viftable[vifi].v_rsvpd = NULL;
2369             /* This may seem silly, but we need to be sure we don't
2370              * over-decrement the RSVP counter, in case something slips up.
2371              */
2372             if (viftable[vifi].v_rsvp_on) {
2373                 viftable[vifi].v_rsvp_on = 0;
2374                 rsvp_on--;
2375             }
2376         }
2377     }
2378
2379     VIF_UNLOCK();
2380 }
2381
2382 static void
2383 X_rsvp_input(struct mbuf *m, int off)
2384 {
2385     int vifi;
2386     struct ip *ip = mtod(m, struct ip *);
2387     struct sockaddr_in rsvp_src = { sizeof rsvp_src, AF_INET };
2388     struct ifnet *ifp;
2389
2390     if (rsvpdebug)
2391         printf("rsvp_input: rsvp_on %d\n",rsvp_on);
2392
2393     /* Can still get packets with rsvp_on = 0 if there is a local member
2394      * of the group to which the RSVP packet is addressed.  But in this
2395      * case we want to throw the packet away.
2396      */
2397     if (!rsvp_on) {
2398         m_freem(m);
2399         return;
2400     }
2401
2402     if (rsvpdebug)
2403         printf("rsvp_input: check vifs\n");
2404
2405 #ifdef DIAGNOSTIC
2406     M_ASSERTPKTHDR(m);
2407 #endif
2408
2409     ifp = m->m_pkthdr.rcvif;
2410
2411     VIF_LOCK();
2412     /* Find which vif the packet arrived on. */
2413     for (vifi = 0; vifi < numvifs; vifi++)
2414         if (viftable[vifi].v_ifp == ifp)
2415             break;
2416
2417     if (vifi == numvifs || viftable[vifi].v_rsvpd == NULL) {
2418         /*
2419          * Drop the lock here to avoid holding it across rip_input.
2420          * This could make rsvpdebug printfs wrong.  If you care,
2421          * record the state of stuff before dropping the lock.
2422          */
2423         VIF_UNLOCK();
2424         /*
2425          * If the old-style non-vif-associated socket is set,
2426          * then use it.  Otherwise, drop packet since there
2427          * is no specific socket for this vif.
2428          */
2429         if (ip_rsvpd != NULL) {
2430             if (rsvpdebug)
2431                 printf("rsvp_input: Sending packet up old-style socket\n");
2432             rip_input(m, off);  /* xxx */
2433         } else {
2434             if (rsvpdebug && vifi == numvifs)
2435                 printf("rsvp_input: Can't find vif for packet.\n");
2436             else if (rsvpdebug && viftable[vifi].v_rsvpd == NULL)
2437                 printf("rsvp_input: No socket defined for vif %d\n",vifi);
2438             m_freem(m);
2439         }
2440         return;
2441     }
2442     rsvp_src.sin_addr = ip->ip_src;
2443
2444     if (rsvpdebug && m)
2445         printf("rsvp_input: m->m_len = %d, sbspace() = %ld\n",
2446                m->m_len,sbspace(&(viftable[vifi].v_rsvpd->so_rcv)));
2447
2448     if (socket_send(viftable[vifi].v_rsvpd, m, &rsvp_src) < 0) {
2449         if (rsvpdebug)
2450             printf("rsvp_input: Failed to append to socket\n");
2451     } else {
2452         if (rsvpdebug)
2453             printf("rsvp_input: send packet up\n");
2454     }
2455     VIF_UNLOCK();
2456 }
2457
2458 /*
2459  * Code for bandwidth monitors
2460  */
2461
2462 /*
2463  * Define common interface for timeval-related methods
2464  */
2465 #define BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
2466 #define BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
2467 #define BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
2468
2469 static uint32_t
2470 compute_bw_meter_flags(struct bw_upcall *req)
2471 {
2472     uint32_t flags = 0;
2473
2474     if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
2475         flags |= BW_METER_UNIT_PACKETS;
2476     if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
2477         flags |= BW_METER_UNIT_BYTES;
2478     if (req->bu_flags & BW_UPCALL_GEQ)
2479         flags |= BW_METER_GEQ;
2480     if (req->bu_flags & BW_UPCALL_LEQ)
2481         flags |= BW_METER_LEQ;
2482
2483     return flags;
2484 }
2485
2486 /*
2487  * Add a bw_meter entry
2488  */
2489 static int
2490 add_bw_upcall(struct bw_upcall *req)
2491 {
2492     struct mfc *mfc;
2493     struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
2494                 BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
2495     struct timeval now;
2496     struct bw_meter *x;
2497     uint32_t flags;
2498
2499     if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2500         return EOPNOTSUPP;
2501
2502     /* Test if the flags are valid */
2503     if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
2504         return EINVAL;
2505     if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
2506         return EINVAL;
2507     if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2508             == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2509         return EINVAL;
2510
2511     /* Test if the threshold time interval is valid */
2512     if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
2513         return EINVAL;
2514
2515     flags = compute_bw_meter_flags(req);
2516
2517     /*
2518      * Find if we have already same bw_meter entry
2519      */
2520     MFC_LOCK();
2521     mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2522     if (mfc == NULL) {
2523         MFC_UNLOCK();
2524         return EADDRNOTAVAIL;
2525     }
2526     for (x = mfc->mfc_bw_meter; x != NULL; x = x->bm_mfc_next) {
2527         if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2528                            &req->bu_threshold.b_time, ==)) &&
2529             (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2530             (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2531             (x->bm_flags & BW_METER_USER_FLAGS) == flags)  {
2532             MFC_UNLOCK();
2533             return 0;           /* XXX Already installed */
2534         }
2535     }
2536
2537     /* Allocate the new bw_meter entry */
2538     x = (struct bw_meter *)malloc(sizeof(*x), M_BWMETER, M_NOWAIT);
2539     if (x == NULL) {
2540         MFC_UNLOCK();
2541         return ENOBUFS;
2542     }
2543
2544     /* Set the new bw_meter entry */
2545     x->bm_threshold.b_time = req->bu_threshold.b_time;
2546     GET_TIME(now);
2547     x->bm_start_time = now;
2548     x->bm_threshold.b_packets = req->bu_threshold.b_packets;
2549     x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
2550     x->bm_measured.b_packets = 0;
2551     x->bm_measured.b_bytes = 0;
2552     x->bm_flags = flags;
2553     x->bm_time_next = NULL;
2554     x->bm_time_hash = BW_METER_BUCKETS;
2555
2556     /* Add the new bw_meter entry to the front of entries for this MFC */
2557     x->bm_mfc = mfc;
2558     x->bm_mfc_next = mfc->mfc_bw_meter;
2559     mfc->mfc_bw_meter = x;
2560     schedule_bw_meter(x, &now);
2561     MFC_UNLOCK();
2562
2563     return 0;
2564 }
2565
2566 static void
2567 free_bw_list(struct bw_meter *list)
2568 {
2569     while (list != NULL) {
2570         struct bw_meter *x = list;
2571
2572         list = list->bm_mfc_next;
2573         unschedule_bw_meter(x);
2574         free(x, M_BWMETER);
2575     }
2576 }
2577
2578 /*
2579  * Delete one or multiple bw_meter entries
2580  */
2581 static int
2582 del_bw_upcall(struct bw_upcall *req)
2583 {
2584     struct mfc *mfc;
2585     struct bw_meter *x;
2586
2587     if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2588         return EOPNOTSUPP;
2589
2590     MFC_LOCK();
2591     /* Find the corresponding MFC entry */
2592     mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2593     if (mfc == NULL) {
2594         MFC_UNLOCK();
2595         return EADDRNOTAVAIL;
2596     } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2597         /*
2598          * Delete all bw_meter entries for this mfc
2599          */
2600         struct bw_meter *list;
2601
2602         list = mfc->mfc_bw_meter;
2603         mfc->mfc_bw_meter = NULL;
2604         free_bw_list(list);
2605         MFC_UNLOCK();
2606         return 0;
2607     } else {                    /* Delete a single bw_meter entry */
2608         struct bw_meter *prev;
2609         uint32_t flags = 0;
2610
2611         flags = compute_bw_meter_flags(req);
2612
2613         /* Find the bw_meter entry to delete */
2614         for (prev = NULL, x = mfc->mfc_bw_meter; x != NULL;
2615              prev = x, x = x->bm_mfc_next) {
2616             if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2617                                &req->bu_threshold.b_time, ==)) &&
2618                 (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2619                 (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2620                 (x->bm_flags & BW_METER_USER_FLAGS) == flags)
2621                 break;
2622         }
2623         if (x != NULL) { /* Delete entry from the list for this MFC */
2624             if (prev != NULL)
2625                 prev->bm_mfc_next = x->bm_mfc_next;     /* remove from middle*/
2626             else
2627                 x->bm_mfc->mfc_bw_meter = x->bm_mfc_next;/* new head of list */
2628
2629             unschedule_bw_meter(x);
2630             MFC_UNLOCK();
2631             /* Free the bw_meter entry */
2632             free(x, M_BWMETER);
2633             return 0;
2634         } else {
2635             MFC_UNLOCK();
2636             return EINVAL;
2637         }
2638     }
2639     /* NOTREACHED */
2640 }
2641
2642 /*
2643  * Perform bandwidth measurement processing that may result in an upcall
2644  */
2645 static void
2646 bw_meter_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2647 {
2648     struct timeval delta;
2649
2650     MFC_LOCK_ASSERT();
2651
2652     delta = *nowp;
2653     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2654
2655     if (x->bm_flags & BW_METER_GEQ) {
2656         /*
2657          * Processing for ">=" type of bw_meter entry
2658          */
2659         if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2660             /* Reset the bw_meter entry */
2661             x->bm_start_time = *nowp;
2662             x->bm_measured.b_packets = 0;
2663             x->bm_measured.b_bytes = 0;
2664             x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2665         }
2666
2667         /* Record that a packet is received */
2668         x->bm_measured.b_packets++;
2669         x->bm_measured.b_bytes += plen;
2670
2671         /*
2672          * Test if we should deliver an upcall
2673          */
2674         if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2675             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2676                  (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2677                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2678                  (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2679                 /* Prepare an upcall for delivery */
2680                 bw_meter_prepare_upcall(x, nowp);
2681                 x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2682             }
2683         }
2684     } else if (x->bm_flags & BW_METER_LEQ) {
2685         /*
2686          * Processing for "<=" type of bw_meter entry
2687          */
2688         if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2689             /*
2690              * We are behind time with the multicast forwarding table
2691              * scanning for "<=" type of bw_meter entries, so test now
2692              * if we should deliver an upcall.
2693              */
2694             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2695                  (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2696                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2697                  (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2698                 /* Prepare an upcall for delivery */
2699                 bw_meter_prepare_upcall(x, nowp);
2700             }
2701             /* Reschedule the bw_meter entry */
2702             unschedule_bw_meter(x);
2703             schedule_bw_meter(x, nowp);
2704         }
2705
2706         /* Record that a packet is received */
2707         x->bm_measured.b_packets++;
2708         x->bm_measured.b_bytes += plen;
2709
2710         /*
2711          * Test if we should restart the measuring interval
2712          */
2713         if ((x->bm_flags & BW_METER_UNIT_PACKETS &&
2714              x->bm_measured.b_packets <= x->bm_threshold.b_packets) ||
2715             (x->bm_flags & BW_METER_UNIT_BYTES &&
2716              x->bm_measured.b_bytes <= x->bm_threshold.b_bytes)) {
2717             /* Don't restart the measuring interval */
2718         } else {
2719             /* Do restart the measuring interval */
2720             /*
2721              * XXX: note that we don't unschedule and schedule, because this
2722              * might be too much overhead per packet. Instead, when we process
2723              * all entries for a given timer hash bin, we check whether it is
2724              * really a timeout. If not, we reschedule at that time.
2725              */
2726             x->bm_start_time = *nowp;
2727             x->bm_measured.b_packets = 0;
2728             x->bm_measured.b_bytes = 0;
2729             x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2730         }
2731     }
2732 }
2733
2734 /*
2735  * Prepare a bandwidth-related upcall
2736  */
2737 static void
2738 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2739 {
2740     struct timeval delta;
2741     struct bw_upcall *u;
2742
2743     MFC_LOCK_ASSERT();
2744
2745     /*
2746      * Compute the measured time interval
2747      */
2748     delta = *nowp;
2749     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2750
2751     /*
2752      * If there are too many pending upcalls, deliver them now
2753      */
2754     if (bw_upcalls_n >= BW_UPCALLS_MAX)
2755         bw_upcalls_send();
2756
2757     /*
2758      * Set the bw_upcall entry
2759      */
2760     u = &bw_upcalls[bw_upcalls_n++];
2761     u->bu_src = x->bm_mfc->mfc_origin;
2762     u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2763     u->bu_threshold.b_time = x->bm_threshold.b_time;
2764     u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2765     u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2766     u->bu_measured.b_time = delta;
2767     u->bu_measured.b_packets = x->bm_measured.b_packets;
2768     u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2769     u->bu_flags = 0;
2770     if (x->bm_flags & BW_METER_UNIT_PACKETS)
2771         u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2772     if (x->bm_flags & BW_METER_UNIT_BYTES)
2773         u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2774     if (x->bm_flags & BW_METER_GEQ)
2775         u->bu_flags |= BW_UPCALL_GEQ;
2776     if (x->bm_flags & BW_METER_LEQ)
2777         u->bu_flags |= BW_UPCALL_LEQ;
2778 }
2779
2780 /*
2781  * Send the pending bandwidth-related upcalls
2782  */
2783 static void
2784 bw_upcalls_send(void)
2785 {
2786     struct mbuf *m;
2787     int len = bw_upcalls_n * sizeof(bw_upcalls[0]);
2788     struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2789     static struct igmpmsg igmpmsg = { 0,                /* unused1 */
2790                                       0,                /* unused2 */
2791                                       IGMPMSG_BW_UPCALL,/* im_msgtype */
2792                                       0,                /* im_mbz  */
2793                                       0,                /* im_vif  */
2794                                       0,                /* unused3 */
2795                                       { 0 },            /* im_src  */
2796                                       { 0 } };          /* im_dst  */
2797
2798     MFC_LOCK_ASSERT();
2799
2800     if (bw_upcalls_n == 0)
2801         return;                 /* No pending upcalls */
2802
2803     bw_upcalls_n = 0;
2804
2805     /*
2806      * Allocate a new mbuf, initialize it with the header and
2807      * the payload for the pending calls.
2808      */
2809     MGETHDR(m, M_DONTWAIT, MT_DATA);
2810     if (m == NULL) {
2811         log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2812         return;
2813     }
2814
2815     m->m_len = m->m_pkthdr.len = 0;
2816     m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2817     m_copyback(m, sizeof(struct igmpmsg), len, (caddr_t)&bw_upcalls[0]);
2818
2819     /*
2820      * Send the upcalls
2821      * XXX do we need to set the address in k_igmpsrc ?
2822      */
2823     mrtstat.mrts_upcalls++;
2824     if (socket_send(ip_mrouter, m, &k_igmpsrc) < 0) {
2825         log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2826         ++mrtstat.mrts_upq_sockfull;
2827     }
2828 }
2829
2830 /*
2831  * Compute the timeout hash value for the bw_meter entries
2832  */
2833 #define BW_METER_TIMEHASH(bw_meter, hash)                               \
2834     do {                                                                \
2835         struct timeval next_timeval = (bw_meter)->bm_start_time;        \
2836                                                                         \
2837         BW_TIMEVALADD(&next_timeval, &(bw_meter)->bm_threshold.b_time); \
2838         (hash) = next_timeval.tv_sec;                                   \
2839         if (next_timeval.tv_usec)                                       \
2840             (hash)++; /* XXX: make sure we don't timeout early */       \
2841         (hash) %= BW_METER_BUCKETS;                                     \
2842     } while (0)
2843
2844 /*
2845  * Schedule a timer to process periodically bw_meter entry of type "<="
2846  * by linking the entry in the proper hash bucket.
2847  */
2848 static void
2849 schedule_bw_meter(struct bw_meter *x, struct timeval *nowp)
2850 {
2851     int time_hash;
2852
2853     MFC_LOCK_ASSERT();
2854
2855     if (!(x->bm_flags & BW_METER_LEQ))
2856         return;         /* XXX: we schedule timers only for "<=" entries */
2857
2858     /*
2859      * Reset the bw_meter entry
2860      */
2861     x->bm_start_time = *nowp;
2862     x->bm_measured.b_packets = 0;
2863     x->bm_measured.b_bytes = 0;
2864     x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2865
2866     /*
2867      * Compute the timeout hash value and insert the entry
2868      */
2869     BW_METER_TIMEHASH(x, time_hash);
2870     x->bm_time_next = bw_meter_timers[time_hash];
2871     bw_meter_timers[time_hash] = x;
2872     x->bm_time_hash = time_hash;
2873 }
2874
2875 /*
2876  * Unschedule the periodic timer that processes bw_meter entry of type "<="
2877  * by removing the entry from the proper hash bucket.
2878  */
2879 static void
2880 unschedule_bw_meter(struct bw_meter *x)
2881 {
2882     int time_hash;
2883     struct bw_meter *prev, *tmp;
2884
2885     MFC_LOCK_ASSERT();
2886
2887     if (!(x->bm_flags & BW_METER_LEQ))
2888         return;         /* XXX: we schedule timers only for "<=" entries */
2889
2890     /*
2891      * Compute the timeout hash value and delete the entry
2892      */
2893     time_hash = x->bm_time_hash;
2894     if (time_hash >= BW_METER_BUCKETS)
2895         return;         /* Entry was not scheduled */
2896
2897     for (prev = NULL, tmp = bw_meter_timers[time_hash];
2898              tmp != NULL; prev = tmp, tmp = tmp->bm_time_next)
2899         if (tmp == x)
2900             break;
2901
2902     if (tmp == NULL)
2903         panic("unschedule_bw_meter: bw_meter entry not found");
2904
2905     if (prev != NULL)
2906         prev->bm_time_next = x->bm_time_next;
2907     else
2908         bw_meter_timers[time_hash] = x->bm_time_next;
2909
2910     x->bm_time_next = NULL;
2911     x->bm_time_hash = BW_METER_BUCKETS;
2912 }
2913
2914
2915 /*
2916  * Process all "<=" type of bw_meter that should be processed now,
2917  * and for each entry prepare an upcall if necessary. Each processed
2918  * entry is rescheduled again for the (periodic) processing.
2919  *
2920  * This is run periodically (once per second normally). On each round,
2921  * all the potentially matching entries are in the hash slot that we are
2922  * looking at.
2923  */
2924 static void
2925 bw_meter_process()
2926 {
2927     static uint32_t last_tv_sec;        /* last time we processed this */
2928
2929     uint32_t loops;
2930     int i;
2931     struct timeval now, process_endtime;
2932
2933     GET_TIME(now);
2934     if (last_tv_sec == now.tv_sec)
2935         return;         /* nothing to do */
2936
2937     loops = now.tv_sec - last_tv_sec;
2938     last_tv_sec = now.tv_sec;
2939     if (loops > BW_METER_BUCKETS)
2940         loops = BW_METER_BUCKETS;
2941
2942     MFC_LOCK();
2943     /*
2944      * Process all bins of bw_meter entries from the one after the last
2945      * processed to the current one. On entry, i points to the last bucket
2946      * visited, so we need to increment i at the beginning of the loop.
2947      */
2948     for (i = (now.tv_sec - loops) % BW_METER_BUCKETS; loops > 0; loops--) {
2949         struct bw_meter *x, *tmp_list;
2950
2951         if (++i >= BW_METER_BUCKETS)
2952             i = 0;
2953
2954         /* Disconnect the list of bw_meter entries from the bin */
2955         tmp_list = bw_meter_timers[i];
2956         bw_meter_timers[i] = NULL;
2957
2958         /* Process the list of bw_meter entries */
2959         while (tmp_list != NULL) {
2960             x = tmp_list;
2961             tmp_list = tmp_list->bm_time_next;
2962
2963             /* Test if the time interval is over */
2964             process_endtime = x->bm_start_time;
2965             BW_TIMEVALADD(&process_endtime, &x->bm_threshold.b_time);
2966             if (BW_TIMEVALCMP(&process_endtime, &now, >)) {
2967                 /* Not yet: reschedule, but don't reset */
2968                 int time_hash;
2969
2970                 BW_METER_TIMEHASH(x, time_hash);
2971                 if (time_hash == i && process_endtime.tv_sec == now.tv_sec) {
2972                     /*
2973                      * XXX: somehow the bin processing is a bit ahead of time.
2974                      * Put the entry in the next bin.
2975                      */
2976                     if (++time_hash >= BW_METER_BUCKETS)
2977                         time_hash = 0;
2978                 }
2979                 x->bm_time_next = bw_meter_timers[time_hash];
2980                 bw_meter_timers[time_hash] = x;
2981                 x->bm_time_hash = time_hash;
2982
2983                 continue;
2984             }
2985
2986             /*
2987              * Test if we should deliver an upcall
2988              */
2989             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2990                  (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2991                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2992                  (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2993                 /* Prepare an upcall for delivery */
2994                 bw_meter_prepare_upcall(x, &now);
2995             }
2996
2997             /*
2998              * Reschedule for next processing
2999              */
3000             schedule_bw_meter(x, &now);
3001         }
3002     }
3003
3004     /* Send all upcalls that are pending delivery */
3005     bw_upcalls_send();
3006
3007     MFC_UNLOCK();
3008 }
3009
3010 /*
3011  * A periodic function for sending all upcalls that are pending delivery
3012  */
3013 static void
3014 expire_bw_upcalls_send(void *unused)
3015 {
3016     MFC_LOCK();
3017     bw_upcalls_send();
3018     MFC_UNLOCK();
3019
3020     callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
3021         expire_bw_upcalls_send, NULL);
3022 }
3023
3024 /*
3025  * A periodic function for periodic scanning of the multicast forwarding
3026  * table for processing all "<=" bw_meter entries.
3027  */
3028 static void
3029 expire_bw_meter_process(void *unused)
3030 {
3031     if (mrt_api_config & MRT_MFC_BW_UPCALL)
3032         bw_meter_process();
3033
3034     callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
3035 }
3036
3037 /*
3038  * End of bandwidth monitoring code
3039  */
3040
3041 #ifdef PIM
3042 /*
3043  * Send the packet up to the user daemon, or eventually do kernel encapsulation
3044  *
3045  */
3046 static int
3047 pim_register_send(struct ip *ip, struct vif *vifp,
3048         struct mbuf *m, struct mfc *rt)
3049 {
3050     struct mbuf *mb_copy, *mm;
3051
3052     if (mrtdebug & DEBUG_PIM)
3053         log(LOG_DEBUG, "pim_register_send: ");
3054
3055     mb_copy = pim_register_prepare(ip, m);
3056     if (mb_copy == NULL)
3057         return ENOBUFS;
3058
3059     /*
3060      * Send all the fragments. Note that the mbuf for each fragment
3061      * is freed by the sending machinery.
3062      */
3063     for (mm = mb_copy; mm; mm = mb_copy) {
3064         mb_copy = mm->m_nextpkt;
3065         mm->m_nextpkt = 0;
3066         mm = m_pullup(mm, sizeof(struct ip));
3067         if (mm != NULL) {
3068             ip = mtod(mm, struct ip *);
3069             if ((mrt_api_config & MRT_MFC_RP) &&
3070                 (rt->mfc_rp.s_addr != INADDR_ANY)) {
3071                 pim_register_send_rp(ip, vifp, mm, rt);
3072             } else {
3073                 pim_register_send_upcall(ip, vifp, mm, rt);
3074             }
3075         }
3076     }
3077
3078     return 0;
3079 }
3080
3081 /*
3082  * Return a copy of the data packet that is ready for PIM Register
3083  * encapsulation.
3084  * XXX: Note that in the returned copy the IP header is a valid one.
3085  */
3086 static struct mbuf *
3087 pim_register_prepare(struct ip *ip, struct mbuf *m)
3088 {
3089     struct mbuf *mb_copy = NULL;
3090     int mtu;
3091
3092     /* Take care of delayed checksums */
3093     if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
3094         in_delayed_cksum(m);
3095         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
3096     }
3097
3098     /*
3099      * Copy the old packet & pullup its IP header into the
3100      * new mbuf so we can modify it.
3101      */
3102     mb_copy = m_copypacket(m, M_DONTWAIT);
3103     if (mb_copy == NULL)
3104         return NULL;
3105     mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
3106     if (mb_copy == NULL)
3107         return NULL;
3108
3109     /* take care of the TTL */
3110     ip = mtod(mb_copy, struct ip *);
3111     --ip->ip_ttl;
3112
3113     /* Compute the MTU after the PIM Register encapsulation */
3114     mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
3115
3116     if (ip->ip_len <= mtu) {
3117         /* Turn the IP header into a valid one */
3118         ip->ip_len = htons(ip->ip_len);
3119         ip->ip_off = htons(ip->ip_off);
3120         ip->ip_sum = 0;
3121         ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
3122     } else {
3123         /* Fragment the packet */
3124         if (ip_fragment(ip, &mb_copy, mtu, 0, CSUM_DELAY_IP) != 0) {
3125             m_freem(mb_copy);
3126             return NULL;
3127         }
3128     }
3129     return mb_copy;
3130 }
3131
3132 /*
3133  * Send an upcall with the data packet to the user-level process.
3134  */
3135 static int
3136 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
3137         struct mbuf *mb_copy, struct mfc *rt)
3138 {
3139     struct mbuf *mb_first;
3140     int len = ntohs(ip->ip_len);
3141     struct igmpmsg *im;
3142     struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
3143
3144     VIF_LOCK_ASSERT();
3145
3146     /*
3147      * Add a new mbuf with an upcall header
3148      */
3149     MGETHDR(mb_first, M_DONTWAIT, MT_DATA);
3150     if (mb_first == NULL) {
3151         m_freem(mb_copy);
3152         return ENOBUFS;
3153     }
3154     mb_first->m_data += max_linkhdr;
3155     mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
3156     mb_first->m_len = sizeof(struct igmpmsg);
3157     mb_first->m_next = mb_copy;
3158
3159     /* Send message to routing daemon */
3160     im = mtod(mb_first, struct igmpmsg *);
3161     im->im_msgtype      = IGMPMSG_WHOLEPKT;
3162     im->im_mbz          = 0;
3163     im->im_vif          = vifp - viftable;
3164     im->im_src          = ip->ip_src;
3165     im->im_dst          = ip->ip_dst;
3166
3167     k_igmpsrc.sin_addr  = ip->ip_src;
3168
3169     mrtstat.mrts_upcalls++;
3170
3171     if (socket_send(ip_mrouter, mb_first, &k_igmpsrc) < 0) {
3172         if (mrtdebug & DEBUG_PIM)
3173             log(LOG_WARNING,
3174                 "mcast: pim_register_send_upcall: ip_mrouter socket queue full");
3175         ++mrtstat.mrts_upq_sockfull;
3176         return ENOBUFS;
3177     }
3178
3179     /* Keep statistics */
3180     pimstat.pims_snd_registers_msgs++;
3181     pimstat.pims_snd_registers_bytes += len;
3182
3183     return 0;
3184 }
3185
3186 /*
3187  * Encapsulate the data packet in PIM Register message and send it to the RP.
3188  */
3189 static int
3190 pim_register_send_rp(struct ip *ip, struct vif *vifp,
3191         struct mbuf *mb_copy, struct mfc *rt)
3192 {
3193     struct mbuf *mb_first;
3194     struct ip *ip_outer;
3195     struct pim_encap_pimhdr *pimhdr;
3196     int len = ntohs(ip->ip_len);
3197     vifi_t vifi = rt->mfc_parent;
3198
3199     VIF_LOCK_ASSERT();
3200
3201     if ((vifi >= numvifs) || (viftable[vifi].v_lcl_addr.s_addr == 0)) {
3202         m_freem(mb_copy);
3203         return EADDRNOTAVAIL;           /* The iif vif is invalid */
3204     }
3205
3206     /*
3207      * Add a new mbuf with the encapsulating header
3208      */
3209     MGETHDR(mb_first, M_DONTWAIT, MT_DATA);
3210     if (mb_first == NULL) {
3211         m_freem(mb_copy);
3212         return ENOBUFS;
3213     }
3214     mb_first->m_data += max_linkhdr;
3215     mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
3216     mb_first->m_next = mb_copy;
3217
3218     mb_first->m_pkthdr.len = len + mb_first->m_len;
3219
3220     /*
3221      * Fill in the encapsulating IP and PIM header
3222      */
3223     ip_outer = mtod(mb_first, struct ip *);
3224     *ip_outer = pim_encap_iphdr;
3225     ip_outer->ip_id = ip_newid();
3226     ip_outer->ip_len = len + sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
3227     ip_outer->ip_src = viftable[vifi].v_lcl_addr;
3228     ip_outer->ip_dst = rt->mfc_rp;
3229     /*
3230      * Copy the inner header TOS to the outer header, and take care of the
3231      * IP_DF bit.
3232      */
3233     ip_outer->ip_tos = ip->ip_tos;
3234     if (ntohs(ip->ip_off) & IP_DF)
3235         ip_outer->ip_off |= IP_DF;
3236     pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
3237                                          + sizeof(pim_encap_iphdr));
3238     *pimhdr = pim_encap_pimhdr;
3239     /* If the iif crosses a border, set the Border-bit */
3240     if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & mrt_api_config)
3241         pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
3242
3243     mb_first->m_data += sizeof(pim_encap_iphdr);
3244     pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
3245     mb_first->m_data -= sizeof(pim_encap_iphdr);
3246
3247     if (vifp->v_rate_limit == 0)
3248         tbf_send_packet(vifp, mb_first);
3249     else
3250         tbf_control(vifp, mb_first, ip, ip_outer->ip_len);
3251
3252     /* Keep statistics */
3253     pimstat.pims_snd_registers_msgs++;
3254     pimstat.pims_snd_registers_bytes += len;
3255
3256     return 0;
3257 }
3258
3259 /*
3260  * PIM-SMv2 and PIM-DM messages processing.
3261  * Receives and verifies the PIM control messages, and passes them
3262  * up to the listening socket, using rip_input().
3263  * The only message with special processing is the PIM_REGISTER message
3264  * (used by PIM-SM): the PIM header is stripped off, and the inner packet
3265  * is passed to if_simloop().
3266  */
3267 void
3268 pim_input(struct mbuf *m, int off)
3269 {
3270     struct ip *ip = mtod(m, struct ip *);
3271     struct pim *pim;
3272     int minlen;
3273     int datalen = ip->ip_len;
3274     int ip_tos;
3275     int iphlen = off;
3276
3277     /* Keep statistics */
3278     pimstat.pims_rcv_total_msgs++;
3279     pimstat.pims_rcv_total_bytes += datalen;
3280
3281     /*
3282      * Validate lengths
3283      */
3284     if (datalen < PIM_MINLEN) {
3285         pimstat.pims_rcv_tooshort++;
3286         log(LOG_ERR, "pim_input: packet size too small %d from %lx\n",
3287             datalen, (u_long)ip->ip_src.s_addr);
3288         m_freem(m);
3289         return;
3290     }
3291
3292     /*
3293      * If the packet is at least as big as a REGISTER, go agead
3294      * and grab the PIM REGISTER header size, to avoid another
3295      * possible m_pullup() later.
3296      *
3297      * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
3298      * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
3299      */
3300     minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
3301     /*
3302      * Get the IP and PIM headers in contiguous memory, and
3303      * possibly the PIM REGISTER header.
3304      */
3305     if ((m->m_flags & M_EXT || m->m_len < minlen) &&
3306         (m = m_pullup(m, minlen)) == 0) {
3307         log(LOG_ERR, "pim_input: m_pullup failure\n");
3308         return;
3309     }
3310     /* m_pullup() may have given us a new mbuf so reset ip. */
3311     ip = mtod(m, struct ip *);
3312     ip_tos = ip->ip_tos;
3313
3314     /* adjust mbuf to point to the PIM header */
3315     m->m_data += iphlen;
3316     m->m_len  -= iphlen;
3317     pim = mtod(m, struct pim *);
3318
3319     /*
3320      * Validate checksum. If PIM REGISTER, exclude the data packet.
3321      *
3322      * XXX: some older PIMv2 implementations don't make this distinction,
3323      * so for compatibility reason perform the checksum over part of the
3324      * message, and if error, then over the whole message.
3325      */
3326     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
3327         /* do nothing, checksum okay */
3328     } else if (in_cksum(m, datalen)) {
3329         pimstat.pims_rcv_badsum++;
3330         if (mrtdebug & DEBUG_PIM)
3331             log(LOG_DEBUG, "pim_input: invalid checksum");
3332         m_freem(m);
3333         return;
3334     }
3335
3336     /* PIM version check */
3337     if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
3338         pimstat.pims_rcv_badversion++;
3339         log(LOG_ERR, "pim_input: incorrect version %d, expecting %d\n",
3340             PIM_VT_V(pim->pim_vt), PIM_VERSION);
3341         m_freem(m);
3342         return;
3343     }
3344
3345     /* restore mbuf back to the outer IP */
3346     m->m_data -= iphlen;
3347     m->m_len  += iphlen;
3348
3349     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
3350         /*
3351          * Since this is a REGISTER, we'll make a copy of the register
3352          * headers ip + pim + u_int32 + encap_ip, to be passed up to the
3353          * routing daemon.
3354          */
3355         struct sockaddr_in dst = { sizeof(dst), AF_INET };
3356         struct mbuf *mcp;
3357         struct ip *encap_ip;
3358         u_int32_t *reghdr;
3359         struct ifnet *vifp;
3360
3361         VIF_LOCK();
3362         if ((reg_vif_num >= numvifs) || (reg_vif_num == VIFI_INVALID)) {
3363             VIF_UNLOCK();
3364             if (mrtdebug & DEBUG_PIM)
3365                 log(LOG_DEBUG,
3366                     "pim_input: register vif not set: %d\n", reg_vif_num);
3367             m_freem(m);
3368             return;
3369         }
3370         /* XXX need refcnt? */
3371         vifp = viftable[reg_vif_num].v_ifp;
3372         VIF_UNLOCK();
3373
3374         /*
3375          * Validate length
3376          */
3377         if (datalen < PIM_REG_MINLEN) {
3378             pimstat.pims_rcv_tooshort++;
3379             pimstat.pims_rcv_badregisters++;
3380             log(LOG_ERR,
3381                 "pim_input: register packet size too small %d from %lx\n",
3382                 datalen, (u_long)ip->ip_src.s_addr);
3383             m_freem(m);
3384             return;
3385         }
3386
3387         reghdr = (u_int32_t *)(pim + 1);
3388         encap_ip = (struct ip *)(reghdr + 1);
3389
3390         if (mrtdebug & DEBUG_PIM) {
3391             log(LOG_DEBUG,
3392                 "pim_input[register], encap_ip: %lx -> %lx, encap_ip len %d\n",
3393                 (u_long)ntohl(encap_ip->ip_src.s_addr),
3394                 (u_long)ntohl(encap_ip->ip_dst.s_addr),
3395                 ntohs(encap_ip->ip_len));
3396         }
3397
3398         /* verify the version number of the inner packet */
3399         if (encap_ip->ip_v != IPVERSION) {
3400             pimstat.pims_rcv_badregisters++;
3401             if (mrtdebug & DEBUG_PIM) {
3402                 log(LOG_DEBUG, "pim_input: invalid IP version (%d) "
3403                     "of the inner packet\n", encap_ip->ip_v);
3404             }
3405             m_freem(m);
3406             return;
3407         }
3408
3409         /* verify the inner packet is destined to a mcast group */
3410         if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
3411             pimstat.pims_rcv_badregisters++;
3412             if (mrtdebug & DEBUG_PIM)
3413                 log(LOG_DEBUG,
3414                     "pim_input: inner packet of register is not "
3415                     "multicast %lx\n",
3416                     (u_long)ntohl(encap_ip->ip_dst.s_addr));
3417             m_freem(m);
3418             return;
3419         }
3420
3421         /* If a NULL_REGISTER, pass it to the daemon */
3422         if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
3423             goto pim_input_to_daemon;
3424
3425         /*
3426          * Copy the TOS from the outer IP header to the inner IP header.
3427          */
3428         if (encap_ip->ip_tos != ip_tos) {
3429             /* Outer TOS -> inner TOS */
3430             encap_ip->ip_tos = ip_tos;
3431             /* Recompute the inner header checksum. Sigh... */
3432
3433             /* adjust mbuf to point to the inner IP header */
3434             m->m_data += (iphlen + PIM_MINLEN);
3435             m->m_len  -= (iphlen + PIM_MINLEN);
3436
3437             encap_ip->ip_sum = 0;
3438             encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
3439
3440             /* restore mbuf to point back to the outer IP header */
3441             m->m_data -= (iphlen + PIM_MINLEN);
3442             m->m_len  += (iphlen + PIM_MINLEN);
3443         }
3444
3445         /*
3446          * Decapsulate the inner IP packet and loopback to forward it
3447          * as a normal multicast packet. Also, make a copy of the
3448          *     outer_iphdr + pimhdr + reghdr + encap_iphdr
3449          * to pass to the daemon later, so it can take the appropriate
3450          * actions (e.g., send back PIM_REGISTER_STOP).
3451          * XXX: here m->m_data points to the outer IP header.
3452          */
3453         mcp = m_copy(m, 0, iphlen + PIM_REG_MINLEN);
3454         if (mcp == NULL) {
3455             log(LOG_ERR,
3456                 "pim_input: pim register: could not copy register head\n");
3457             m_freem(m);
3458             return;
3459         }
3460
3461         /* Keep statistics */
3462         /* XXX: registers_bytes include only the encap. mcast pkt */
3463         pimstat.pims_rcv_registers_msgs++;
3464         pimstat.pims_rcv_registers_bytes += ntohs(encap_ip->ip_len);
3465
3466         /*
3467          * forward the inner ip packet; point m_data at the inner ip.
3468          */
3469         m_adj(m, iphlen + PIM_MINLEN);
3470
3471         if (mrtdebug & DEBUG_PIM) {
3472             log(LOG_DEBUG,
3473                 "pim_input: forwarding decapsulated register: "
3474                 "src %lx, dst %lx, vif %d\n",
3475                 (u_long)ntohl(encap_ip->ip_src.s_addr),
3476                 (u_long)ntohl(encap_ip->ip_dst.s_addr),
3477                 reg_vif_num);
3478         }
3479         /* NB: vifp was collected above; can it change on us? */
3480         if_simloop(vifp, m, dst.sin_family, 0);
3481
3482         /* prepare the register head to send to the mrouting daemon */
3483         m = mcp;
3484     }
3485
3486 pim_input_to_daemon:
3487     /*
3488      * Pass the PIM message up to the daemon; if it is a Register message,
3489      * pass the 'head' only up to the daemon. This includes the
3490      * outer IP header, PIM header, PIM-Register header and the
3491      * inner IP header.
3492      * XXX: the outer IP header pkt size of a Register is not adjust to
3493      * reflect the fact that the inner multicast data is truncated.
3494      */
3495     rip_input(m, iphlen);
3496
3497     return;
3498 }
3499 #endif /* PIM */
3500
3501 static int
3502 ip_mroute_modevent(module_t mod, int type, void *unused)
3503 {
3504     switch (type) {
3505     case MOD_LOAD:
3506         mtx_init(&mrouter_mtx, "mrouter initialization", NULL, MTX_DEF);
3507         MFC_LOCK_INIT();
3508         VIF_LOCK_INIT();
3509         ip_mrouter_reset();
3510         ip_mcast_src = X_ip_mcast_src;
3511         ip_mforward = X_ip_mforward;
3512         ip_mrouter_done = X_ip_mrouter_done;
3513         ip_mrouter_get = X_ip_mrouter_get;
3514         ip_mrouter_set = X_ip_mrouter_set;
3515         ip_rsvp_force_done = X_ip_rsvp_force_done;
3516         ip_rsvp_vif = X_ip_rsvp_vif;
3517         legal_vif_num = X_legal_vif_num;
3518         mrt_ioctl = X_mrt_ioctl;
3519         rsvp_input_p = X_rsvp_input;
3520         break;
3521
3522     case MOD_UNLOAD:
3523         /*
3524          * Typically module unload happens after the user-level
3525          * process has shutdown the kernel services (the check
3526          * below insures someone can't just yank the module out
3527          * from under a running process).  But if the module is
3528          * just loaded and then unloaded w/o starting up a user
3529          * process we still need to cleanup.
3530          */
3531         if (ip_mrouter)
3532             return EINVAL;
3533
3534         X_ip_mrouter_done();
3535         ip_mcast_src = NULL;
3536         ip_mforward = NULL;
3537         ip_mrouter_done = NULL;
3538         ip_mrouter_get = NULL;
3539         ip_mrouter_set = NULL;
3540         ip_rsvp_force_done = NULL;
3541         ip_rsvp_vif = NULL;
3542         legal_vif_num = NULL;
3543         mrt_ioctl = NULL;
3544         rsvp_input_p = NULL;
3545         VIF_LOCK_DESTROY();
3546         MFC_LOCK_DESTROY();
3547         mtx_destroy(&mrouter_mtx);
3548         break;
3549     default:
3550         return EOPNOTSUPP;
3551     }
3552     return 0;
3553 }
3554
3555 static moduledata_t ip_mroutemod = {
3556     "ip_mroute",
3557     ip_mroute_modevent,
3558     0
3559 };
3560 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PSEUDO, SI_ORDER_ANY);