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