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