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