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