Change mbug allocation flags from M_ to MB_ to avoid confusion with malloc
[dragonfly.git] / sys / net / oldbridge / bridge.c
1 /*
2  * Copyright (c) 1998-2002 Luigi Rizzo
3  *
4  * Work partly supported by: Cisco Systems, Inc. - NSITE lab, RTP, NC
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: src/sys/net/bridge.c,v 1.16.2.25 2003/01/23 21:06:44 sam Exp $
28  * $DragonFly: src/sys/net/oldbridge/Attic/bridge.c,v 1.8 2004/06/02 14:42:58 eirikn Exp $
29  */
30
31 /*
32  * This code implements bridging in FreeBSD. It only acts on ethernet
33  * interfaces, including VLANs (others are still usable for routing).
34  * A FreeBSD host can implement multiple logical bridges, called
35  * "clusters". Each cluster is made of a set of interfaces, and
36  * identified by a "cluster-id" which is a number in the range 1..2^16-1.
37  *
38  * Bridging is enabled by the sysctl variable
39  *      net.link.ether.bridge
40  * the grouping of interfaces into clusters is done with
41  *      net.link.ether.bridge_cfg
42  * containing a list of interfaces each optionally followed by
43  * a colon and the cluster it belongs to (1 is the default).
44  * Separators can be * spaces, commas or tabs, e.g.
45  *      net.link.ether.bridge_cfg="fxp0:2 fxp1:2 dc0 dc1:1"
46  * Optionally bridged packets can be passed through the firewall,
47  * this is controlled by the variable
48  *      net.link.ether.bridge_ipfw
49  *
50  * For each cluster there is a descriptor (cluster_softc) storing
51  * the following data structures:
52  * - a hash table with the MAC address and destination interface for each
53  *   known node. The table is indexed using a hash of the source address.
54  * - an array with the MAC addresses of the interfaces used in the cluster.
55  *
56  * Input packets are tapped near the beginning of ether_input(), and
57  * analysed by bridge_in(). Depending on the result, the packet
58  * can be forwarded to one or more output interfaces using bdg_forward(),
59  * and/or sent to the upper layer (e.g. in case of multicast).
60  *
61  * Output packets are intercepted near the end of ether_output().
62  * The correct destination is selected by bridge_dst_lookup(),
63  * and then forwarding is done by bdg_forward().
64  *
65  * The arp code is also modified to let a machine answer to requests
66  * irrespective of the port the request came from.
67  *
68  * In case of loops in the bridging topology, the bridge detects this
69  * event and temporarily mutes output bridging on one of the ports.
70  * Periodically, interfaces are unmuted by bdg_timeout().
71  * Muting is only implemented as a safety measure, and also as
72  * a mechanism to support a user-space implementation of the spanning
73  * tree algorithm.
74  *
75  * To build a bridging kernel, use the following option
76  *    option BRIDGE
77  * and then at runtime set the sysctl variable to enable bridging.
78  *
79  * Only one interface per cluster is supposed to have addresses set (but
80  * there are no substantial problems if you set addresses for none or
81  * for more than one interface).
82  * Bridging will act before routing, but nothing prevents a machine
83  * from doing both (modulo bugs in the implementation...).
84  *
85  * THINGS TO REMEMBER
86  *  - bridging is incompatible with multicast routing on the same
87  *    machine. There is not an easy fix to this.
88  *  - be very careful when bridging VLANs
89  *  - loop detection is still not very robust.
90  */
91
92 #include <sys/param.h>
93 #include <sys/mbuf.h>
94 #include <sys/malloc.h>
95 #include <sys/systm.h>
96 #include <sys/socket.h> /* for net/if.h */
97 #include <sys/ctype.h>  /* string functions */
98 #include <sys/kernel.h>
99 #include <sys/sysctl.h>
100
101 #include <net/if.h>
102 #include <net/if_types.h>
103 #include <net/if_var.h>
104
105 #include <netinet/in.h> /* for struct arpcom */
106 #include <netinet/in_systm.h>
107 #include <netinet/in_var.h>
108 #include <netinet/ip.h>
109 #include <netinet/if_ether.h> /* for struct arpcom */
110
111 #include <net/route.h>
112 #include <net/ipfw/ip_fw.h>
113 #include <net/dummynet/ip_dummynet.h>
114 #include "bridge.h"
115
116 /*--------------------*/
117
118 /*
119  * For each cluster, source MAC addresses are stored into a hash
120  * table which locates the port they reside on.
121  */
122 #define HASH_SIZE 8192  /* Table size, must be a power of 2 */
123
124 typedef struct hash_table {             /* each entry.          */
125     struct ifnet *      name;
126     u_char              etheraddr[6];
127     u_int16_t           used;           /* also, padding        */
128 } bdg_hash_table ;
129
130 /*
131  * The hash function applied to MAC addresses. Out of the 6 bytes,
132  * the last ones tend to vary more. Since we are on a little endian machine,
133  * we have to do some gimmick...
134  */
135 #define HASH_FN(addr)   (       \
136     ntohs( ((u_int16_t *)addr)[1] ^ ((u_int16_t *)addr)[2] ) & (HASH_SIZE -1))
137
138 /*
139  * This is the data structure where local addresses are stored.
140  */
141 struct bdg_addr {
142     u_char      etheraddr[6] ;
143     u_int16_t   _padding ;
144 };
145
146 /*
147  * The configuration of each cluster includes the cluster id, a pointer to
148  * the hash table, and an array of local MAC addresses (of size "ports").
149  */
150 struct cluster_softc {
151     u_int16_t   cluster_id;
152     u_int16_t   ports;
153     bdg_hash_table *ht;
154     struct bdg_addr     *my_macs;       /* local MAC addresses */
155 };
156
157
158 extern struct protosw inetsw[];                 /* from netinet/ip_input.c */
159 extern u_char ip_protox[];                      /* from netinet/ip_input.c */
160
161 static int n_clusters;                          /* number of clusters */
162 static struct cluster_softc *clusters;
163
164 #define BDG_MUTED(ifp) (ifp2sc[ifp->if_index].flags & IFF_MUTE)
165 #define BDG_MUTE(ifp) ifp2sc[ifp->if_index].flags |= IFF_MUTE
166 #define BDG_CLUSTER(ifp) (ifp2sc[ifp->if_index].cluster)
167
168 #define BDG_SAMECLUSTER(ifp,src) \
169         (src == NULL || BDG_CLUSTER(ifp) == BDG_CLUSTER(src) )
170
171 #ifdef __i386__
172 #define BDG_MATCH(a,b) ( \
173     ((u_int16_t *)(a))[2] == ((u_int16_t *)(b))[2] && \
174     *((u_int32_t *)(a)) == *((u_int32_t *)(b)) )
175 #define IS_ETHER_BROADCAST(a) ( \
176         *((u_int32_t *)(a)) == 0xffffffff && \
177         ((u_int16_t *)(a))[2] == 0xffff )
178 #else
179 /* for machines that do not support unaligned access */
180 #define BDG_MATCH(a,b)          (!bcmp(a, b, ETHER_ADDR_LEN) )
181 #define IS_ETHER_BROADCAST(a)   (!bcmp(a, "\377\377\377\377\377\377", 6))
182 #endif
183
184
185 /*
186  * For timing-related debugging, you can use the following macros.
187  * remember, rdtsc() only works on Pentium-class machines
188
189     quad_t ticks;
190     DDB(ticks = rdtsc();)
191     ... interesting code ...
192     DDB(bdg_fw_ticks += (u_long)(rdtsc() - ticks) ; bdg_fw_count++ ;)
193
194  *
195  */
196
197 #define DDB(x) x
198 #define DEB(x)
199
200 static int bdginit(void);
201 static void parse_bdg_cfg(void);
202
203 static int bdg_ipf;             /* IPFilter enabled in bridge */
204 static int bdg_ipfw;
205
206 /*
207  * For IPFilter, declared in ip_input.c
208  */
209 extern int (*fr_checkp)(struct ip *, int, struct ifnet *, int, struct mbuf **);
210
211 #if 0 /* debugging only */
212 static char *bdg_dst_names[] = {
213         "BDG_NULL    ",
214         "BDG_BCAST   ",
215         "BDG_MCAST   ",
216         "BDG_LOCAL   ",
217         "BDG_DROP    ",
218         "BDG_UNKNOWN ",
219         "BDG_IN      ",
220         "BDG_OUT     ",
221         "BDG_FORWARD " };
222 #endif
223 /*
224  * System initialization
225  */
226
227 static struct bdg_stats bdg_stats ;
228 static struct callout_handle bdg_timeout_h ;
229
230 /*
231  * Add an interface to a cluster, possibly creating a new entry in
232  * the cluster table. This requires reallocation of the table and
233  * updating pointers in ifp2sc.
234  */
235 static struct cluster_softc *
236 add_cluster(u_int16_t cluster_id, struct arpcom *ac)
237 {
238     struct cluster_softc *c = NULL;
239     int i;
240
241     for (i = 0; i < n_clusters ; i++)
242         if (clusters[i].cluster_id == cluster_id)
243             goto found;
244
245     /* Not found, need to reallocate */
246     c = malloc((1+n_clusters) * sizeof (*c), M_IFADDR, M_WAITOK | M_ZERO);
247     c[n_clusters].ht = malloc(HASH_SIZE * sizeof(struct hash_table),
248                                 M_IFADDR, M_WAITOK | M_ZERO);
249     c[n_clusters].my_macs = malloc(BDG_MAX_PORTS * sizeof(struct bdg_addr),
250                                 M_IFADDR, M_WAITOK | M_ZERO);
251
252     c[n_clusters].cluster_id = cluster_id;
253     c[n_clusters].ports = 0;
254     /*
255      * now copy old descriptors here
256      */
257     if (n_clusters > 0) {
258         for (i=0; i < n_clusters; i++)
259             c[i] = clusters[i];
260         /*
261          * and finally update pointers in ifp2sc
262          */
263         for (i = 0 ; i < if_index && i < BDG_MAX_PORTS; i++)
264             if (ifp2sc[i].cluster != NULL)
265                 ifp2sc[i].cluster = c + (ifp2sc[i].cluster - clusters);
266         free(clusters, M_IFADDR);
267     }
268     clusters = c;
269     i = n_clusters;             /* index of cluster entry */
270     n_clusters++;
271 found:
272     c = clusters + i;           /* the right cluster ... */
273     bcopy(ac->ac_enaddr, &(c->my_macs[c->ports]), 6);
274     c->ports++;
275     return c;
276 }
277
278
279 /*
280  * Turn off bridging, by clearing promisc mode on the interface,
281  * marking the interface as unused, and clearing the name in the
282  * stats entry.
283  * Also dispose the hash tables associated with the clusters.
284  */
285 static void
286 bridge_off(void)
287 {
288     struct ifnet *ifp ;
289     int i, s;
290
291     DEB(printf("bridge_off: n_clusters %d\n", n_clusters);)
292     TAILQ_FOREACH(ifp, &ifnet, if_link) {
293         struct bdg_softc *b;
294
295         if (ifp->if_index >= BDG_MAX_PORTS)
296             continue;   /* make sure we do not go beyond the end */
297         b = &(ifp2sc[ifp->if_index]);
298
299         if ( b->flags & IFF_BDG_PROMISC ) {
300             s = splimp();
301             ifpromisc(ifp, 0);
302             splx(s);
303             b->flags &= ~(IFF_BDG_PROMISC|IFF_MUTE) ;
304             DEB(printf(">> now %s promisc OFF if_flags 0x%x bdg_flags 0x%x\n",
305                     ifp->if_xname,
306                     ifp->if_flags, b->flags);)
307         }
308         b->flags &= ~(IFF_USED) ;
309         b->cluster = NULL;
310         bdg_stats.s[ifp->if_index].name[0] = '\0';
311     }
312     /* flush_tables */
313
314     s = splimp();
315     for (i=0; i < n_clusters; i++) {
316         free(clusters[i].ht, M_IFADDR);
317         free(clusters[i].my_macs, M_IFADDR);
318     }
319     if (clusters != NULL)
320         free(clusters, M_IFADDR);
321     clusters = NULL;
322     n_clusters =0;
323     splx(s);
324 }
325
326 /*
327  * set promisc mode on the interfaces we use.
328  */
329 static void
330 bridge_on(void)
331 {
332     struct ifnet *ifp ;
333     int s ;
334
335     TAILQ_FOREACH(ifp, &ifnet, if_link) {
336         struct bdg_softc *b = &ifp2sc[ifp->if_index];
337
338         if ( !(b->flags & IFF_USED) )
339             continue ;
340         if ( !( ifp->if_flags & IFF_UP) ) {
341             s = splimp();
342             if_up(ifp);
343             splx(s);
344         }
345         if ( !(b->flags & IFF_BDG_PROMISC) ) {
346             int ret ;
347             s = splimp();
348             ret = ifpromisc(ifp, 1);
349             splx(s);
350             b->flags |= IFF_BDG_PROMISC ;
351             DEB(printf(">> now %s promisc ON if_flags 0x%x bdg_flags 0x%x\n",
352                     ifp->if_xname,
353                     ifp->if_flags, b->flags);)
354         }
355         if (b->flags & IFF_MUTE) {
356             DEB(printf(">> unmuting %s\n", ifp->if_xname);)
357             b->flags &= ~IFF_MUTE;
358         }
359     }
360 }
361
362 /**
363  * reconfigure bridge.
364  * This is also done every time we attach or detach an interface.
365  * Main use is to make sure that we do not bridge on some old
366  * (ejected) device. So, it would be really useful to have a
367  * pointer to the modified device as an argument. Without it, we
368  * have to scan all interfaces.
369  */
370 static void
371 reconfigure_bridge(void)
372 {
373     bridge_off();
374     if (do_bridge) {
375         if (if_index >= BDG_MAX_PORTS) {
376             printf("-- sorry too many interfaces (%d, max is %d),"
377                 " disabling bridging\n", if_index, BDG_MAX_PORTS);
378             do_bridge=0;
379             return;
380         }
381         parse_bdg_cfg();
382         bridge_on();
383     }
384 }
385
386 static char bridge_cfg[1024]; /* in BSS so initialized to all NULs */
387
388 /*
389  * parse the config string, set IFF_USED, name and cluster_id
390  * for all interfaces found.
391  * The config string is a list of "if[:cluster]" with
392  * a number of possible separators (see "sep"). In particular the
393  * use of the space lets you set bridge_cfg with the output from
394  * "ifconfig -l"
395  */
396 static void
397 parse_bdg_cfg()
398 {
399     char *p, *beg ;
400     int l, cluster;
401     static char *sep = ", \t";
402
403     for (p = bridge_cfg; *p ; p++) {
404         struct ifnet *ifp;
405         int found = 0;
406         char c;
407
408         if (index(sep, *p))     /* skip separators */
409             continue ;
410         /* names are lowercase and digits */
411         for ( beg = p ; islower(*p) || isdigit(*p) ; p++ )
412             ;
413         l = p - beg ;           /* length of name string */
414         if (l == 0)             /* invalid name */
415             break ;
416         if ( *p != ':' )        /* no ':', assume default cluster 1 */
417             cluster = 1 ;
418         else                    /* fetch cluster */
419             cluster = strtoul( p+1, &p, 10);
420         c = *p;
421         *p = '\0';
422         /*
423          * now search in interface list for a matching name
424          */
425         TAILQ_FOREACH(ifp, &ifnet, if_link) {
426             char buf[IFNAMSIZ];
427
428             snprintf(buf, sizeof(buf), "%s", ifp->if_xname);
429             if (!strncmp(beg, buf, max(l, strlen(buf)))) {
430                 struct bdg_softc *b = &ifp2sc[ifp->if_index];
431                 if (ifp->if_type != IFT_ETHER && ifp->if_type != IFT_L2VLAN) {
432                     printf("%s is not an ethernet, continue\n", buf);
433                     continue;
434                 }
435                 if (b->flags & IFF_USED) {
436                     printf("%s already used, skipping\n", buf);
437                     break;
438                 }
439                 b->cluster = add_cluster(htons(cluster), (struct arpcom *)ifp);
440                 b->flags |= IFF_USED ;
441                 sprintf(bdg_stats.s[ifp->if_index].name,
442                         "%s:%d", ifp->if_xname, cluster);
443
444                 DEB(printf("--++  found %s next c %d\n",
445                     bdg_stats.s[ifp->if_index].name, c);)
446                 found = 1;
447                 break ;
448             }
449         }
450         if (!found)
451             printf("interface %s Not found in bridge\n", beg);
452         *p = c;
453         if (c == '\0')
454             break; /* no more */
455     }
456 }
457
458
459 /*
460  * handler for net.link.ether.bridge
461  */
462 static int
463 sysctl_bdg(SYSCTL_HANDLER_ARGS)
464 {
465     int error, oldval = do_bridge ;
466
467     error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
468     DEB( printf("called sysctl for bridge name %s arg2 %d val %d->%d\n",
469         oidp->oid_name, oidp->oid_arg2,
470         oldval, do_bridge); )
471
472     if (oldval != do_bridge)
473         reconfigure_bridge();
474     return error ;
475 }
476
477 /*
478  * handler for net.link.ether.bridge_cfg
479  */
480 static int
481 sysctl_bdg_cfg(SYSCTL_HANDLER_ARGS)
482 {
483     int error = 0 ;
484     char old_cfg[1024] ;
485
486     strcpy(old_cfg, bridge_cfg) ;
487
488     error = sysctl_handle_string(oidp, bridge_cfg, oidp->oid_arg2, req);
489     DEB(
490         printf("called sysctl for bridge name %s arg2 %d err %d val %s->%s\n",
491                 oidp->oid_name, oidp->oid_arg2,
492                 error,
493                 old_cfg, bridge_cfg);
494         )
495     if (strcmp(old_cfg, bridge_cfg))
496         reconfigure_bridge();
497     return error ;
498 }
499
500 static int
501 sysctl_refresh(SYSCTL_HANDLER_ARGS)
502 {
503     if (req->newptr)
504         reconfigure_bridge();
505
506     return 0;
507 }
508
509
510 SYSCTL_DECL(_net_link_ether);
511 SYSCTL_PROC(_net_link_ether, OID_AUTO, bridge_cfg, CTLTYPE_STRING|CTLFLAG_RW,
512             &bridge_cfg, sizeof(bridge_cfg), &sysctl_bdg_cfg, "A",
513             "Bridge configuration");
514
515 SYSCTL_PROC(_net_link_ether, OID_AUTO, bridge, CTLTYPE_INT|CTLFLAG_RW,
516             &do_bridge, 0, &sysctl_bdg, "I", "Bridging");
517
518 SYSCTL_INT(_net_link_ether, OID_AUTO, bridge_ipfw, CTLFLAG_RW,
519             &bdg_ipfw,0,"Pass bridged pkts through firewall");
520
521 SYSCTL_INT(_net_link_ether, OID_AUTO, bridge_ipf, CTLFLAG_RW,
522             &bdg_ipf, 0,"Pass bridged pkts through IPFilter");
523
524 /*
525  * The follow macro declares a variable, and maps it to
526  * a SYSCTL_INT entry with the same name.
527  */
528 #define SY(parent, var, comment)                        \
529         static int var ;                                \
530         SYSCTL_INT(parent, OID_AUTO, var, CTLFLAG_RW, &(var), 0, comment);
531
532 int bdg_ipfw_drops;
533 SYSCTL_INT(_net_link_ether, OID_AUTO, bridge_ipfw_drop,
534         CTLFLAG_RW, &bdg_ipfw_drops,0,"");
535
536 int bdg_ipfw_colls;
537 SYSCTL_INT(_net_link_ether, OID_AUTO, bridge_ipfw_collisions,
538         CTLFLAG_RW, &bdg_ipfw_colls,0,"");
539
540 SYSCTL_PROC(_net_link_ether, OID_AUTO, bridge_refresh, CTLTYPE_INT|CTLFLAG_WR,
541             NULL, 0, &sysctl_refresh, "I", "iface refresh");
542
543 #if 1 /* diagnostic vars */
544
545 SY(_net_link_ether, verbose, "Be verbose");
546 SY(_net_link_ether, bdg_split_pkts, "Packets split in bdg_forward");
547
548 SY(_net_link_ether, bdg_thru, "Packets through bridge");
549
550 SY(_net_link_ether, bdg_copied, "Packets copied in bdg_forward");
551
552 SY(_net_link_ether, bdg_copy, "Force copy in bdg_forward");
553 SY(_net_link_ether, bdg_predict, "Correctly predicted header location");
554
555 SY(_net_link_ether, bdg_fw_avg, "Cycle counter avg");
556 SY(_net_link_ether, bdg_fw_ticks, "Cycle counter item");
557 SY(_net_link_ether, bdg_fw_count, "Cycle counter count");
558 #endif
559
560 SYSCTL_STRUCT(_net_link_ether, PF_BDG, bdgstats,
561         CTLFLAG_RD, &bdg_stats , bdg_stats, "bridge statistics");
562
563 static int bdg_loops ;
564
565 /*
566  * called periodically to flush entries etc.
567  */
568 static void
569 bdg_timeout(void *dummy)
570 {
571     static int slowtimer; /* in BSS so initialized to 0 */
572
573     if (do_bridge) {
574         static int age_index = 0 ; /* index of table position to age */
575         int l = age_index + HASH_SIZE/4 ;
576         int i;
577         /*
578          * age entries in the forwarding table.
579          */
580         if (l > HASH_SIZE)
581             l = HASH_SIZE ;
582
583         for (i=0; i<n_clusters; i++) {
584             bdg_hash_table *bdg_table = clusters[i].ht;
585             for (; age_index < l ; age_index++)
586                 if (bdg_table[age_index].used)
587                     bdg_table[age_index].used = 0 ;
588                 else if (bdg_table[age_index].name) {
589                     /* printf("xx flushing stale entry %d\n", age_index); */
590                     bdg_table[age_index].name = NULL ;
591                 }
592         }
593         if (age_index >= HASH_SIZE)
594             age_index = 0 ;
595
596         if (--slowtimer <= 0 ) {
597             slowtimer = 5 ;
598
599             bridge_on() ; /* we just need unmute, really */
600             bdg_loops = 0 ;
601         }
602     }
603     bdg_timeout_h = timeout(bdg_timeout, NULL, 2*hz );
604 }
605
606 /*
607  * Find the right pkt destination:
608  *      BDG_BCAST       is a broadcast
609  *      BDG_MCAST       is a multicast
610  *      BDG_LOCAL       is for a local address
611  *      BDG_DROP        must be dropped
612  *      other           ifp of the dest. interface (incl.self)
613  *
614  * We assume this is only called for interfaces for which bridging
615  * is enabled, i.e. BDG_USED(ifp) is true.
616  */
617 static __inline
618 struct ifnet *
619 bridge_dst_lookup(struct ether_header *eh, struct cluster_softc *c)
620 {
621     struct ifnet *dst ;
622     int index ;
623     struct bdg_addr *p ;
624     bdg_hash_table *bt;         /* pointer to entry in hash table */
625
626     if (IS_ETHER_BROADCAST(eh->ether_dhost))
627         return BDG_BCAST ;
628     if (eh->ether_dhost[0] & 1)
629         return BDG_MCAST ;
630     /*
631      * Lookup local addresses in case one matches.
632      */
633     for (index = c->ports, p = c->my_macs; index ; index--, p++ )
634         if (BDG_MATCH(p->etheraddr, eh->ether_dhost) )
635             return BDG_LOCAL ;
636     /*
637      * Look for a possible destination in table
638      */
639     index= HASH_FN( eh->ether_dhost );
640     bt = &(c->ht[index]);
641     dst = bt->name;
642     if ( dst && BDG_MATCH( bt->etheraddr, eh->ether_dhost) )
643         return dst ;
644     else
645         return BDG_UNKNOWN ;
646 }
647
648 /**
649  * bridge_in() is invoked to perform bridging decision on input packets.
650  *
651  * On Input:
652  *   eh         Ethernet header of the incoming packet.
653  *   ifp        interface the packet is coming from.
654  *
655  * On Return: destination of packet, one of
656  *   BDG_BCAST  broadcast
657  *   BDG_MCAST  multicast
658  *   BDG_LOCAL  is only for a local address (do not forward)
659  *   BDG_DROP   drop the packet
660  *   ifp        ifp of the destination interface.
661  *
662  * Forwarding is not done directly to give a chance to some drivers
663  * to fetch more of the packet, or simply drop it completely.
664  */
665
666 static struct ifnet *
667 bridge_in(struct ifnet *ifp, struct ether_header *eh)
668 {
669     int index;
670     struct ifnet *dst , *old ;
671     bdg_hash_table *bt;                 /* location in hash table */
672     int dropit = BDG_MUTED(ifp) ;
673
674     /*
675      * hash the source address
676      */
677     index= HASH_FN(eh->ether_shost);
678     bt = &(ifp2sc[ifp->if_index].cluster->ht[index]);
679     bt->used = 1 ;
680     old = bt->name ;
681     if ( old ) { /* the entry is valid. */
682         if (!BDG_MATCH( eh->ether_shost, bt->etheraddr) ) {
683             bdg_ipfw_colls++ ;
684             bt->name = NULL ;
685         } else if (old != ifp) {
686             /*
687              * Found a loop. Either a machine has moved, or there
688              * is a misconfiguration/reconfiguration of the network.
689              * First, do not forward this packet!
690              * Record the relocation anyways; then, if loops persist,
691              * suspect a reconfiguration and disable forwarding
692              * from the old interface.
693              */
694             bt->name = ifp ; /* relocate address */
695             printf("-- loop (%d) %6D to %s from %s (%s)\n",
696                         bdg_loops, eh->ether_shost, ".",
697                         ifp->if_xname, old->if_xname,
698                         BDG_MUTED(old) ? "muted":"active");
699             dropit = 1 ;
700             if ( !BDG_MUTED(old) ) {
701                 if (++bdg_loops > 10)
702                     BDG_MUTE(old) ;
703             }
704         }
705     }
706
707     /*
708      * now write the source address into the table
709      */
710     if (bt->name == NULL) {
711         DEB(printf("new addr %6D at %d for %s\n",
712             eh->ether_shost, ".", index, ifp->if_xname);)
713         bcopy(eh->ether_shost, bt->etheraddr, 6);
714         bt->name = ifp ;
715     }
716     dst = bridge_dst_lookup(eh, ifp2sc[ifp->if_index].cluster);
717     /*
718      * bridge_dst_lookup can return the following values:
719      *   BDG_BCAST, BDG_MCAST, BDG_LOCAL, BDG_UNKNOWN, BDG_DROP, ifp.
720      * For muted interfaces, or when we detect a loop, the first 3 are
721      * changed in BDG_LOCAL (we still listen to incoming traffic),
722      * and others to BDG_DROP (no use for the local host).
723      * Also, for incoming packets, ifp is changed to BDG_DROP if ifp == src.
724      * These changes are not necessary for outgoing packets from ether_output().
725      */
726     BDG_STAT(ifp, BDG_IN);
727     switch ((uintptr_t)dst) {
728     case (uintptr_t)BDG_BCAST:
729     case (uintptr_t)BDG_MCAST:
730     case (uintptr_t)BDG_LOCAL:
731     case (uintptr_t)BDG_UNKNOWN:
732     case (uintptr_t)BDG_DROP:
733         BDG_STAT(ifp, dst);
734         break ;
735     default :
736         if (dst == ifp || dropit)
737             BDG_STAT(ifp, BDG_DROP);
738         else
739             BDG_STAT(ifp, BDG_FORWARD);
740         break ;
741     }
742
743     if ( dropit ) {
744         if (dst == BDG_BCAST || dst == BDG_MCAST || dst == BDG_LOCAL)
745             dst = BDG_LOCAL ;
746         else
747             dst = BDG_DROP ;
748     } else {
749         if (dst == ifp)
750             dst = BDG_DROP;
751     }
752     DEB(printf("bridge_in %6D ->%6D ty 0x%04x dst %s\n",
753         eh->ether_shost, ".",
754         eh->ether_dhost, ".",
755         ntohs(eh->ether_type),
756         (dst <= BDG_FORWARD) ? bdg_dst_names[(int)dst]"0" :
757                 dst->if_xname); )
758
759     return dst ;
760 }
761
762 /*
763  * Forward a packet to dst -- which can be a single interface or
764  * an entire cluster. The src port and muted interfaces are excluded.
765  *
766  * If src == NULL, the pkt comes from ether_output, and dst is the real
767  * interface the packet is originally sent to. In this case, we must forward
768  * it to the whole cluster.
769  * We never call bdg_forward from ether_output on interfaces which are
770  * not part of a cluster.
771  *
772  * If possible (i.e. we can determine that the caller does not need
773  * a copy), the packet is consumed here, and bdg_forward returns NULL.
774  * Otherwise, a pointer to a copy of the packet is returned.
775  *
776  * XXX be careful with eh, it can be a pointer into *m
777  */
778 static struct mbuf *
779 bdg_forward(struct mbuf *m0, struct ether_header *const eh, struct ifnet *dst)
780 {
781     struct ifnet *src;
782     struct ifnet *ifp, *last;
783     int shared = bdg_copy ; /* someone else is using the mbuf */
784     int once = 0;      /* loop only once */
785     struct ifnet *real_dst = dst ; /* real dst from ether_output */
786     struct ip_fw_args args;
787
788     /*
789      * XXX eh is usually a pointer within the mbuf (some ethernet drivers
790      * do that), so we better copy it before doing anything with the mbuf,
791      * or we might corrupt the header.
792      */
793     struct ether_header save_eh = *eh ;
794
795     DEB(quad_t ticks; ticks = rdtsc();)
796
797     args.rule = NULL;           /* did we match a firewall rule ? */
798     /* Fetch state from dummynet tag, ignore others */
799     for (;m0->m_type == MT_TAG; m0 = m0->m_next)
800         if (m0->_m_tag_id == PACKET_TAG_DUMMYNET) {
801             args.rule = ((struct dn_pkt *)m0)->rule;
802             shared = 0;         /* For sure this is our own mbuf. */
803         }
804     if (args.rule == NULL)
805         bdg_thru++; /* first time through bdg_forward, count packet */
806
807     src = m0->m_pkthdr.rcvif;
808     if (src == NULL)                    /* packet from ether_output */
809         dst = bridge_dst_lookup(eh, ifp2sc[real_dst->if_index].cluster);
810
811     if (dst == BDG_DROP) { /* this should not happen */
812         printf("xx bdg_forward for BDG_DROP\n");
813         m_freem(m0);
814         return NULL;
815     }
816     if (dst == BDG_LOCAL) { /* this should not happen as well */
817         printf("xx ouch, bdg_forward for local pkt\n");
818         return m0;
819     }
820     if (dst == BDG_BCAST || dst == BDG_MCAST || dst == BDG_UNKNOWN) {
821         ifp = TAILQ_FIRST(&ifnet) ; /* scan all ports */
822         once = 0 ;
823         if (dst != BDG_UNKNOWN) /* need a copy for the local stack */
824             shared = 1 ;
825     } else {
826         ifp = dst ;
827         once = 1 ;
828     }
829     if ( (uintptr_t)(ifp) <= (u_int)BDG_FORWARD )
830         panic("bdg_forward: bad dst");
831
832     /*
833      * Do filtering in a very similar way to what is done in ip_output.
834      * Only if firewall is loaded, enabled, and the packet is not
835      * from ether_output() (src==NULL, or we would filter it twice).
836      * Additional restrictions may apply e.g. non-IP, short packets,
837      * and pkts already gone through a pipe.
838      */
839     if (src != NULL && (
840         (fr_checkp != NULL && bdg_ipf != 0) ||
841         (IPFW_LOADED && bdg_ipfw != 0))) {
842
843         int i;
844
845         if (args.rule != NULL && fw_one_pass)
846             goto forward; /* packet already partially processed */
847         /*
848          * i need some amt of data to be contiguous, and in case others need
849          * the packet (shared==1) also better be in the first mbuf.
850          */
851         i = min(m0->m_pkthdr.len, max_protohdr) ;
852         if ( shared || m0->m_len < i) {
853             m0 = m_pullup(m0, i) ;
854             if (m0 == NULL) {
855                 printf("-- bdg: pullup failed.\n") ;
856                 return NULL ;
857             }
858         }
859
860         /*
861          * IP Filter hook.
862          */
863         if (fr_checkp != NULL && bdg_ipf &&
864             m0->m_pkthdr.len >= sizeof(struct ip) &&
865             ntohs(save_eh.ether_type) == ETHERTYPE_IP) {
866             /*
867              * before calling the firewall, swap fields the same as IP does.
868              * here we assume the pkt is an IP one and the header is contiguous
869              */
870             struct ip *ip = mtod(m0, struct ip *);
871
872             ip->ip_len = ntohs(ip->ip_len);
873             ip->ip_off = ntohs(ip->ip_off);
874
875             if ((*fr_checkp)(ip, ip->ip_hl << 2, src, 0, &m0) || m0 == NULL)
876                 return m0;
877
878             /*
879              * If we get here, the firewall has passed the pkt, but the mbuf
880              * pointer might have changed. Restore ip and the fields ntohs()'d.
881              */
882             ip = mtod(m0, struct ip *);
883             ip->ip_len = htons(ip->ip_len);
884             ip->ip_off = htons(ip->ip_off);
885         }
886
887         /*
888          * Prepare arguments and call the firewall.
889          */
890         if (!IPFW_LOADED || bdg_ipfw == 0)
891             goto forward;       /* not using ipfw, accept the packet */
892
893         /*
894          * XXX The following code is very similar to the one in
895          * if_ethersubr.c:ether_ipfw_chk()
896          */
897
898         args.m = m0;            /* the packet we are looking at         */
899         args.oif = NULL;        /* this is an input packet              */
900         args.divert_rule = 0;   /* we do not support divert yet         */
901         args.next_hop = NULL;   /* we do not support forward yet        */
902         args.eh = &save_eh;     /* MAC header for bridged/MAC packets   */
903         i = ip_fw_chk_ptr(&args);
904         m0 = args.m;            /* in case the firewall used the mbuf   */
905
906         if ( (i & IP_FW_PORT_DENY_FLAG) || m0 == NULL) /* drop */
907             return m0 ;
908
909         if (i == 0) /* a PASS rule.  */
910             goto forward ;
911         if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG)) {
912             /*
913              * Pass the pkt to dummynet, which consumes it.
914              * If shared, make a copy and keep the original.
915              */
916             struct mbuf *m ;
917
918             if (shared) {
919                 m = m_copypacket(m0, MB_DONTWAIT);
920                 if (m == NULL)  /* copy failed, give up */
921                     return m0;
922             } else {
923                 m = m0 ; /* pass the original to dummynet */
924                 m0 = NULL ; /* and nothing back to the caller */
925             }
926             /*
927              * Prepend the header, optimize for the common case of
928              * eh pointing into the mbuf.
929              */
930             if ( (void *)(eh + 1) == (void *)m->m_data) {
931                 m->m_data -= ETHER_HDR_LEN ;
932                 m->m_len += ETHER_HDR_LEN ;
933                 m->m_pkthdr.len += ETHER_HDR_LEN ;
934                 bdg_predict++;
935             } else {
936                 M_PREPEND(m, ETHER_HDR_LEN, MB_DONTWAIT);
937                 if (m == NULL) /* nope... */
938                     return m0 ;
939                 bcopy(&save_eh, mtod(m, struct ether_header *), ETHER_HDR_LEN);
940             }
941
942             args.oif = real_dst;
943             ip_dn_io_ptr(m, (i & 0xffff),DN_TO_BDG_FWD, &args);
944             return m0 ;
945         }
946         /*
947          * XXX at some point, add support for divert/forward actions.
948          * If none of the above matches, we have to drop the packet.
949          */
950         bdg_ipfw_drops++ ;
951         return m0 ;
952     }
953 forward:
954     /*
955      * Again, bring up the headers in case of shared bufs to avoid
956      * corruptions in the future.
957      */
958     if ( shared ) {
959         int i = min(m0->m_pkthdr.len, max_protohdr) ;
960
961         m0 = m_pullup(m0, i) ;
962         if (m0 == NULL)
963             return NULL ;
964     }
965     /*
966      * now real_dst is used to determine the cluster where to forward.
967      * For packets coming from ether_input, this is the one of the 'src'
968      * interface, whereas for locally generated packets (src==NULL) it
969      * is the cluster of the original destination interface, which
970      * was already saved into real_dst.
971      */
972     if (src != NULL)
973         real_dst = src ;
974
975     last = NULL;
976     for (;;) {
977         if (last) { /* need to forward packet leftover from previous loop */
978             struct mbuf *m ;
979             if (shared == 0 && once ) { /* no need to copy */
980                 m = m0 ;
981                 m0 = NULL ; /* original is gone */
982             } else {
983                 m = m_copypacket(m0, MB_DONTWAIT);
984                 if (m == NULL) {
985                     printf("bdg_forward: sorry, m_copypacket failed!\n");
986                     return m0 ; /* the original is still there... */
987                 }
988             }
989             /*
990              * Add header (optimized for the common case of eh pointing
991              * already into the mbuf) and execute last part of ether_output:
992              * queue pkt and start output if interface not yet active.
993              */
994             if ( (void *)(eh + 1) == (void *)m->m_data) {
995                 m->m_data -= ETHER_HDR_LEN ;
996                 m->m_len += ETHER_HDR_LEN ;
997                 m->m_pkthdr.len += ETHER_HDR_LEN ;
998                 bdg_predict++;
999             } else {
1000                 M_PREPEND(m, ETHER_HDR_LEN, MB_DONTWAIT);
1001                 if (!m && verbose)
1002                     printf("M_PREPEND failed\n");
1003                 if (m == NULL)
1004                     return m0;
1005                 bcopy(&save_eh, mtod(m, struct ether_header *), ETHER_HDR_LEN);
1006             }
1007             if (!IF_HANDOFF(&last->if_snd, m, last)) {
1008 #if 0
1009                 BDG_MUTE(last); /* should I also mute ? */
1010 #endif
1011             }
1012             BDG_STAT(last, BDG_OUT);
1013             last = NULL ;
1014             if (once)
1015                 break ;
1016         }
1017         if (ifp == NULL)
1018             break ;
1019         /*
1020          * If the interface is used for bridging, not muted, not full,
1021          * up and running, is not the source interface, and belongs to
1022          * the same cluster as the 'real_dst', then send here.
1023          */
1024         if ( BDG_USED(ifp) && !BDG_MUTED(ifp) && !_IF_QFULL(&ifp->if_snd)  &&
1025              (ifp->if_flags & (IFF_UP|IFF_RUNNING)) == (IFF_UP|IFF_RUNNING) &&
1026              ifp != src && BDG_SAMECLUSTER(ifp, real_dst) )
1027             last = ifp ;
1028         ifp = TAILQ_NEXT(ifp, if_link) ;
1029         if (ifp == NULL)
1030             once = 1 ;
1031     }
1032     DEB(bdg_fw_ticks += (u_long)(rdtsc() - ticks) ; bdg_fw_count++ ;
1033         if (bdg_fw_count != 0) bdg_fw_avg = bdg_fw_ticks/bdg_fw_count; )
1034     return m0 ;
1035 }
1036
1037 /*
1038  * initialization of bridge code.
1039  */
1040 static int
1041 bdginit(void)
1042 {
1043     printf("BRIDGE 020214 loaded\n");
1044
1045     ifp2sc = malloc(BDG_MAX_PORTS * sizeof(struct bdg_softc),
1046                 M_IFADDR, M_WAITOK | M_ZERO );
1047     if (ifp2sc == NULL)
1048         return ENOMEM ;
1049
1050     bridge_in_ptr = bridge_in;
1051     bdg_forward_ptr = bdg_forward;
1052     bdgtakeifaces_ptr = reconfigure_bridge;
1053
1054     n_clusters = 0;
1055     clusters = NULL;
1056     do_bridge=0;
1057
1058     bzero(&bdg_stats, sizeof(bdg_stats) );
1059     bdgtakeifaces_ptr();
1060     bdg_timeout(0);
1061     return 0 ;
1062 }
1063
1064 /*
1065  * initialization code, both for static and dynamic loading.
1066  */
1067 static int
1068 bridge_modevent(module_t mod, int type, void *unused)
1069 {
1070         int s;
1071         int err = 0 ;
1072
1073         switch (type) {
1074         case MOD_LOAD:
1075                 if (BDG_LOADED) {
1076                         err = EEXIST;
1077                         break ;
1078                 }
1079                 s = splimp();
1080                 err = bdginit();
1081                 splx(s);
1082                 break;
1083         case MOD_UNLOAD:
1084 #if !defined(KLD_MODULE)
1085                 printf("bridge statically compiled, cannot unload\n");
1086                 err = EINVAL ;
1087 #else
1088                 s = splimp();
1089                 do_bridge = 0;
1090                 bridge_in_ptr = NULL;
1091                 bdg_forward_ptr = NULL;
1092                 bdgtakeifaces_ptr = NULL;
1093                 untimeout(bdg_timeout, NULL, bdg_timeout_h);
1094                 bridge_off();
1095                 if (clusters)
1096                     free(clusters, M_IFADDR);
1097                 free(ifp2sc, M_IFADDR);
1098                 ifp2sc = NULL ;
1099                 splx(s);
1100 #endif
1101                 break;
1102         default:
1103                 err = EINVAL ;
1104                 break;
1105         }
1106         return err;
1107 }
1108
1109 static moduledata_t bridge_mod = {
1110         "bridge",
1111         bridge_modevent,
1112         0
1113 };
1114
1115 DECLARE_MODULE(bridge, bridge_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
1116 MODULE_VERSION(bridge, 1);