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.1/sys/net/bridge.c 111119 2003-02-19 05:47:46Z imp $
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_NOWAIT | 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 IFNET_RLOCK();
306 TAILQ_FOREACH(ifp, &ifnet, if_link) {
307 struct bdg_softc *b;
308
309 if (ifp->if_index >= BDG_MAX_PORTS)
310 continue; /* make sure we do not go beyond the end */
311 b = &(ifp2sc[ifp->if_index]);
312
313 if ( b->flags & IFF_BDG_PROMISC ) {
314 s = splimp();
315 ifpromisc(ifp, 0);
316 splx(s);
317 b->flags &= ~(IFF_BDG_PROMISC|IFF_MUTE) ;
318 DEB(printf(">> now %s%d promisc OFF if_flags 0x%x bdg_flags 0x%x\n",
319 ifp->if_name, ifp->if_unit,
320 ifp->if_flags, b->flags);)
321 }
322 b->flags &= ~(IFF_USED) ;
323 b->cluster = NULL;
324 bdg_stats.s[ifp->if_index].name[0] = '\0';
325 }
326 IFNET_RUNLOCK();
327 /* flush_tables */
328
329 s = splimp();
330 for (i=0; i < n_clusters; i++) {
331 free(clusters[i].ht, M_IFADDR);
332 free(clusters[i].my_macs, M_IFADDR);
333 }
334 if (clusters != NULL)
335 free(clusters, M_IFADDR);
336 clusters = NULL;
337 n_clusters =0;
338 splx(s);
339 }
340
341 /*
342 * set promisc mode on the interfaces we use.
343 */
344 static void
345 bridge_on(void)
346 {
347 struct ifnet *ifp ;
348 int s ;
349
350 IFNET_RLOCK();
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 IFNET_RUNLOCK();
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 */
387 static void
388 reconfigure_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
403 static 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 */
413 static void
414 parse_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 IFNET_RLOCK(); /* could sleep XXX */
443 TAILQ_FOREACH(ifp, &ifnet, if_link) {
444 char buf[IFNAMSIZ];
445
446 snprintf(buf, sizeof(buf), "%s%d", ifp->if_name, ifp->if_unit);
447 if (!strncmp(beg, buf, max(l, strlen(buf)))) {
448 struct bdg_softc *b = &ifp2sc[ifp->if_index];
449 if (ifp->if_type != IFT_ETHER && ifp->if_type != IFT_L2VLAN) {
450 printf("%s is not an ethernet, continue\n", buf);
451 continue;
452 }
453 if (b->flags & IFF_USED) {
454 printf("%s already used, skipping\n", buf);
455 break;
456 }
457 b->cluster = add_cluster(htons(cluster), (struct arpcom *)ifp);
458 b->flags |= IFF_USED ;
459 sprintf(bdg_stats.s[ifp->if_index].name,
460 "%s%d:%d", ifp->if_name, ifp->if_unit, cluster);
461
462 DEB(printf("--++ found %s next c %d\n",
463 bdg_stats.s[ifp->if_index].name, c);)
464 found = 1;
465 break ;
466 }
467 }
468 IFNET_RUNLOCK();
469 if (!found)
470 printf("interface %s Not found in bridge\n", beg);
471 *p = c;
472 if (c == '\0')
473 break; /* no more */
474 }
475 }
476
477
478 /*
479 * handler for net.link.ether.bridge
480 */
481 static int
482 sysctl_bdg(SYSCTL_HANDLER_ARGS)
483 {
484 int error, oldval = do_bridge ;
485
486 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
487 DEB( printf("called sysctl for bridge name %s arg2 %d val %d->%d\n",
488 oidp->oid_name, oidp->oid_arg2,
489 oldval, do_bridge); )
490
491 if (oldval != do_bridge)
492 reconfigure_bridge();
493 return error ;
494 }
495
496 /*
497 * handler for net.link.ether.bridge_cfg
498 */
499 static int
500 sysctl_bdg_cfg(SYSCTL_HANDLER_ARGS)
501 {
502 int error = 0 ;
503 char old_cfg[1024] ;
504
505 strcpy(old_cfg, bridge_cfg) ;
506
507 error = sysctl_handle_string(oidp, bridge_cfg, oidp->oid_arg2, req);
508 DEB(
509 printf("called sysctl for bridge name %s arg2 %d err %d val %s->%s\n",
510 oidp->oid_name, oidp->oid_arg2,
511 error,
512 old_cfg, bridge_cfg);
513 )
514 if (strcmp(old_cfg, bridge_cfg))
515 reconfigure_bridge();
516 return error ;
517 }
518
519 static int
520 sysctl_refresh(SYSCTL_HANDLER_ARGS)
521 {
522 if (req->newptr)
523 reconfigure_bridge();
524
525 return 0;
526 }
527
528
529 SYSCTL_DECL(_net_link_ether);
530 SYSCTL_PROC(_net_link_ether, OID_AUTO, bridge_cfg, CTLTYPE_STRING|CTLFLAG_RW,
531 &bridge_cfg, sizeof(bridge_cfg), &sysctl_bdg_cfg, "A",
532 "Bridge configuration");
533
534 SYSCTL_PROC(_net_link_ether, OID_AUTO, bridge, CTLTYPE_INT|CTLFLAG_RW,
535 &do_bridge, 0, &sysctl_bdg, "I", "Bridging");
536
537 SYSCTL_INT(_net_link_ether, OID_AUTO, bridge_ipfw, CTLFLAG_RW,
538 &bdg_ipfw,0,"Pass bridged pkts through firewall");
539
540 SYSCTL_INT(_net_link_ether, OID_AUTO, bridge_ipf, CTLFLAG_RW,
541 &bdg_ipf, 0,"Pass bridged pkts through IPFilter");
542
543 /*
544 * The follow macro declares a variable, and maps it to
545 * a SYSCTL_INT entry with the same name.
546 */
547 #define SY(parent, var, comment) \
548 static int var ; \
549 SYSCTL_INT(parent, OID_AUTO, var, CTLFLAG_RW, &(var), 0, comment);
550
551 int bdg_ipfw_drops;
552 SYSCTL_INT(_net_link_ether, OID_AUTO, bridge_ipfw_drop,
553 CTLFLAG_RW, &bdg_ipfw_drops,0,"");
554
555 int bdg_ipfw_colls;
556 SYSCTL_INT(_net_link_ether, OID_AUTO, bridge_ipfw_collisions,
557 CTLFLAG_RW, &bdg_ipfw_colls,0,"");
558
559 SYSCTL_PROC(_net_link_ether, OID_AUTO, bridge_refresh, CTLTYPE_INT|CTLFLAG_WR,
560 NULL, 0, &sysctl_refresh, "I", "iface refresh");
561
562 #if 1 /* diagnostic vars */
563
564 SY(_net_link_ether, verbose, "Be verbose");
565 SY(_net_link_ether, bdg_split_pkts, "Packets split in bdg_forward");
566
567 SY(_net_link_ether, bdg_thru, "Packets through bridge");
568
569 SY(_net_link_ether, bdg_copied, "Packets copied in bdg_forward");
570 SY(_net_link_ether, bdg_dropped, "Packets dropped in bdg_forward");
571
572 SY(_net_link_ether, bdg_copy, "Force copy in bdg_forward");
573 SY(_net_link_ether, bdg_predict, "Correctly predicted header location");
574
575 SY(_net_link_ether, bdg_fw_avg, "Cycle counter avg");
576 SY(_net_link_ether, bdg_fw_ticks, "Cycle counter item");
577 SY(_net_link_ether, bdg_fw_count, "Cycle counter count");
578 #endif
579
580 SYSCTL_STRUCT(_net_link_ether, PF_BDG, bdgstats,
581 CTLFLAG_RD, &bdg_stats , bdg_stats, "bridge statistics");
582
583 static int bdg_loops ;
584
585 /*
586 * called periodically to flush entries etc.
587 */
588 static void
589 bdg_timeout(void *dummy)
590 {
591 static int slowtimer; /* in BSS so initialized to 0 */
592
593 if (do_bridge) {
594 static int age_index = 0 ; /* index of table position to age */
595 int l = age_index + HASH_SIZE/4 ;
596 int i;
597 /*
598 * age entries in the forwarding table.
599 */
600 if (l > HASH_SIZE)
601 l = HASH_SIZE ;
602
603 for (i=0; i<n_clusters; i++) {
604 bdg_hash_table *bdg_table = clusters[i].ht;
605 for (; age_index < l ; age_index++)
606 if (bdg_table[age_index].used)
607 bdg_table[age_index].used = 0 ;
608 else if (bdg_table[age_index].name) {
609 /* printf("xx flushing stale entry %d\n", age_index); */
610 bdg_table[age_index].name = NULL ;
611 }
612 }
613 if (age_index >= HASH_SIZE)
614 age_index = 0 ;
615
616 if (--slowtimer <= 0 ) {
617 slowtimer = 5 ;
618
619 bridge_on() ; /* we just need unmute, really */
620 bdg_loops = 0 ;
621 }
622 }
623 bdg_timeout_h = timeout(bdg_timeout, NULL, 2*hz );
624 }
625
626 /*
627 * Find the right pkt destination:
628 * BDG_BCAST is a broadcast
629 * BDG_MCAST is a multicast
630 * BDG_LOCAL is for a local address
631 * BDG_DROP must be dropped
632 * other ifp of the dest. interface (incl.self)
633 *
634 * We assume this is only called for interfaces for which bridging
635 * is enabled, i.e. BDG_USED(ifp) is true.
636 */
637 static __inline
638 struct ifnet *
639 bridge_dst_lookup(struct ether_header *eh, struct cluster_softc *c)
640 {
641 struct ifnet *dst ;
642 int index ;
643 struct bdg_addr *p ;
644 bdg_hash_table *bt; /* pointer to entry in hash table */
645
646 if (IS_ETHER_BROADCAST(eh->ether_dhost))
647 return BDG_BCAST ;
648 if (eh->ether_dhost[0] & 1)
649 return BDG_MCAST ;
650 /*
651 * Lookup local addresses in case one matches.
652 */
653 for (index = c->ports, p = c->my_macs; index ; index--, p++ )
654 if (BDG_MATCH(p->etheraddr, eh->ether_dhost) )
655 return BDG_LOCAL ;
656 /*
657 * Look for a possible destination in table
658 */
659 index= HASH_FN( eh->ether_dhost );
660 bt = &(c->ht[index]);
661 dst = bt->name;
662 if ( dst && BDG_MATCH( bt->etheraddr, eh->ether_dhost) )
663 return dst ;
664 else
665 return BDG_UNKNOWN ;
666 }
667
668 /**
669 * bridge_in() is invoked to perform bridging decision on input packets.
670 *
671 * On Input:
672 * eh Ethernet header of the incoming packet.
673 * ifp interface the packet is coming from.
674 *
675 * On Return: destination of packet, one of
676 * BDG_BCAST broadcast
677 * BDG_MCAST multicast
678 * BDG_LOCAL is only for a local address (do not forward)
679 * BDG_DROP drop the packet
680 * ifp ifp of the destination interface.
681 *
682 * Forwarding is not done directly to give a chance to some drivers
683 * to fetch more of the packet, or simply drop it completely.
684 */
685
686 static struct ifnet *
687 bridge_in(struct ifnet *ifp, struct ether_header *eh)
688 {
689 int index;
690 struct ifnet *dst , *old ;
691 bdg_hash_table *bt; /* location in hash table */
692 int dropit = BDG_MUTED(ifp) ;
693
694 /*
695 * hash the source address
696 */
697 index= HASH_FN(eh->ether_shost);
698 bt = &(ifp2sc[ifp->if_index].cluster->ht[index]);
699 bt->used = 1 ;
700 old = bt->name ;
701 if ( old ) { /* the entry is valid. */
702 if (!BDG_MATCH( eh->ether_shost, bt->etheraddr) ) {
703 bdg_ipfw_colls++ ;
704 bt->name = NULL ;
705 } else if (old != ifp) {
706 /*
707 * Found a loop. Either a machine has moved, or there
708 * is a misconfiguration/reconfiguration of the network.
709 * First, do not forward this packet!
710 * Record the relocation anyways; then, if loops persist,
711 * suspect a reconfiguration and disable forwarding
712 * from the old interface.
713 */
714 bt->name = ifp ; /* relocate address */
715 printf("-- loop (%d) %6D to %s%d from %s%d (%s)\n",
716 bdg_loops, eh->ether_shost, ".",
717 ifp->if_name, ifp->if_unit,
718 old->if_name, old->if_unit,
719 BDG_MUTED(old) ? "muted":"active");
720 dropit = 1 ;
721 if ( !BDG_MUTED(old) ) {
722 if (++bdg_loops > 10)
723 BDG_MUTE(old) ;
724 }
725 }
726 }
727
728 /*
729 * now write the source address into the table
730 */
731 if (bt->name == NULL) {
732 DEB(printf("new addr %6D at %d for %s%d\n",
733 eh->ether_shost, ".", index, ifp->if_name, ifp->if_unit);)
734 bcopy(eh->ether_shost, bt->etheraddr, 6);
735 bt->name = ifp ;
736 }
737 dst = bridge_dst_lookup(eh, ifp2sc[ifp->if_index].cluster);
738 /*
739 * bridge_dst_lookup can return the following values:
740 * BDG_BCAST, BDG_MCAST, BDG_LOCAL, BDG_UNKNOWN, BDG_DROP, ifp.
741 * For muted interfaces, or when we detect a loop, the first 3 are
742 * changed in BDG_LOCAL (we still listen to incoming traffic),
743 * and others to BDG_DROP (no use for the local host).
744 * Also, for incoming packets, ifp is changed to BDG_DROP if ifp == src.
745 * These changes are not necessary for outgoing packets from ether_output().
746 */
747 BDG_STAT(ifp, BDG_IN);
748 switch ((uintptr_t)dst) {
749 case (uintptr_t)BDG_BCAST:
750 case (uintptr_t)BDG_MCAST:
751 case (uintptr_t)BDG_LOCAL:
752 case (uintptr_t)BDG_UNKNOWN:
753 case (uintptr_t)BDG_DROP:
754 BDG_STAT(ifp, dst);
755 break ;
756 default :
757 if (dst == ifp || dropit)
758 BDG_STAT(ifp, BDG_DROP);
759 else
760 BDG_STAT(ifp, BDG_FORWARD);
761 break ;
762 }
763
764 if ( dropit ) {
765 if (dst == BDG_BCAST || dst == BDG_MCAST || dst == BDG_LOCAL)
766 dst = BDG_LOCAL ;
767 else
768 dst = BDG_DROP ;
769 } else {
770 if (dst == ifp)
771 dst = BDG_DROP;
772 }
773 DEB(printf("bridge_in %6D ->%6D ty 0x%04x dst %s%d\n",
774 eh->ether_shost, ".",
775 eh->ether_dhost, ".",
776 ntohs(eh->ether_type),
777 (dst <= BDG_FORWARD) ? bdg_dst_names[(int)dst] :
778 dst->if_name,
779 (dst <= BDG_FORWARD) ? 0 : dst->if_unit); )
780
781 return dst ;
782 }
783
784 /*
785 * Forward a packet to dst -- which can be a single interface or
786 * an entire cluster. The src port and muted interfaces are excluded.
787 *
788 * If src == NULL, the pkt comes from ether_output, and dst is the real
789 * interface the packet is originally sent to. In this case, we must forward
790 * it to the whole cluster.
791 * We never call bdg_forward from ether_output on interfaces which are
792 * not part of a cluster.
793 *
794 * If possible (i.e. we can determine that the caller does not need
795 * a copy), the packet is consumed here, and bdg_forward returns NULL.
796 * Otherwise, a pointer to a copy of the packet is returned.
797 */
798 static struct mbuf *
799 bdg_forward(struct mbuf *m0, struct ifnet *dst)
800 {
801 #define EH_RESTORE(_m) do { \
802 M_PREPEND((_m), ETHER_HDR_LEN, M_DONTWAIT); \
803 if ((_m) == NULL) { \
804 bdg_dropped++; \
805 return NULL; \
806 } \
807 if (eh != mtod((_m), struct ether_header *)) \
808 bcopy(&save_eh, mtod((_m), struct ether_header *), ETHER_HDR_LEN); \
809 else \
810 bdg_predict++; \
811 } while (0);
812 struct ether_header *eh;
813 struct ifnet *src;
814 struct ifnet *ifp, *last;
815 int shared = bdg_copy ; /* someone else is using the mbuf */
816 int once = 0; /* loop only once */
817 struct ifnet *real_dst = dst ; /* real dst from ether_output */
818 struct ip_fw_args args;
819 #ifdef PFIL_HOOKS
820 struct packet_filter_hook *pfh;
821 int rv;
822 #endif /* PFIL_HOOKS */
823 struct ether_header save_eh;
824
825 DEB(quad_t ticks; ticks = rdtsc();)
826
827 args.rule = NULL; /* did we match a firewall rule ? */
828 /* Fetch state from dummynet tag, ignore others */
829 for (;m0->m_type == MT_TAG; m0 = m0->m_next)
830 if (m0->_m_tag_id == PACKET_TAG_DUMMYNET) {
831 args.rule = ((struct dn_pkt *)m0)->rule;
832 shared = 0; /* For sure this is our own mbuf. */
833 }
834 if (args.rule == NULL)
835 bdg_thru++; /* first time through bdg_forward, count packet */
836
837 /*
838 * The packet arrives with the Ethernet header at the front.
839 */
840 eh = mtod(m0, struct ether_header *);
841
842 src = m0->m_pkthdr.rcvif;
843 if (src == NULL) /* packet from ether_output */
844 dst = bridge_dst_lookup(eh, ifp2sc[real_dst->if_index].cluster);
845
846 if (dst == BDG_DROP) { /* this should not happen */
847 printf("xx bdg_forward for BDG_DROP\n");
848 m_freem(m0);
849 bdg_dropped++;
850 return NULL;
851 }
852 if (dst == BDG_LOCAL) { /* this should not happen as well */
853 printf("xx ouch, bdg_forward for local pkt\n");
854 return m0;
855 }
856 if (dst == BDG_BCAST || dst == BDG_MCAST) {
857 /* need a copy for the local stack */
858 shared = 1 ;
859 }
860
861 /*
862 * Do filtering in a very similar way to what is done in ip_output.
863 * Only if firewall is loaded, enabled, and the packet is not
864 * from ether_output() (src==NULL, or we would filter it twice).
865 * Additional restrictions may apply e.g. non-IP, short packets,
866 * and pkts already gone through a pipe.
867 */
868 if (src != NULL && (
869 #ifdef PFIL_HOOKS
870 ((pfh = pfil_hook_get(PFIL_IN, &inetsw[ip_protox[IPPROTO_IP]].pr_pfh)) != NULL && bdg_ipf !=0) ||
871 #endif
872 (IPFW_LOADED && bdg_ipfw != 0))) {
873
874 int i;
875
876 if (args.rule != NULL && fw_one_pass)
877 goto forward; /* packet already partially processed */
878 /*
879 * i need some amt of data to be contiguous, and in case others need
880 * the packet (shared==1) also better be in the first mbuf.
881 */
882 i = min(m0->m_pkthdr.len, max_protohdr) ;
883 if ( shared || m0->m_len < i) {
884 m0 = m_pullup(m0, i) ;
885 if (m0 == NULL) {
886 printf("-- bdg: pullup failed.\n") ;
887 bdg_dropped++;
888 return NULL ;
889 }
890 eh = mtod(m0, struct ether_header *);
891 }
892
893 /*
894 * Processing below expects the Ethernet header is stripped.
895 * Furthermore, the mbuf chain might be replaced at various
896 * places. To deal with this we copy the header to a temporary
897 * location, strip the header, and restore it as needed.
898 */
899 bcopy(eh, &save_eh, ETHER_HDR_LEN); /* local copy for restore */
900 m_adj(m0, ETHER_HDR_LEN); /* temporarily strip header */
901
902 #ifdef PFIL_HOOKS
903 /*
904 * NetBSD-style generic packet filter, pfil(9), hooks.
905 * Enables ipf(8) in bridging.
906 */
907 if (pfh != NULL && m0->m_pkthdr.len >= sizeof(struct ip) &&
908 ntohs(save_eh.ether_type) == ETHERTYPE_IP) {
909 /*
910 * before calling the firewall, swap fields the same as IP does.
911 * here we assume the pkt is an IP one and the header is contiguous
912 */
913 struct ip *ip = mtod(m0, struct ip *);
914
915 ip->ip_len = ntohs(ip->ip_len);
916 ip->ip_off = ntohs(ip->ip_off);
917
918 do {
919 if (pfh->pfil_func) {
920 rv = pfh->pfil_func(ip, ip->ip_hl << 2, src, 0, &m0);
921 if (m0 == NULL) {
922 bdg_dropped++;
923 return NULL;
924 }
925 if (rv != 0) {
926 EH_RESTORE(m0); /* restore Ethernet header */
927 return m0;
928 }
929 ip = mtod(m0, struct ip *);
930 }
931 } while ((pfh = TAILQ_NEXT(pfh, pfil_link)) != NULL);
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 if (m0 != NULL)
964 EH_RESTORE(m0); /* restore Ethernet header */
965
966 if ( (i & IP_FW_PORT_DENY_FLAG) || m0 == NULL) /* drop */
967 return m0 ;
968
969 if (i == 0) /* a PASS rule. */
970 goto forward ;
971 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG)) {
972 /*
973 * Pass the pkt to dummynet, which consumes it.
974 * If shared, make a copy and keep the original.
975 */
976 struct mbuf *m ;
977
978 if (shared) {
979 m = m_copypacket(m0, M_DONTWAIT);
980 if (m == NULL) { /* copy failed, give up */
981 bdg_dropped++;
982 return NULL;
983 }
984 } else {
985 m = m0 ; /* pass the original to dummynet */
986 m0 = NULL ; /* and nothing back to the caller */
987 }
988
989 args.oif = real_dst;
990 ip_dn_io_ptr(m, (i & 0xffff),DN_TO_BDG_FWD, &args);
991 return m0 ;
992 }
993 /*
994 * XXX at some point, add support for divert/forward actions.
995 * If none of the above matches, we have to drop the packet.
996 */
997 bdg_ipfw_drops++ ;
998 return m0 ;
999 }
1000 forward:
1001 /*
1002 * Again, bring up the headers in case of shared bufs to avoid
1003 * corruptions in the future.
1004 */
1005 if ( shared ) {
1006 int i = min(m0->m_pkthdr.len, max_protohdr) ;
1007
1008 m0 = m_pullup(m0, i) ;
1009 if (m0 == NULL) {
1010 bdg_dropped++ ;
1011 return NULL ;
1012 }
1013 /* NB: eh is not used below; no need to recalculate it */
1014 }
1015
1016 /*
1017 * now real_dst is used to determine the cluster where to forward.
1018 * For packets coming from ether_input, this is the one of the 'src'
1019 * interface, whereas for locally generated packets (src==NULL) it
1020 * is the cluster of the original destination interface, which
1021 * was already saved into real_dst.
1022 */
1023 if (src != NULL)
1024 real_dst = src ;
1025
1026 last = NULL;
1027 IFNET_RLOCK();
1028 if (dst == BDG_BCAST || dst == BDG_MCAST || dst == BDG_UNKNOWN) {
1029 ifp = TAILQ_FIRST(&ifnet) ; /* scan all ports */
1030 once = 0 ;
1031 } else {
1032 ifp = dst ;
1033 once = 1 ;
1034 }
1035 if ((uintptr_t)(ifp) <= (u_int)BDG_FORWARD)
1036 panic("bdg_forward: bad dst");
1037
1038 for (;;) {
1039 if (last) { /* need to forward packet leftover from previous loop */
1040 struct mbuf *m ;
1041 if (shared == 0 && once ) { /* no need to copy */
1042 m = m0 ;
1043 m0 = NULL ; /* original is gone */
1044 } else {
1045 m = m_copypacket(m0, M_DONTWAIT);
1046 if (m == NULL) {
1047 IFNET_RUNLOCK();
1048 printf("bdg_forward: sorry, m_copypacket failed!\n");
1049 bdg_dropped++ ;
1050 return m0 ; /* the original is still there... */
1051 }
1052 }
1053 if (!IF_HANDOFF(&last->if_snd, m, last)) {
1054 #if 0
1055 BDG_MUTE(last); /* should I also mute ? */
1056 #endif
1057 }
1058 BDG_STAT(last, BDG_OUT);
1059 last = NULL ;
1060 if (once)
1061 break ;
1062 }
1063 if (ifp == NULL)
1064 break ;
1065 /*
1066 * If the interface is used for bridging, not muted, not full,
1067 * up and running, is not the source interface, and belongs to
1068 * the same cluster as the 'real_dst', then send here.
1069 */
1070 if ( BDG_USED(ifp) && !BDG_MUTED(ifp) && !_IF_QFULL(&ifp->if_snd) &&
1071 (ifp->if_flags & (IFF_UP|IFF_RUNNING)) == (IFF_UP|IFF_RUNNING) &&
1072 ifp != src && BDG_SAMECLUSTER(ifp, real_dst) )
1073 last = ifp ;
1074 ifp = TAILQ_NEXT(ifp, if_link) ;
1075 if (ifp == NULL)
1076 once = 1 ;
1077 }
1078 IFNET_RUNLOCK();
1079 DEB(bdg_fw_ticks += (u_long)(rdtsc() - ticks) ; bdg_fw_count++ ;
1080 if (bdg_fw_count != 0) bdg_fw_avg = bdg_fw_ticks/bdg_fw_count; )
1081 return m0 ;
1082 #undef EH_RESTORE
1083 }
1084
1085 /*
1086 * initialization of bridge code.
1087 */
1088 static int
1089 bdginit(void)
1090 {
1091 printf("BRIDGE 020214 loaded\n");
1092
1093 ifp2sc = malloc(BDG_MAX_PORTS * sizeof(struct bdg_softc),
1094 M_IFADDR, M_WAITOK | M_ZERO );
1095 if (ifp2sc == NULL)
1096 return ENOMEM ;
1097
1098 bridge_in_ptr = bridge_in;
1099 bdg_forward_ptr = bdg_forward;
1100 bdgtakeifaces_ptr = reconfigure_bridge;
1101
1102 n_clusters = 0;
1103 clusters = NULL;
1104 do_bridge=0;
1105
1106 bzero(&bdg_stats, sizeof(bdg_stats) );
1107 bdgtakeifaces_ptr();
1108 bdg_timeout(0);
1109 return 0 ;
1110 }
1111
1112 /*
1113 * initialization code, both for static and dynamic loading.
1114 */
1115 static int
1116 bridge_modevent(module_t mod, int type, void *unused)
1117 {
1118 int s;
1119 int err = 0 ;
1120
1121 switch (type) {
1122 case MOD_LOAD:
1123 if (BDG_LOADED) {
1124 err = EEXIST;
1125 break ;
1126 }
1127 s = splimp();
1128 err = bdginit();
1129 splx(s);
1130 break;
1131 case MOD_UNLOAD:
1132 #if !defined(KLD_MODULE)
1133 printf("bridge statically compiled, cannot unload\n");
1134 err = EINVAL ;
1135 #else
1136 s = splimp();
1137 do_bridge = 0;
1138 bridge_in_ptr = NULL;
1139 bdg_forward_ptr = NULL;
1140 bdgtakeifaces_ptr = NULL;
1141 untimeout(bdg_timeout, NULL, bdg_timeout_h);
1142 bridge_off();
1143 if (clusters)
1144 free(clusters, M_IFADDR);
1145 free(ifp2sc, M_IFADDR);
1146 ifp2sc = NULL ;
1147 splx(s);
1148 #endif
1149 break;
1150 default:
1151 err = EINVAL ;
1152 break;
1153 }
1154 return err;
1155 }
1156
1157 static moduledata_t bridge_mod = {
1158 "bridge",
1159 bridge_modevent,
1160 0
1161 };
1162
1163 DECLARE_MODULE(bridge, bridge_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
1164 MODULE_VERSION(bridge, 1);
Cache object: 742e07efa8584a71cf9a989ed6875666
|