2 * Copyright (c) 2000 Whistle Communications, Inc.
5 * Subject to the following obligations and disclaimer of warranty, use and
6 * redistribution of this software, in source or object code forms, with or
7 * without modifications are expressly permitted by Whistle Communications;
8 * provided, however, that:
9 * 1. Any and all reproductions of the source or object code must include the
10 * copyright notice above and the following disclaimer of warranties; and
11 * 2. No rights are granted, in any manner or form, to use Whistle
12 * Communications, Inc. trademarks, including the mark "WHISTLE
13 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
14 * such appears in the above copyright notice or in the software.
16 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
17 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
18 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
19 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
21 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
22 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
23 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
24 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
25 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
26 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
27 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
28 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
34 * Author: Archie Cobbs <archie@freebsd.org>
40 * ng_bridge(4) netgraph node type
42 * The node performs standard intelligent Ethernet bridging over
43 * each of its connected hooks, or links. A simple loop detection
44 * algorithm is included which disables a link for priv->conf.loopTimeout
45 * seconds when a host is seen to have jumped from one link to
46 * another within priv->conf.minStableAge seconds.
48 * We keep a hashtable that maps Ethernet addresses to host info,
49 * which is contained in struct ng_bridge_host's. These structures
50 * tell us on which link the host may be found. A host's entry will
51 * expire after priv->conf.maxStaleness seconds.
53 * This node is optimzed for stable networks, where machines jump
54 * from one port to the other only rarely.
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/kernel.h>
61 #include <sys/malloc.h>
63 #include <sys/errno.h>
64 #include <sys/rwlock.h>
65 #include <sys/syslog.h>
66 #include <sys/socket.h>
67 #include <sys/ctype.h>
70 #include <net/if_var.h>
71 #include <net/ethernet.h>
74 #include <netinet/in.h>
75 #if 0 /* not used yet */
76 #include <netinet/ip_fw.h>
78 #include <netgraph/ng_message.h>
79 #include <netgraph/netgraph.h>
80 #include <netgraph/ng_parse.h>
81 #include <netgraph/ng_bridge.h>
83 #ifdef NG_SEPARATE_MALLOC
84 static MALLOC_DEFINE(M_NETGRAPH_BRIDGE, "netgraph_bridge",
85 "netgraph bridge node");
87 #define M_NETGRAPH_BRIDGE M_NETGRAPH
90 /* Per-link private data */
91 struct ng_bridge_link {
92 hook_p hook; /* netgraph hook */
93 u_int16_t loopCount; /* loop ignore timer */
94 unsigned int learnMac : 1, /* autolearn macs */
95 sendUnknown : 1;/* send unknown macs out */
96 struct ng_bridge_link_stats stats; /* link stats */
99 /* Per-node private data */
100 struct ng_bridge_private {
101 struct ng_bridge_bucket *tab; /* hash table bucket array */
102 struct ng_bridge_config conf; /* node configuration */
103 node_p node; /* netgraph node */
104 u_int numHosts; /* num entries in table */
105 u_int numBuckets; /* num buckets in table */
106 u_int hashMask; /* numBuckets - 1 */
107 int numLinks; /* num connected links */
108 unsigned int persistent : 1, /* can exist w/o hooks */
109 sendUnknown : 1;/* links receive unknowns by default */
110 struct callout timer; /* one second periodic timer */
112 typedef struct ng_bridge_private *priv_p;
114 /* Information about a host, stored in a hash table entry */
115 struct ng_bridge_hent {
116 struct ng_bridge_host host; /* actual host info */
117 SLIST_ENTRY(ng_bridge_hent) next; /* next entry in bucket */
120 /* Hash table bucket declaration */
121 SLIST_HEAD(ng_bridge_bucket, ng_bridge_hent);
123 /* Netgraph node methods */
124 static ng_constructor_t ng_bridge_constructor;
125 static ng_rcvmsg_t ng_bridge_rcvmsg;
126 static ng_shutdown_t ng_bridge_shutdown;
127 static ng_newhook_t ng_bridge_newhook;
128 static ng_rcvdata_t ng_bridge_rcvdata;
129 static ng_disconnect_t ng_bridge_disconnect;
131 /* Other internal functions */
132 static struct ng_bridge_host *ng_bridge_get(priv_p priv, const u_char *addr);
133 static int ng_bridge_put(priv_p priv, const u_char *addr, link_p link);
134 static void ng_bridge_rehash(priv_p priv);
135 static void ng_bridge_remove_hosts(priv_p priv, link_p link);
136 static void ng_bridge_timeout(node_p node, hook_p hook, void *arg1, int arg2);
137 static const char *ng_bridge_nodename(node_p node);
139 /* Ethernet broadcast */
140 static const u_char ng_bridge_bcast_addr[ETHER_ADDR_LEN] =
141 { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
143 /* Compare Ethernet addresses using 32 and 16 bit words instead of bytewise */
144 #define ETHER_EQUAL(a,b) (((const u_int32_t *)(a))[0] \
145 == ((const u_int32_t *)(b))[0] \
146 && ((const u_int16_t *)(a))[2] \
147 == ((const u_int16_t *)(b))[2])
149 /* Minimum and maximum number of hash buckets. Must be a power of two. */
150 #define MIN_BUCKETS (1 << 5) /* 32 */
151 #define MAX_BUCKETS (1 << 14) /* 16384 */
153 /* Configuration default values */
154 #define DEFAULT_LOOP_TIMEOUT 60
155 #define DEFAULT_MAX_STALENESS (15 * 60) /* same as ARP timeout */
156 #define DEFAULT_MIN_STABLE_AGE 1
158 /******************************************************************
160 ******************************************************************/
163 * How to determine the length of the table returned by NGM_BRIDGE_GET_TABLE
166 ng_bridge_getTableLength(const struct ng_parse_type *type,
167 const u_char *start, const u_char *buf)
169 const struct ng_bridge_host_ary *const hary
170 = (const struct ng_bridge_host_ary *)(buf - sizeof(u_int32_t));
172 return hary->numHosts;
175 /* Parse type for struct ng_bridge_host_ary */
176 static const struct ng_parse_struct_field ng_bridge_host_type_fields[]
177 = NG_BRIDGE_HOST_TYPE_INFO(&ng_parse_enaddr_type);
178 static const struct ng_parse_type ng_bridge_host_type = {
179 &ng_parse_struct_type,
180 &ng_bridge_host_type_fields
182 static const struct ng_parse_array_info ng_bridge_hary_type_info = {
183 &ng_bridge_host_type,
184 ng_bridge_getTableLength
186 static const struct ng_parse_type ng_bridge_hary_type = {
187 &ng_parse_array_type,
188 &ng_bridge_hary_type_info
190 static const struct ng_parse_struct_field ng_bridge_host_ary_type_fields[]
191 = NG_BRIDGE_HOST_ARY_TYPE_INFO(&ng_bridge_hary_type);
192 static const struct ng_parse_type ng_bridge_host_ary_type = {
193 &ng_parse_struct_type,
194 &ng_bridge_host_ary_type_fields
197 /* Parse type for struct ng_bridge_config */
198 static const struct ng_parse_struct_field ng_bridge_config_type_fields[]
199 = NG_BRIDGE_CONFIG_TYPE_INFO;
200 static const struct ng_parse_type ng_bridge_config_type = {
201 &ng_parse_struct_type,
202 &ng_bridge_config_type_fields
205 /* Parse type for struct ng_bridge_link_stat */
206 static const struct ng_parse_struct_field ng_bridge_stats_type_fields[]
207 = NG_BRIDGE_STATS_TYPE_INFO;
208 static const struct ng_parse_type ng_bridge_stats_type = {
209 &ng_parse_struct_type,
210 &ng_bridge_stats_type_fields
213 /* List of commands and how to convert arguments to/from ASCII */
214 static const struct ng_cmdlist ng_bridge_cmdlist[] = {
217 NGM_BRIDGE_SET_CONFIG,
219 &ng_bridge_config_type,
224 NGM_BRIDGE_GET_CONFIG,
227 &ng_bridge_config_type
238 NGM_BRIDGE_GET_STATS,
240 &ng_parse_uint32_type,
241 &ng_bridge_stats_type
245 NGM_BRIDGE_CLR_STATS,
247 &ng_parse_uint32_type,
252 NGM_BRIDGE_GETCLR_STATS,
254 &ng_parse_uint32_type,
255 &ng_bridge_stats_type
259 NGM_BRIDGE_GET_TABLE,
262 &ng_bridge_host_ary_type
266 NGM_BRIDGE_SET_PERSISTENT,
274 /* Node type descriptor */
275 static struct ng_type ng_bridge_typestruct = {
276 .version = NG_ABI_VERSION,
277 .name = NG_BRIDGE_NODE_TYPE,
278 .constructor = ng_bridge_constructor,
279 .rcvmsg = ng_bridge_rcvmsg,
280 .shutdown = ng_bridge_shutdown,
281 .newhook = ng_bridge_newhook,
282 .rcvdata = ng_bridge_rcvdata,
283 .disconnect = ng_bridge_disconnect,
284 .cmdlist = ng_bridge_cmdlist,
286 NETGRAPH_INIT(bridge, &ng_bridge_typestruct);
288 /******************************************************************
289 NETGRAPH NODE METHODS
290 ******************************************************************/
296 ng_bridge_constructor(node_p node)
300 /* Allocate and initialize private info */
301 priv = malloc(sizeof(*priv), M_NETGRAPH_BRIDGE, M_WAITOK | M_ZERO);
302 ng_callout_init(&priv->timer);
304 /* Allocate and initialize hash table, etc. */
305 priv->tab = malloc(MIN_BUCKETS * sizeof(*priv->tab),
306 M_NETGRAPH_BRIDGE, M_WAITOK | M_ZERO);
307 priv->numBuckets = MIN_BUCKETS;
308 priv->hashMask = MIN_BUCKETS - 1;
309 priv->conf.debugLevel = 1;
310 priv->conf.loopTimeout = DEFAULT_LOOP_TIMEOUT;
311 priv->conf.maxStaleness = DEFAULT_MAX_STALENESS;
312 priv->conf.minStableAge = DEFAULT_MIN_STABLE_AGE;
313 priv->sendUnknown = 1; /* classic bridge */
316 * This node has all kinds of stuff that could be screwed by SMP.
317 * Until it gets it's own internal protection, we go through in
318 * single file. This could hurt a machine bridging between two
319 * GB ethernets so it should be fixed.
320 * When it's fixed the process SHOULD NOT SLEEP, spinlocks please!
323 NG_NODE_FORCE_WRITER(node);
324 NG_NODE_SET_PRIVATE(node, priv);
327 /* Start timer; timer is always running while node is alive */
328 ng_callout(&priv->timer, node, NULL, hz, ng_bridge_timeout, NULL, 0);
335 * Method for attaching a new hook
338 ng_bridge_newhook(node_p node, hook_p hook, const char *name)
340 const priv_p priv = NG_NODE_PRIVATE(node);
341 char linkName[NG_HOOKSIZ];
344 const char *prefix = NG_BRIDGE_HOOK_LINK_PREFIX;
347 /* Check for a link hook */
348 if (strlen(name) <= strlen(prefix))
349 return (EINVAL); /* Unknown hook name */
351 isUplink = (name[0] == 'u');
353 prefix = NG_BRIDGE_HOOK_UPLINK_PREFIX;
355 /* primitive parsing */
356 linkNum = strtoul(name + strlen(prefix), NULL, 10);
357 /* validation by comparing against the reconstucted name */
358 snprintf(linkName, sizeof(linkName), "%s%u", prefix, linkNum);
359 if (strcmp(linkName, name) != 0)
362 if (linkNum == 0 && isUplink)
365 if(NG_PEER_NODE(hook) == node)
368 link = malloc(sizeof(*link), M_NETGRAPH_BRIDGE, M_ZERO);
375 link->sendUnknown = 1;
376 if (priv->numLinks == 0) /* if the first link is an uplink */
377 priv->sendUnknown = 0; /* switch to restrictive mode */
380 link->sendUnknown = priv->sendUnknown;
383 NG_HOOK_SET_PRIVATE(hook, link);
389 * Receive a control message
392 ng_bridge_reset_link(hook_p hook, void *arg __unused)
394 link_p priv = NG_HOOK_PRIVATE(hook);
397 bzero(&priv->stats, sizeof(priv->stats));
404 ng_bridge_rcvmsg(node_p node, item_p item, hook_p lasthook)
406 const priv_p priv = NG_NODE_PRIVATE(node);
407 struct ng_mesg *resp = NULL;
411 NGI_GET_MSG(item, msg);
412 switch (msg->header.typecookie) {
413 #ifdef NGM_BRIDGE_TABLE_ABI
414 case NGM_BRIDGE_COOKIE_TBL:
415 switch (msg->header.cmd) {
416 case NGM_BRIDGE_GET_CONFIG:
418 struct ng_bridge_config_tbl *conf;
420 NG_MKRESPONSE(resp, msg, sizeof(*conf),
426 conf = (struct ng_bridge_config_tbl *)resp->data;
427 conf->cfg = priv->conf;
430 case NGM_BRIDGE_SET_CONFIG:
432 struct ng_bridge_config_tbl *conf;
434 if (msg->header.arglen != sizeof(*conf)) {
438 conf = (struct ng_bridge_config_tbl *)msg->data;
439 priv->conf = conf->cfg;
442 case NGM_BRIDGE_GET_TABLE:
444 struct ng_bridge_host_tbl_ary *ary;
445 struct ng_bridge_hent *hent;
448 NG_MKRESPONSE(resp, msg, sizeof(*ary) +
449 (priv->numHosts * sizeof(*ary->hosts)), M_NOWAIT);
454 ary = (struct ng_bridge_host_tbl_ary *)resp->data;
455 ary->numHosts = priv->numHosts;
457 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
458 SLIST_FOREACH(hent, &priv->tab[bucket], next) {
459 const char *name = NG_HOOK_NAME(hent->host.link->hook);
460 const char *prefix = name[0] == 'u' ?
461 NG_BRIDGE_HOOK_UPLINK_PREFIX :
462 NG_BRIDGE_HOOK_LINK_PREFIX;
464 memcpy(ary->hosts[i].addr,
466 sizeof(ary->hosts[i].addr));
467 ary->hosts[i].age = hent->host.age;
468 ary->hosts[i].staleness =
469 hent->host.staleness;
470 ary->hosts[i].linkNum = strtol(
471 name + strlen(prefix), NULL, 10);
478 /* If already handled break, otherwise use new ABI. */
479 if (resp != NULL || error != 0)
481 #endif /* NGM_BRIDGE_TABLE_ABI */
482 case NGM_BRIDGE_COOKIE:
483 switch (msg->header.cmd) {
484 case NGM_BRIDGE_GET_CONFIG:
486 struct ng_bridge_config *conf;
488 NG_MKRESPONSE(resp, msg,
489 sizeof(struct ng_bridge_config), M_NOWAIT);
494 conf = (struct ng_bridge_config *)resp->data;
495 *conf = priv->conf; /* no sanity checking needed */
498 case NGM_BRIDGE_SET_CONFIG:
500 struct ng_bridge_config *conf;
502 if (msg->header.arglen
503 != sizeof(struct ng_bridge_config)) {
507 conf = (struct ng_bridge_config *)msg->data;
511 case NGM_BRIDGE_RESET:
515 /* Flush all entries in the hash table */
516 ng_bridge_remove_hosts(priv, NULL);
518 /* Reset all loop detection counters and stats */
519 NG_NODE_FOREACH_HOOK(node, ng_bridge_reset_link, NULL,
523 case NGM_BRIDGE_GET_STATS:
524 case NGM_BRIDGE_CLR_STATS:
525 case NGM_BRIDGE_GETCLR_STATS:
529 char linkName[NG_HOOKSIZ];
532 /* Get link number */
533 if (msg->header.arglen != sizeof(u_int32_t)) {
537 linkNum = *((int32_t *)msg->data);
539 snprintf(linkName, sizeof(linkName),
540 "%s%u", NG_BRIDGE_HOOK_UPLINK_PREFIX, -linkNum);
542 snprintf(linkName, sizeof(linkName),
543 "%s%u", NG_BRIDGE_HOOK_LINK_PREFIX, linkNum);
545 if ((hook = ng_findhook(node, linkName)) == NULL) {
549 link = NG_HOOK_PRIVATE(hook);
551 /* Get/clear stats */
552 if (msg->header.cmd != NGM_BRIDGE_CLR_STATS) {
553 NG_MKRESPONSE(resp, msg,
554 sizeof(link->stats), M_NOWAIT);
560 resp->data, sizeof(link->stats));
562 if (msg->header.cmd != NGM_BRIDGE_GET_STATS)
563 bzero(&link->stats, sizeof(link->stats));
566 case NGM_BRIDGE_GET_TABLE:
568 struct ng_bridge_host_ary *ary;
569 struct ng_bridge_hent *hent;
572 NG_MKRESPONSE(resp, msg, sizeof(*ary)
573 + (priv->numHosts * sizeof(*ary->hosts)), M_NOWAIT);
578 ary = (struct ng_bridge_host_ary *)resp->data;
579 ary->numHosts = priv->numHosts;
580 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
581 SLIST_FOREACH(hent, &priv->tab[bucket], next) {
582 memcpy(ary->hosts[i].addr,
584 sizeof(ary->hosts[i].addr));
585 ary->hosts[i].age = hent->host.age;
586 ary->hosts[i].staleness = hent->host.staleness;
587 strncpy(ary->hosts[i].hook,
588 NG_HOOK_NAME(hent->host.link->hook),
589 sizeof(ary->hosts[i].hook));
595 case NGM_BRIDGE_SET_PERSISTENT:
597 priv->persistent = 1;
611 NG_RESPOND_MSG(error, node, item, resp);
617 * Receive data on a hook
619 struct ng_bridge_send_ctx {
620 link_p foundFirst, incoming;
626 ng_bridge_send_ctx(hook_p dst, void *arg)
628 struct ng_bridge_send_ctx *ctx = arg;
629 link_p destLink = NG_HOOK_PRIVATE(dst);
630 struct mbuf *m2 = NULL;
633 /* Skip incoming link */
634 if (destLink == ctx->incoming) {
638 /* Skip sending unknowns to undesired links */
639 if (!ctx->manycast && !destLink->sendUnknown)
642 if (ctx->foundFirst == NULL) {
644 * This is the first usable link we have found.
645 * Reserve it for the originals.
646 * If we never find another we save a copy.
648 ctx->foundFirst = destLink;
653 * It's usable link but not the reserved (first) one.
654 * Copy mbuf info for sending.
656 m2 = m_dup(ctx->m, M_NOWAIT); /* XXX m_copypacket() */
658 ctx->incoming->stats.memoryFailures++;
659 ctx->error = ENOBUFS;
660 return (0); /* abort loop */
665 destLink->stats.xmitPackets++;
666 destLink->stats.xmitOctets += m2->m_pkthdr.len;
667 switch (ctx->manycast) {
668 default: /* unknown unicast */
670 case 1: /* multicast */
671 destLink->stats.xmitMulticasts++;
673 case 2: /* broadcast */
674 destLink->stats.xmitBroadcasts++;
679 NG_SEND_DATA_ONLY(error, destLink->hook, m2);
686 ng_bridge_rcvdata(hook_p hook, item_p item)
688 const node_p node = NG_HOOK_NODE(hook);
689 const priv_p priv = NG_NODE_PRIVATE(node);
690 struct ng_bridge_host *host;
691 struct ether_header *eh;
692 struct ng_bridge_send_ctx ctx = { 0 };
695 NGI_GET_M(item, ctx.m);
697 ctx.incoming = NG_HOOK_PRIVATE(hook);
698 /* Sanity check packet and pull up header */
699 if (ctx.m->m_pkthdr.len < ETHER_HDR_LEN) {
700 ctx.incoming->stats.recvRunts++;
705 if (ctx.m->m_len < ETHER_HDR_LEN && !(ctx.m = m_pullup(ctx.m, ETHER_HDR_LEN))) {
706 ctx.incoming->stats.memoryFailures++;
710 eh = mtod(ctx.m, struct ether_header *);
711 if ((eh->ether_shost[0] & 1) != 0) {
712 ctx.incoming->stats.recvInvalid++;
718 /* Is link disabled due to a loopback condition? */
719 if (ctx.incoming->loopCount != 0) {
720 ctx.incoming->stats.loopDrops++;
723 return (ELOOP); /* XXX is this an appropriate error? */
727 ctx.incoming->stats.recvPackets++;
728 ctx.incoming->stats.recvOctets += ctx.m->m_pkthdr.len;
729 if ((ctx.manycast = (eh->ether_dhost[0] & 1)) != 0) {
730 if (ETHER_EQUAL(eh->ether_dhost, ng_bridge_bcast_addr)) {
731 ctx.incoming->stats.recvBroadcasts++;
734 ctx.incoming->stats.recvMulticasts++;
737 /* Look up packet's source Ethernet address in hashtable */
738 if ((host = ng_bridge_get(priv, eh->ether_shost)) != NULL) {
740 /* Update time since last heard from this host */
743 /* Did host jump to a different link? */
744 if (host->link != ctx.incoming) {
747 * If the host's old link was recently established
748 * on the old link and it's already jumped to a new
749 * link, declare a loopback condition.
751 if (host->age < priv->conf.minStableAge) {
753 /* Log the problem */
754 if (priv->conf.debugLevel >= 2) {
755 struct ifnet *ifp = ctx.m->m_pkthdr.rcvif;
759 snprintf(suffix, sizeof(suffix),
760 " (%s)", ifp->if_xname);
763 log(LOG_WARNING, "ng_bridge: %s:"
764 " loopback detected on %s%s\n",
765 ng_bridge_nodename(node),
766 NG_HOOK_NAME(hook), suffix);
769 /* Mark link as linka non grata */
770 ctx.incoming->loopCount = priv->conf.loopTimeout;
771 ctx.incoming->stats.loopDetects++;
773 /* Forget all hosts on this link */
774 ng_bridge_remove_hosts(priv, ctx.incoming);
777 ctx.incoming->stats.loopDrops++;
780 return (ELOOP); /* XXX appropriate? */
783 /* Move host over to new link */
784 host->link = ctx.incoming;
787 } else if (ctx.incoming->learnMac) {
788 if (!ng_bridge_put(priv, eh->ether_shost, ctx.incoming)) {
789 ctx.incoming->stats.memoryFailures++;
796 /* Run packet through ipfw processing, if enabled */
798 if (priv->conf.ipfw[linkNum] && V_fw_enable && V_ip_fw_chk_ptr != NULL) {
799 /* XXX not implemented yet */
804 * If unicast and destination host known, deliver to host's link,
805 * unless it is the same link as the packet came in on.
809 /* Determine packet destination link */
810 if ((host = ng_bridge_get(priv, eh->ether_dhost)) != NULL) {
811 link_p destLink = host->link;
813 /* If destination same as incoming link, do nothing */
814 if (destLink == ctx.incoming) {
820 /* Deliver packet out the destination link */
821 destLink->stats.xmitPackets++;
822 destLink->stats.xmitOctets += ctx.m->m_pkthdr.len;
823 NG_FWD_NEW_DATA(ctx.error, item, destLink->hook, ctx.m);
827 /* Destination host is not known */
828 ctx.incoming->stats.recvUnknown++;
831 /* Distribute unknown, multicast, broadcast pkts to all other links */
832 NG_NODE_FOREACH_HOOK(node, ng_bridge_send_ctx, &ctx, ret);
834 /* If we never saw a good link, leave. */
835 if (ctx.foundFirst == NULL || ctx.error != 0) {
842 * If we've sent all the others, send the original
843 * on the first link we found.
845 NG_FWD_NEW_DATA(ctx.error, item, ctx.foundFirst->hook, ctx.m);
853 ng_bridge_shutdown(node_p node)
855 const priv_p priv = NG_NODE_PRIVATE(node);
858 * Shut down everything including the timer. Even if the
859 * callout has already been dequeued and is about to be
860 * run, ng_bridge_timeout() won't be fired as the node
861 * is already marked NGF_INVALID, so we're safe to free
864 KASSERT(priv->numLinks == 0 && priv->numHosts == 0,
865 ("%s: numLinks=%d numHosts=%d",
866 __func__, priv->numLinks, priv->numHosts));
867 ng_uncallout(&priv->timer, node);
868 NG_NODE_SET_PRIVATE(node, NULL);
870 free(priv->tab, M_NETGRAPH_BRIDGE);
871 free(priv, M_NETGRAPH_BRIDGE);
876 * Hook disconnection.
879 ng_bridge_disconnect(hook_p hook)
881 const priv_p priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
882 link_p link = NG_HOOK_PRIVATE(hook);
884 /* Remove all hosts associated with this link */
885 ng_bridge_remove_hosts(priv, link);
887 /* Free associated link information */
888 free(link, M_NETGRAPH_BRIDGE);
891 /* If no more hooks, go away */
892 if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
893 && (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
894 && !priv->persistent) {
895 ng_rmnode_self(NG_HOOK_NODE(hook));
900 /******************************************************************
902 ******************************************************************/
907 #define HASH(addr,mask) ( (((const u_int16_t *)(addr))[0] \
908 ^ ((const u_int16_t *)(addr))[1] \
909 ^ ((const u_int16_t *)(addr))[2]) & (mask) )
912 * Find a host entry in the table.
914 static struct ng_bridge_host *
915 ng_bridge_get(priv_p priv, const u_char *addr)
917 const int bucket = HASH(addr, priv->hashMask);
918 struct ng_bridge_hent *hent;
920 SLIST_FOREACH(hent, &priv->tab[bucket], next) {
921 if (ETHER_EQUAL(hent->host.addr, addr))
922 return (&hent->host);
928 * Add a new host entry to the table. This assumes the host doesn't
929 * already exist in the table. Returns 1 on success, 0 if there
930 * was a memory allocation failure.
933 ng_bridge_put(priv_p priv, const u_char *addr, link_p link)
935 const int bucket = HASH(addr, priv->hashMask);
936 struct ng_bridge_hent *hent;
939 /* Assert that entry does not already exist in hashtable */
940 SLIST_FOREACH(hent, &priv->tab[bucket], next) {
941 KASSERT(!ETHER_EQUAL(hent->host.addr, addr),
942 ("%s: entry %6D exists in table", __func__, addr, ":"));
946 /* Allocate and initialize new hashtable entry */
947 hent = malloc(sizeof(*hent), M_NETGRAPH_BRIDGE, M_NOWAIT);
950 bcopy(addr, hent->host.addr, ETHER_ADDR_LEN);
951 hent->host.link = link;
952 hent->host.staleness = 0;
955 /* Add new element to hash bucket */
956 SLIST_INSERT_HEAD(&priv->tab[bucket], hent, next);
959 /* Resize table if necessary */
960 ng_bridge_rehash(priv);
965 * Resize the hash table. We try to maintain the number of buckets
966 * such that the load factor is in the range 0.25 to 1.0.
968 * If we can't get the new memory then we silently fail. This is OK
969 * because things will still work and we'll try again soon anyway.
972 ng_bridge_rehash(priv_p priv)
974 struct ng_bridge_bucket *newTab;
975 int oldBucket, newBucket;
979 /* Is table too full or too empty? */
980 if (priv->numHosts > priv->numBuckets
981 && (priv->numBuckets << 1) <= MAX_BUCKETS)
982 newNumBuckets = priv->numBuckets << 1;
983 else if (priv->numHosts < (priv->numBuckets >> 2)
984 && (priv->numBuckets >> 2) >= MIN_BUCKETS)
985 newNumBuckets = priv->numBuckets >> 2;
988 newMask = newNumBuckets - 1;
990 /* Allocate and initialize new table */
991 newTab = malloc(newNumBuckets * sizeof(*newTab),
992 M_NETGRAPH_BRIDGE, M_NOWAIT | M_ZERO);
996 /* Move all entries from old table to new table */
997 for (oldBucket = 0; oldBucket < priv->numBuckets; oldBucket++) {
998 struct ng_bridge_bucket *const oldList = &priv->tab[oldBucket];
1000 while (!SLIST_EMPTY(oldList)) {
1001 struct ng_bridge_hent *const hent
1002 = SLIST_FIRST(oldList);
1004 SLIST_REMOVE_HEAD(oldList, next);
1005 newBucket = HASH(hent->host.addr, newMask);
1006 SLIST_INSERT_HEAD(&newTab[newBucket], hent, next);
1010 /* Replace old table with new one */
1011 if (priv->conf.debugLevel >= 3) {
1012 log(LOG_INFO, "ng_bridge: %s: table size %d -> %d\n",
1013 ng_bridge_nodename(priv->node),
1014 priv->numBuckets, newNumBuckets);
1016 free(priv->tab, M_NETGRAPH_BRIDGE);
1017 priv->numBuckets = newNumBuckets;
1018 priv->hashMask = newMask;
1023 /******************************************************************
1025 ******************************************************************/
1029 * Remove all hosts associated with a specific link from the hashtable.
1030 * If linkNum == -1, then remove all hosts in the table.
1033 ng_bridge_remove_hosts(priv_p priv, link_p link)
1037 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
1038 struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
1040 while (*hptr != NULL) {
1041 struct ng_bridge_hent *const hent = *hptr;
1043 if (link == NULL || hent->host.link == link) {
1044 *hptr = SLIST_NEXT(hent, next);
1045 free(hent, M_NETGRAPH_BRIDGE);
1048 hptr = &SLIST_NEXT(hent, next);
1054 * Handle our once-per-second timeout event. We do two things:
1055 * we decrement link->loopCount for those links being muted due to
1056 * a detected loopback condition, and we remove any hosts from
1057 * the hashtable whom we haven't heard from in a long while.
1060 ng_bridge_unmute(hook_p hook, void *arg)
1062 link_p link = NG_HOOK_PRIVATE(hook);
1063 node_p node = NG_HOOK_NODE(hook);
1064 priv_p priv = NG_NODE_PRIVATE(node);
1067 if (link->loopCount != 0) {
1069 if (link->loopCount == 0 && priv->conf.debugLevel >= 2) {
1070 log(LOG_INFO, "ng_bridge: %s:"
1071 " restoring looped back %s\n",
1072 ng_bridge_nodename(node), NG_HOOK_NAME(hook));
1080 ng_bridge_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1082 const priv_p priv = NG_NODE_PRIVATE(node);
1087 /* Update host time counters and remove stale entries */
1088 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
1089 struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
1091 while (*hptr != NULL) {
1092 struct ng_bridge_hent *const hent = *hptr;
1094 /* Remove hosts we haven't heard from in a while */
1095 if (++hent->host.staleness >= priv->conf.maxStaleness) {
1096 *hptr = SLIST_NEXT(hent, next);
1097 free(hent, M_NETGRAPH_BRIDGE);
1100 if (hent->host.age < 0xffff)
1102 hptr = &SLIST_NEXT(hent, next);
1107 KASSERT(priv->numHosts == counter,
1108 ("%s: hosts: %d != %d", __func__, priv->numHosts, counter));
1110 /* Decrease table size if necessary */
1111 ng_bridge_rehash(priv);
1113 /* Decrease loop counter on muted looped back links */
1115 NG_NODE_FOREACH_HOOK(node, ng_bridge_unmute, &counter, ret);
1116 KASSERT(priv->numLinks == counter,
1117 ("%s: links: %d != %d", __func__, priv->numLinks, counter));
1119 /* Register a new timeout, keeping the existing node reference */
1120 ng_callout(&priv->timer, node, NULL, hz, ng_bridge_timeout, NULL, 0);
1124 * Return node's "name", even if it doesn't have one.
1127 ng_bridge_nodename(node_p node)
1129 static char name[NG_NODESIZ];
1131 if (NG_NODE_HAS_NAME(node))
1132 snprintf(name, sizeof(name), "%s", NG_NODE_NAME(node));
1134 snprintf(name, sizeof(name), "[%x]", ng_node2ID(node));