6 * Copyright (c) 2000 Whistle Communications, Inc.
9 * Subject to the following obligations and disclaimer of warranty, use and
10 * redistribution of this software, in source or object code forms, with or
11 * without modifications are expressly permitted by Whistle Communications;
12 * provided, however, that:
13 * 1. Any and all reproductions of the source or object code must include the
14 * copyright notice above and the following disclaimer of warranties; and
15 * 2. No rights are granted, in any manner or form, to use Whistle
16 * Communications, Inc. trademarks, including the mark "WHISTLE
17 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18 * such appears in the above copyright notice or in the software.
20 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
38 * Author: Archie Cobbs <archie@freebsd.org>
44 * ng_bridge(4) netgraph node type
46 * The node performs standard intelligent Ethernet bridging over
47 * each of its connected hooks, or links. A simple loop detection
48 * algorithm is included which disables a link for priv->conf.loopTimeout
49 * seconds when a host is seen to have jumped from one link to
50 * another within priv->conf.minStableAge seconds.
52 * We keep a hashtable that maps Ethernet addresses to host info,
53 * which is contained in struct ng_bridge_host's. These structures
54 * tell us on which link the host may be found. A host's entry will
55 * expire after priv->conf.maxStaleness seconds.
57 * This node is optimzed for stable networks, where machines jump
58 * from one port to the other only rarely.
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/kernel.h>
65 #include <sys/malloc.h>
67 #include <sys/errno.h>
68 #include <sys/rwlock.h>
69 #include <sys/syslog.h>
70 #include <sys/socket.h>
71 #include <sys/ctype.h>
74 #include <net/ethernet.h>
77 #include <netinet/in.h>
78 #if 0 /* not used yet */
79 #include <netinet/ip_fw.h>
81 #include <netgraph/ng_message.h>
82 #include <netgraph/netgraph.h>
83 #include <netgraph/ng_parse.h>
84 #include <netgraph/ng_bridge.h>
86 #ifdef NG_SEPARATE_MALLOC
87 MALLOC_DEFINE(M_NETGRAPH_BRIDGE, "netgraph_bridge", "netgraph bridge node");
89 #define M_NETGRAPH_BRIDGE M_NETGRAPH
92 /* Per-link private data */
93 struct ng_bridge_link {
94 hook_p hook; /* netgraph hook */
95 u_int16_t loopCount; /* loop ignore timer */
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_link *links[NG_BRIDGE_MAX_LINKS];
103 struct ng_bridge_config conf; /* node configuration */
104 node_p node; /* netgraph node */
105 u_int numHosts; /* num entries in table */
106 u_int numBuckets; /* num buckets in table */
107 u_int hashMask; /* numBuckets - 1 */
108 int numLinks; /* num connected links */
109 int persistent; /* can exist w/o hooks */
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, int linkNum);
134 static void ng_bridge_rehash(priv_p priv);
135 static void ng_bridge_remove_hosts(priv_p priv, int linkNum);
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 /* Store each hook's link number in the private field */
144 #define LINK_NUM(hook) (*(u_int16_t *)(&(hook)->private))
146 /* Compare Ethernet addresses using 32 and 16 bit words instead of bytewise */
147 #define ETHER_EQUAL(a,b) (((const u_int32_t *)(a))[0] \
148 == ((const u_int32_t *)(b))[0] \
149 && ((const u_int16_t *)(a))[2] \
150 == ((const u_int16_t *)(b))[2])
152 /* Minimum and maximum number of hash buckets. Must be a power of two. */
153 #define MIN_BUCKETS (1 << 5) /* 32 */
154 #define MAX_BUCKETS (1 << 14) /* 16384 */
156 /* Configuration default values */
157 #define DEFAULT_LOOP_TIMEOUT 60
158 #define DEFAULT_MAX_STALENESS (15 * 60) /* same as ARP timeout */
159 #define DEFAULT_MIN_STABLE_AGE 1
161 /******************************************************************
163 ******************************************************************/
166 * How to determine the length of the table returned by NGM_BRIDGE_GET_TABLE
169 ng_bridge_getTableLength(const struct ng_parse_type *type,
170 const u_char *start, const u_char *buf)
172 const struct ng_bridge_host_ary *const hary
173 = (const struct ng_bridge_host_ary *)(buf - sizeof(u_int32_t));
175 return hary->numHosts;
178 /* Parse type for struct ng_bridge_host_ary */
179 static const struct ng_parse_struct_field ng_bridge_host_type_fields[]
180 = NG_BRIDGE_HOST_TYPE_INFO(&ng_parse_enaddr_type);
181 static const struct ng_parse_type ng_bridge_host_type = {
182 &ng_parse_struct_type,
183 &ng_bridge_host_type_fields
185 static const struct ng_parse_array_info ng_bridge_hary_type_info = {
186 &ng_bridge_host_type,
187 ng_bridge_getTableLength
189 static const struct ng_parse_type ng_bridge_hary_type = {
190 &ng_parse_array_type,
191 &ng_bridge_hary_type_info
193 static const struct ng_parse_struct_field ng_bridge_host_ary_type_fields[]
194 = NG_BRIDGE_HOST_ARY_TYPE_INFO(&ng_bridge_hary_type);
195 static const struct ng_parse_type ng_bridge_host_ary_type = {
196 &ng_parse_struct_type,
197 &ng_bridge_host_ary_type_fields
200 /* Parse type for struct ng_bridge_config */
201 static const struct ng_parse_fixedarray_info ng_bridge_ipfwary_type_info = {
202 &ng_parse_uint8_type,
205 static const struct ng_parse_type ng_bridge_ipfwary_type = {
206 &ng_parse_fixedarray_type,
207 &ng_bridge_ipfwary_type_info
209 static const struct ng_parse_struct_field ng_bridge_config_type_fields[]
210 = NG_BRIDGE_CONFIG_TYPE_INFO(&ng_bridge_ipfwary_type);
211 static const struct ng_parse_type ng_bridge_config_type = {
212 &ng_parse_struct_type,
213 &ng_bridge_config_type_fields
216 /* Parse type for struct ng_bridge_link_stat */
217 static const struct ng_parse_struct_field ng_bridge_stats_type_fields[]
218 = NG_BRIDGE_STATS_TYPE_INFO;
219 static const struct ng_parse_type ng_bridge_stats_type = {
220 &ng_parse_struct_type,
221 &ng_bridge_stats_type_fields
224 /* List of commands and how to convert arguments to/from ASCII */
225 static const struct ng_cmdlist ng_bridge_cmdlist[] = {
228 NGM_BRIDGE_SET_CONFIG,
230 &ng_bridge_config_type,
235 NGM_BRIDGE_GET_CONFIG,
238 &ng_bridge_config_type
249 NGM_BRIDGE_GET_STATS,
251 &ng_parse_uint32_type,
252 &ng_bridge_stats_type
256 NGM_BRIDGE_CLR_STATS,
258 &ng_parse_uint32_type,
263 NGM_BRIDGE_GETCLR_STATS,
265 &ng_parse_uint32_type,
266 &ng_bridge_stats_type
270 NGM_BRIDGE_GET_TABLE,
273 &ng_bridge_host_ary_type
277 NGM_BRIDGE_SET_PERSISTENT,
285 /* Node type descriptor */
286 static struct ng_type ng_bridge_typestruct = {
287 .version = NG_ABI_VERSION,
288 .name = NG_BRIDGE_NODE_TYPE,
289 .constructor = ng_bridge_constructor,
290 .rcvmsg = ng_bridge_rcvmsg,
291 .shutdown = ng_bridge_shutdown,
292 .newhook = ng_bridge_newhook,
293 .rcvdata = ng_bridge_rcvdata,
294 .disconnect = ng_bridge_disconnect,
295 .cmdlist = ng_bridge_cmdlist,
297 NETGRAPH_INIT(bridge, &ng_bridge_typestruct);
299 /******************************************************************
300 NETGRAPH NODE METHODS
301 ******************************************************************/
307 ng_bridge_constructor(node_p node)
311 /* Allocate and initialize private info */
312 priv = malloc(sizeof(*priv), M_NETGRAPH_BRIDGE, M_WAITOK | M_ZERO);
313 ng_callout_init(&priv->timer);
315 /* Allocate and initialize hash table, etc. */
316 priv->tab = malloc(MIN_BUCKETS * sizeof(*priv->tab),
317 M_NETGRAPH_BRIDGE, M_WAITOK | M_ZERO);
318 priv->numBuckets = MIN_BUCKETS;
319 priv->hashMask = MIN_BUCKETS - 1;
320 priv->conf.debugLevel = 1;
321 priv->conf.loopTimeout = DEFAULT_LOOP_TIMEOUT;
322 priv->conf.maxStaleness = DEFAULT_MAX_STALENESS;
323 priv->conf.minStableAge = DEFAULT_MIN_STABLE_AGE;
326 * This node has all kinds of stuff that could be screwed by SMP.
327 * Until it gets it's own internal protection, we go through in
328 * single file. This could hurt a machine bridging beteen two
329 * GB ethernets so it should be fixed.
330 * When it's fixed the process SHOULD NOT SLEEP, spinlocks please!
333 NG_NODE_FORCE_WRITER(node);
334 NG_NODE_SET_PRIVATE(node, priv);
337 /* Start timer; timer is always running while node is alive */
338 ng_callout(&priv->timer, node, NULL, hz, ng_bridge_timeout, NULL, 0);
345 * Method for attaching a new hook
348 ng_bridge_newhook(node_p node, hook_p hook, const char *name)
350 const priv_p priv = NG_NODE_PRIVATE(node);
352 /* Check for a link hook */
353 if (strncmp(name, NG_BRIDGE_HOOK_LINK_PREFIX,
354 strlen(NG_BRIDGE_HOOK_LINK_PREFIX)) == 0) {
359 cp = name + strlen(NG_BRIDGE_HOOK_LINK_PREFIX);
360 if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
362 linkNum = strtoul(cp, &eptr, 10);
363 if (*eptr != '\0' || linkNum >= NG_BRIDGE_MAX_LINKS)
365 if (priv->links[linkNum] != NULL)
367 priv->links[linkNum] = malloc(sizeof(*priv->links[linkNum]),
368 M_NETGRAPH_BRIDGE, M_NOWAIT|M_ZERO);
369 if (priv->links[linkNum] == NULL)
371 priv->links[linkNum]->hook = hook;
372 NG_HOOK_SET_PRIVATE(hook, (void *)linkNum);
377 /* Unknown hook name */
382 * Receive a control message
385 ng_bridge_rcvmsg(node_p node, item_p item, hook_p lasthook)
387 const priv_p priv = NG_NODE_PRIVATE(node);
388 struct ng_mesg *resp = NULL;
392 NGI_GET_MSG(item, msg);
393 switch (msg->header.typecookie) {
394 case NGM_BRIDGE_COOKIE:
395 switch (msg->header.cmd) {
396 case NGM_BRIDGE_GET_CONFIG:
398 struct ng_bridge_config *conf;
400 NG_MKRESPONSE(resp, msg,
401 sizeof(struct ng_bridge_config), M_NOWAIT);
406 conf = (struct ng_bridge_config *)resp->data;
407 *conf = priv->conf; /* no sanity checking needed */
410 case NGM_BRIDGE_SET_CONFIG:
412 struct ng_bridge_config *conf;
415 if (msg->header.arglen
416 != sizeof(struct ng_bridge_config)) {
420 conf = (struct ng_bridge_config *)msg->data;
422 for (i = 0; i < NG_BRIDGE_MAX_LINKS; i++)
423 priv->conf.ipfw[i] = !!priv->conf.ipfw[i];
426 case NGM_BRIDGE_RESET:
430 /* Flush all entries in the hash table */
431 ng_bridge_remove_hosts(priv, -1);
433 /* Reset all loop detection counters and stats */
434 for (i = 0; i < NG_BRIDGE_MAX_LINKS; i++) {
435 if (priv->links[i] == NULL)
437 priv->links[i]->loopCount = 0;
438 bzero(&priv->links[i]->stats,
439 sizeof(priv->links[i]->stats));
443 case NGM_BRIDGE_GET_STATS:
444 case NGM_BRIDGE_CLR_STATS:
445 case NGM_BRIDGE_GETCLR_STATS:
447 struct ng_bridge_link *link;
450 /* Get link number */
451 if (msg->header.arglen != sizeof(u_int32_t)) {
455 linkNum = *((u_int32_t *)msg->data);
456 if (linkNum < 0 || linkNum >= NG_BRIDGE_MAX_LINKS) {
460 if ((link = priv->links[linkNum]) == NULL) {
465 /* Get/clear stats */
466 if (msg->header.cmd != NGM_BRIDGE_CLR_STATS) {
467 NG_MKRESPONSE(resp, msg,
468 sizeof(link->stats), M_NOWAIT);
474 resp->data, sizeof(link->stats));
476 if (msg->header.cmd != NGM_BRIDGE_GET_STATS)
477 bzero(&link->stats, sizeof(link->stats));
480 case NGM_BRIDGE_GET_TABLE:
482 struct ng_bridge_host_ary *ary;
483 struct ng_bridge_hent *hent;
486 NG_MKRESPONSE(resp, msg, sizeof(*ary)
487 + (priv->numHosts * sizeof(*ary->hosts)), M_NOWAIT);
492 ary = (struct ng_bridge_host_ary *)resp->data;
493 ary->numHosts = priv->numHosts;
494 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
495 SLIST_FOREACH(hent, &priv->tab[bucket], next)
496 ary->hosts[i++] = hent->host;
500 case NGM_BRIDGE_SET_PERSISTENT:
502 priv->persistent = 1;
516 NG_RESPOND_MSG(error, node, item, resp);
522 * Receive data on a hook
525 ng_bridge_rcvdata(hook_p hook, item_p item)
527 const node_p node = NG_HOOK_NODE(hook);
528 const priv_p priv = NG_NODE_PRIVATE(node);
529 struct ng_bridge_host *host;
530 struct ng_bridge_link *link;
531 struct ether_header *eh;
532 int error = 0, linkNum, linksSeen;
535 struct ng_bridge_link *firstLink;
538 /* Get link number */
539 linkNum = (intptr_t)NG_HOOK_PRIVATE(hook);
540 KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
541 ("%s: linkNum=%u", __func__, linkNum));
542 link = priv->links[linkNum];
543 KASSERT(link != NULL, ("%s: link%d null", __func__, linkNum));
545 /* Sanity check packet and pull up header */
546 if (m->m_pkthdr.len < ETHER_HDR_LEN) {
547 link->stats.recvRunts++;
552 if (m->m_len < ETHER_HDR_LEN && !(m = m_pullup(m, ETHER_HDR_LEN))) {
553 link->stats.memoryFailures++;
557 eh = mtod(m, struct ether_header *);
558 if ((eh->ether_shost[0] & 1) != 0) {
559 link->stats.recvInvalid++;
565 /* Is link disabled due to a loopback condition? */
566 if (link->loopCount != 0) {
567 link->stats.loopDrops++;
570 return (ELOOP); /* XXX is this an appropriate error? */
574 link->stats.recvPackets++;
575 link->stats.recvOctets += m->m_pkthdr.len;
576 if ((manycast = (eh->ether_dhost[0] & 1)) != 0) {
577 if (ETHER_EQUAL(eh->ether_dhost, ng_bridge_bcast_addr)) {
578 link->stats.recvBroadcasts++;
581 link->stats.recvMulticasts++;
584 /* Look up packet's source Ethernet address in hashtable */
585 if ((host = ng_bridge_get(priv, eh->ether_shost)) != NULL) {
587 /* Update time since last heard from this host */
590 /* Did host jump to a different link? */
591 if (host->linkNum != linkNum) {
594 * If the host's old link was recently established
595 * on the old link and it's already jumped to a new
596 * link, declare a loopback condition.
598 if (host->age < priv->conf.minStableAge) {
600 /* Log the problem */
601 if (priv->conf.debugLevel >= 2) {
602 struct ifnet *ifp = m->m_pkthdr.rcvif;
606 snprintf(suffix, sizeof(suffix),
607 " (%s)", ifp->if_xname);
610 log(LOG_WARNING, "ng_bridge: %s:"
611 " loopback detected on %s%s\n",
612 ng_bridge_nodename(node),
613 NG_HOOK_NAME(hook), suffix);
616 /* Mark link as linka non grata */
617 link->loopCount = priv->conf.loopTimeout;
618 link->stats.loopDetects++;
620 /* Forget all hosts on this link */
621 ng_bridge_remove_hosts(priv, linkNum);
624 link->stats.loopDrops++;
627 return (ELOOP); /* XXX appropriate? */
630 /* Move host over to new link */
631 host->linkNum = linkNum;
635 if (!ng_bridge_put(priv, eh->ether_shost, linkNum)) {
636 link->stats.memoryFailures++;
643 /* Run packet through ipfw processing, if enabled */
645 if (priv->conf.ipfw[linkNum] && V_fw_enable && V_ip_fw_chk_ptr != NULL) {
646 /* XXX not implemented yet */
651 * If unicast and destination host known, deliver to host's link,
652 * unless it is the same link as the packet came in on.
656 /* Determine packet destination link */
657 if ((host = ng_bridge_get(priv, eh->ether_dhost)) != NULL) {
658 struct ng_bridge_link *const destLink
659 = priv->links[host->linkNum];
661 /* If destination same as incoming link, do nothing */
662 KASSERT(destLink != NULL,
663 ("%s: link%d null", __func__, host->linkNum));
664 if (destLink == link) {
670 /* Deliver packet out the destination link */
671 destLink->stats.xmitPackets++;
672 destLink->stats.xmitOctets += m->m_pkthdr.len;
673 NG_FWD_NEW_DATA(error, item, destLink->hook, m);
677 /* Destination host is not known */
678 link->stats.recvUnknown++;
681 /* Distribute unknown, multicast, broadcast pkts to all other links */
683 for (linkNum = linksSeen = 0; linksSeen <= priv->numLinks; linkNum++) {
684 struct ng_bridge_link *destLink;
685 struct mbuf *m2 = NULL;
688 * If we have checked all the links then now
689 * send the original on its reserved link
691 if (linksSeen == priv->numLinks) {
692 /* If we never saw a good link, leave. */
693 if (firstLink == NULL) {
698 destLink = firstLink;
700 destLink = priv->links[linkNum];
701 if (destLink != NULL)
703 /* Skip incoming link and disconnected links */
704 if (destLink == NULL || destLink == link) {
707 if (firstLink == NULL) {
709 * This is the first usable link we have found.
710 * Reserve it for the originals.
711 * If we never find another we save a copy.
713 firstLink = destLink;
718 * It's usable link but not the reserved (first) one.
719 * Copy mbuf info for sending.
721 m2 = m_dup(m, M_DONTWAIT); /* XXX m_copypacket() */
723 link->stats.memoryFailures++;
731 destLink->stats.xmitPackets++;
732 destLink->stats.xmitOctets += m->m_pkthdr.len;
734 case 0: /* unicast */
736 case 1: /* multicast */
737 destLink->stats.xmitMulticasts++;
739 case 2: /* broadcast */
740 destLink->stats.xmitBroadcasts++;
745 if (destLink == firstLink) {
747 * If we've sent all the others, send the original
748 * on the first link we found.
750 NG_FWD_NEW_DATA(error, item, destLink->hook, m);
751 break; /* always done last - not really needed. */
753 NG_SEND_DATA_ONLY(error, destLink->hook, m2);
763 ng_bridge_shutdown(node_p node)
765 const priv_p priv = NG_NODE_PRIVATE(node);
768 * Shut down everything including the timer. Even if the
769 * callout has already been dequeued and is about to be
770 * run, ng_bridge_timeout() won't be fired as the node
771 * is already marked NGF_INVALID, so we're safe to free
774 KASSERT(priv->numLinks == 0 && priv->numHosts == 0,
775 ("%s: numLinks=%d numHosts=%d",
776 __func__, priv->numLinks, priv->numHosts));
777 ng_uncallout(&priv->timer, node);
778 NG_NODE_SET_PRIVATE(node, NULL);
780 free(priv->tab, M_NETGRAPH_BRIDGE);
781 free(priv, M_NETGRAPH_BRIDGE);
786 * Hook disconnection.
789 ng_bridge_disconnect(hook_p hook)
791 const priv_p priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
794 /* Get link number */
795 linkNum = (intptr_t)NG_HOOK_PRIVATE(hook);
796 KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
797 ("%s: linkNum=%u", __func__, linkNum));
799 /* Remove all hosts associated with this link */
800 ng_bridge_remove_hosts(priv, linkNum);
802 /* Free associated link information */
803 KASSERT(priv->links[linkNum] != NULL, ("%s: no link", __func__));
804 free(priv->links[linkNum], M_NETGRAPH_BRIDGE);
805 priv->links[linkNum] = NULL;
808 /* If no more hooks, go away */
809 if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
810 && (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
811 && !priv->persistent) {
812 ng_rmnode_self(NG_HOOK_NODE(hook));
817 /******************************************************************
819 ******************************************************************/
824 #define HASH(addr,mask) ( (((const u_int16_t *)(addr))[0] \
825 ^ ((const u_int16_t *)(addr))[1] \
826 ^ ((const u_int16_t *)(addr))[2]) & (mask) )
829 * Find a host entry in the table.
831 static struct ng_bridge_host *
832 ng_bridge_get(priv_p priv, const u_char *addr)
834 const int bucket = HASH(addr, priv->hashMask);
835 struct ng_bridge_hent *hent;
837 SLIST_FOREACH(hent, &priv->tab[bucket], next) {
838 if (ETHER_EQUAL(hent->host.addr, addr))
839 return (&hent->host);
845 * Add a new host entry to the table. This assumes the host doesn't
846 * already exist in the table. Returns 1 on success, 0 if there
847 * was a memory allocation failure.
850 ng_bridge_put(priv_p priv, const u_char *addr, int linkNum)
852 const int bucket = HASH(addr, priv->hashMask);
853 struct ng_bridge_hent *hent;
856 /* Assert that entry does not already exist in hashtable */
857 SLIST_FOREACH(hent, &priv->tab[bucket], next) {
858 KASSERT(!ETHER_EQUAL(hent->host.addr, addr),
859 ("%s: entry %6D exists in table", __func__, addr, ":"));
863 /* Allocate and initialize new hashtable entry */
864 hent = malloc(sizeof(*hent), M_NETGRAPH_BRIDGE, M_NOWAIT);
867 bcopy(addr, hent->host.addr, ETHER_ADDR_LEN);
868 hent->host.linkNum = linkNum;
869 hent->host.staleness = 0;
872 /* Add new element to hash bucket */
873 SLIST_INSERT_HEAD(&priv->tab[bucket], hent, next);
876 /* Resize table if necessary */
877 ng_bridge_rehash(priv);
882 * Resize the hash table. We try to maintain the number of buckets
883 * such that the load factor is in the range 0.25 to 1.0.
885 * If we can't get the new memory then we silently fail. This is OK
886 * because things will still work and we'll try again soon anyway.
889 ng_bridge_rehash(priv_p priv)
891 struct ng_bridge_bucket *newTab;
892 int oldBucket, newBucket;
896 /* Is table too full or too empty? */
897 if (priv->numHosts > priv->numBuckets
898 && (priv->numBuckets << 1) <= MAX_BUCKETS)
899 newNumBuckets = priv->numBuckets << 1;
900 else if (priv->numHosts < (priv->numBuckets >> 2)
901 && (priv->numBuckets >> 2) >= MIN_BUCKETS)
902 newNumBuckets = priv->numBuckets >> 2;
905 newMask = newNumBuckets - 1;
907 /* Allocate and initialize new table */
908 newTab = malloc(newNumBuckets * sizeof(*newTab),
909 M_NETGRAPH_BRIDGE, M_NOWAIT | M_ZERO);
913 /* Move all entries from old table to new table */
914 for (oldBucket = 0; oldBucket < priv->numBuckets; oldBucket++) {
915 struct ng_bridge_bucket *const oldList = &priv->tab[oldBucket];
917 while (!SLIST_EMPTY(oldList)) {
918 struct ng_bridge_hent *const hent
919 = SLIST_FIRST(oldList);
921 SLIST_REMOVE_HEAD(oldList, next);
922 newBucket = HASH(hent->host.addr, newMask);
923 SLIST_INSERT_HEAD(&newTab[newBucket], hent, next);
927 /* Replace old table with new one */
928 if (priv->conf.debugLevel >= 3) {
929 log(LOG_INFO, "ng_bridge: %s: table size %d -> %d\n",
930 ng_bridge_nodename(priv->node),
931 priv->numBuckets, newNumBuckets);
933 free(priv->tab, M_NETGRAPH_BRIDGE);
934 priv->numBuckets = newNumBuckets;
935 priv->hashMask = newMask;
940 /******************************************************************
942 ******************************************************************/
945 * Remove all hosts associated with a specific link from the hashtable.
946 * If linkNum == -1, then remove all hosts in the table.
949 ng_bridge_remove_hosts(priv_p priv, int linkNum)
953 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
954 struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
956 while (*hptr != NULL) {
957 struct ng_bridge_hent *const hent = *hptr;
959 if (linkNum == -1 || hent->host.linkNum == linkNum) {
960 *hptr = SLIST_NEXT(hent, next);
961 free(hent, M_NETGRAPH_BRIDGE);
964 hptr = &SLIST_NEXT(hent, next);
970 * Handle our once-per-second timeout event. We do two things:
971 * we decrement link->loopCount for those links being muted due to
972 * a detected loopback condition, and we remove any hosts from
973 * the hashtable whom we haven't heard from in a long while.
976 ng_bridge_timeout(node_p node, hook_p hook, void *arg1, int arg2)
978 const priv_p priv = NG_NODE_PRIVATE(node);
983 /* Update host time counters and remove stale entries */
984 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
985 struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
987 while (*hptr != NULL) {
988 struct ng_bridge_hent *const hent = *hptr;
990 /* Make sure host's link really exists */
991 KASSERT(priv->links[hent->host.linkNum] != NULL,
992 ("%s: host %6D on nonexistent link %d\n",
993 __func__, hent->host.addr, ":",
994 hent->host.linkNum));
996 /* Remove hosts we haven't heard from in a while */
997 if (++hent->host.staleness >= priv->conf.maxStaleness) {
998 *hptr = SLIST_NEXT(hent, next);
999 free(hent, M_NETGRAPH_BRIDGE);
1002 if (hent->host.age < 0xffff)
1004 hptr = &SLIST_NEXT(hent, next);
1009 KASSERT(priv->numHosts == counter,
1010 ("%s: hosts: %d != %d", __func__, priv->numHosts, counter));
1012 /* Decrease table size if necessary */
1013 ng_bridge_rehash(priv);
1015 /* Decrease loop counter on muted looped back links */
1016 for (counter = linkNum = 0; linkNum < NG_BRIDGE_MAX_LINKS; linkNum++) {
1017 struct ng_bridge_link *const link = priv->links[linkNum];
1020 if (link->loopCount != 0) {
1022 if (link->loopCount == 0
1023 && priv->conf.debugLevel >= 2) {
1024 log(LOG_INFO, "ng_bridge: %s:"
1025 " restoring looped back link%d\n",
1026 ng_bridge_nodename(node), linkNum);
1032 KASSERT(priv->numLinks == counter,
1033 ("%s: links: %d != %d", __func__, priv->numLinks, counter));
1035 /* Register a new timeout, keeping the existing node reference */
1036 ng_callout(&priv->timer, node, NULL, hz, ng_bridge_timeout, NULL, 0);
1040 * Return node's "name", even if it doesn't have one.
1043 ng_bridge_nodename(node_p node)
1045 static char name[NG_NODESIZ];
1047 if (NG_NODE_NAME(node) != NULL)
1048 snprintf(name, sizeof(name), "%s", NG_NODE_NAME(node));
1050 snprintf(name, sizeof(name), "[%x]", ng_node2ID(node));