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