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