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