ng_bridge.c revision 184205
1/*
2 * ng_bridge.c
3 */
4
5/*-
6 * Copyright (c) 2000 Whistle Communications, Inc.
7 * All rights reserved.
8 *
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.
19 *
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
36 * OF SUCH DAMAGE.
37 *
38 * Author: Archie Cobbs <archie@freebsd.org>
39 *
40 * $FreeBSD: head/sys/netgraph/ng_bridge.c 184205 2008-10-23 15:53:51Z des $
41 */
42
43/*
44 * ng_bridge(4) netgraph node type
45 *
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.
51 *
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.
56 *
57 * This node is optimzed for stable networks, where machines jump
58 * from one port to the other only rarely.
59 */
60
61#include <sys/param.h>
62#include <sys/systm.h>
63#include <sys/kernel.h>
64#include <sys/malloc.h>
65#include <sys/mbuf.h>
66#include <sys/errno.h>
67#include <sys/syslog.h>
68#include <sys/socket.h>
69#include <sys/ctype.h>
70#include <sys/vimage.h>
71
72#include <net/if.h>
73#include <net/ethernet.h>
74
75#include <netinet/in.h>
76#include <netinet/ip_fw.h>
77
78#include <netgraph/ng_message.h>
79#include <netgraph/netgraph.h>
80#include <netgraph/ng_parse.h>
81#include <netgraph/ng_bridge.h>
82
83#ifdef NG_SEPARATE_MALLOC
84MALLOC_DEFINE(M_NETGRAPH_BRIDGE, "netgraph_bridge", "netgraph bridge node ");
85#else
86#define M_NETGRAPH_BRIDGE M_NETGRAPH
87#endif
88
89/* Per-link private data */
90struct ng_bridge_link {
91	hook_p				hook;		/* netgraph hook */
92	u_int16_t			loopCount;	/* loop ignore timer */
93	struct ng_bridge_link_stats	stats;		/* link stats */
94};
95
96/* Per-node private data */
97struct ng_bridge_private {
98	struct ng_bridge_bucket	*tab;		/* hash table bucket array */
99	struct ng_bridge_link	*links[NG_BRIDGE_MAX_LINKS];
100	struct ng_bridge_config	conf;		/* node configuration */
101	node_p			node;		/* netgraph node */
102	u_int			numHosts;	/* num entries in table */
103	u_int			numBuckets;	/* num buckets in table */
104	u_int			hashMask;	/* numBuckets - 1 */
105	int			numLinks;	/* num connected links */
106	struct callout		timer;		/* one second periodic timer */
107};
108typedef struct ng_bridge_private *priv_p;
109
110/* Information about a host, stored in a hash table entry */
111struct ng_bridge_hent {
112	struct ng_bridge_host		host;	/* actual host info */
113	SLIST_ENTRY(ng_bridge_hent)	next;	/* next entry in bucket */
114};
115
116/* Hash table bucket declaration */
117SLIST_HEAD(ng_bridge_bucket, ng_bridge_hent);
118
119/* Netgraph node methods */
120static ng_constructor_t	ng_bridge_constructor;
121static ng_rcvmsg_t	ng_bridge_rcvmsg;
122static ng_shutdown_t	ng_bridge_shutdown;
123static ng_newhook_t	ng_bridge_newhook;
124static ng_rcvdata_t	ng_bridge_rcvdata;
125static ng_disconnect_t	ng_bridge_disconnect;
126
127/* Other internal functions */
128static struct	ng_bridge_host *ng_bridge_get(priv_p priv, const u_char *addr);
129static int	ng_bridge_put(priv_p priv, const u_char *addr, int linkNum);
130static void	ng_bridge_rehash(priv_p priv);
131static void	ng_bridge_remove_hosts(priv_p priv, int linkNum);
132static void	ng_bridge_timeout(node_p node, hook_p hook, void *arg1, int arg2);
133static const	char *ng_bridge_nodename(node_p node);
134
135/* Ethernet broadcast */
136static const u_char ng_bridge_bcast_addr[ETHER_ADDR_LEN] =
137    { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
138
139/* Store each hook's link number in the private field */
140#define LINK_NUM(hook)		(*(u_int16_t *)(&(hook)->private))
141
142/* Compare Ethernet addresses using 32 and 16 bit words instead of bytewise */
143#define ETHER_EQUAL(a,b)	(((const u_int32_t *)(a))[0] \
144					== ((const u_int32_t *)(b))[0] \
145				    && ((const u_int16_t *)(a))[2] \
146					== ((const u_int16_t *)(b))[2])
147
148/* Minimum and maximum number of hash buckets. Must be a power of two. */
149#define MIN_BUCKETS		(1 << 5)	/* 32 */
150#define MAX_BUCKETS		(1 << 14)	/* 16384 */
151
152/* Configuration default values */
153#define DEFAULT_LOOP_TIMEOUT	60
154#define DEFAULT_MAX_STALENESS	(15 * 60)	/* same as ARP timeout */
155#define DEFAULT_MIN_STABLE_AGE	1
156
157/******************************************************************
158		    NETGRAPH PARSE TYPES
159******************************************************************/
160
161/*
162 * How to determine the length of the table returned by NGM_BRIDGE_GET_TABLE
163 */
164static int
165ng_bridge_getTableLength(const struct ng_parse_type *type,
166	const u_char *start, const u_char *buf)
167{
168	const struct ng_bridge_host_ary *const hary
169	    = (const struct ng_bridge_host_ary *)(buf - sizeof(u_int32_t));
170
171	return hary->numHosts;
172}
173
174/* Parse type for struct ng_bridge_host_ary */
175static const struct ng_parse_struct_field ng_bridge_host_type_fields[]
176	= NG_BRIDGE_HOST_TYPE_INFO(&ng_parse_enaddr_type);
177static const struct ng_parse_type ng_bridge_host_type = {
178	&ng_parse_struct_type,
179	&ng_bridge_host_type_fields
180};
181static const struct ng_parse_array_info ng_bridge_hary_type_info = {
182	&ng_bridge_host_type,
183	ng_bridge_getTableLength
184};
185static const struct ng_parse_type ng_bridge_hary_type = {
186	&ng_parse_array_type,
187	&ng_bridge_hary_type_info
188};
189static const struct ng_parse_struct_field ng_bridge_host_ary_type_fields[]
190	= NG_BRIDGE_HOST_ARY_TYPE_INFO(&ng_bridge_hary_type);
191static const struct ng_parse_type ng_bridge_host_ary_type = {
192	&ng_parse_struct_type,
193	&ng_bridge_host_ary_type_fields
194};
195
196/* Parse type for struct ng_bridge_config */
197static const struct ng_parse_fixedarray_info ng_bridge_ipfwary_type_info = {
198	&ng_parse_uint8_type,
199	NG_BRIDGE_MAX_LINKS
200};
201static const struct ng_parse_type ng_bridge_ipfwary_type = {
202	&ng_parse_fixedarray_type,
203	&ng_bridge_ipfwary_type_info
204};
205static const struct ng_parse_struct_field ng_bridge_config_type_fields[]
206	= NG_BRIDGE_CONFIG_TYPE_INFO(&ng_bridge_ipfwary_type);
207static const struct ng_parse_type ng_bridge_config_type = {
208	&ng_parse_struct_type,
209	&ng_bridge_config_type_fields
210};
211
212/* Parse type for struct ng_bridge_link_stat */
213static const struct ng_parse_struct_field ng_bridge_stats_type_fields[]
214	= NG_BRIDGE_STATS_TYPE_INFO;
215static const struct ng_parse_type ng_bridge_stats_type = {
216	&ng_parse_struct_type,
217	&ng_bridge_stats_type_fields
218};
219
220/* List of commands and how to convert arguments to/from ASCII */
221static const struct ng_cmdlist ng_bridge_cmdlist[] = {
222	{
223	  NGM_BRIDGE_COOKIE,
224	  NGM_BRIDGE_SET_CONFIG,
225	  "setconfig",
226	  &ng_bridge_config_type,
227	  NULL
228	},
229	{
230	  NGM_BRIDGE_COOKIE,
231	  NGM_BRIDGE_GET_CONFIG,
232	  "getconfig",
233	  NULL,
234	  &ng_bridge_config_type
235	},
236	{
237	  NGM_BRIDGE_COOKIE,
238	  NGM_BRIDGE_RESET,
239	  "reset",
240	  NULL,
241	  NULL
242	},
243	{
244	  NGM_BRIDGE_COOKIE,
245	  NGM_BRIDGE_GET_STATS,
246	  "getstats",
247	  &ng_parse_uint32_type,
248	  &ng_bridge_stats_type
249	},
250	{
251	  NGM_BRIDGE_COOKIE,
252	  NGM_BRIDGE_CLR_STATS,
253	  "clrstats",
254	  &ng_parse_uint32_type,
255	  NULL
256	},
257	{
258	  NGM_BRIDGE_COOKIE,
259	  NGM_BRIDGE_GETCLR_STATS,
260	  "getclrstats",
261	  &ng_parse_uint32_type,
262	  &ng_bridge_stats_type
263	},
264	{
265	  NGM_BRIDGE_COOKIE,
266	  NGM_BRIDGE_GET_TABLE,
267	  "gettable",
268	  NULL,
269	  &ng_bridge_host_ary_type
270	},
271	{ 0 }
272};
273
274/* Node type descriptor */
275static 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,
285};
286NETGRAPH_INIT(bridge, &ng_bridge_typestruct);
287
288/******************************************************************
289		    NETGRAPH NODE METHODS
290******************************************************************/
291
292/*
293 * Node constructor
294 */
295static int
296ng_bridge_constructor(node_p node)
297{
298	priv_p priv;
299
300	/* Allocate and initialize private info */
301	priv = malloc(sizeof(*priv), M_NETGRAPH_BRIDGE, M_NOWAIT | M_ZERO);
302	if (priv == NULL)
303		return (ENOMEM);
304	ng_callout_init(&priv->timer);
305
306	/* Allocate and initialize hash table, etc. */
307	priv->tab = malloc(	    MIN_BUCKETS * sizeof(*priv->tab), M_NETGRAPH_BRIDGE, M_NOWAIT | M_ZERO);
308	if (priv->tab == NULL) {
309		free(priv, M_NETGRAPH_BRIDGE);
310		return (ENOMEM);
311	}
312	priv->numBuckets = MIN_BUCKETS;
313	priv->hashMask = MIN_BUCKETS - 1;
314	priv->conf.debugLevel = 1;
315	priv->conf.loopTimeout = DEFAULT_LOOP_TIMEOUT;
316	priv->conf.maxStaleness = DEFAULT_MAX_STALENESS;
317	priv->conf.minStableAge = DEFAULT_MIN_STABLE_AGE;
318
319	/*
320	 * This node has all kinds of stuff that could be screwed by SMP.
321	 * Until it gets it's own internal protection, we go through in
322	 * single file. This could hurt a machine bridging beteen two
323	 * GB ethernets so it should be fixed.
324	 * When it's fixed the process SHOULD NOT SLEEP, spinlocks please!
325	 * (and atomic ops )
326	 */
327	NG_NODE_FORCE_WRITER(node);
328	NG_NODE_SET_PRIVATE(node, priv);
329	priv->node = node;
330
331	/* Start timer; timer is always running while node is alive */
332	ng_callout(&priv->timer, node, NULL, hz, ng_bridge_timeout, NULL, 0);
333
334	/* Done */
335	return (0);
336}
337
338/*
339 * Method for attaching a new hook
340 */
341static	int
342ng_bridge_newhook(node_p node, hook_p hook, const char *name)
343{
344	const priv_p priv = NG_NODE_PRIVATE(node);
345
346	/* Check for a link hook */
347	if (strncmp(name, NG_BRIDGE_HOOK_LINK_PREFIX,
348	    strlen(NG_BRIDGE_HOOK_LINK_PREFIX)) == 0) {
349		const char *cp;
350		char *eptr;
351		u_long linkNum;
352
353		cp = name + strlen(NG_BRIDGE_HOOK_LINK_PREFIX);
354		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
355			return (EINVAL);
356		linkNum = strtoul(cp, &eptr, 10);
357		if (*eptr != '\0' || linkNum >= NG_BRIDGE_MAX_LINKS)
358			return (EINVAL);
359		if (priv->links[linkNum] != NULL)
360			return (EISCONN);
361		priv->links[linkNum] = malloc(		    sizeof(*priv->links[linkNum]), M_NETGRAPH_BRIDGE, M_NOWAIT|M_ZERO);
362		if (priv->links[linkNum] == NULL)
363			return (ENOMEM);
364		priv->links[linkNum]->hook = hook;
365		NG_HOOK_SET_PRIVATE(hook, (void *)linkNum);
366		priv->numLinks++;
367		return (0);
368	}
369
370	/* Unknown hook name */
371	return (EINVAL);
372}
373
374/*
375 * Receive a control message
376 */
377static int
378ng_bridge_rcvmsg(node_p node, item_p item, hook_p lasthook)
379{
380	const priv_p priv = NG_NODE_PRIVATE(node);
381	struct ng_mesg *resp = NULL;
382	int error = 0;
383	struct ng_mesg *msg;
384
385	NGI_GET_MSG(item, msg);
386	switch (msg->header.typecookie) {
387	case NGM_BRIDGE_COOKIE:
388		switch (msg->header.cmd) {
389		case NGM_BRIDGE_GET_CONFIG:
390		    {
391			struct ng_bridge_config *conf;
392
393			NG_MKRESPONSE(resp, msg,
394			    sizeof(struct ng_bridge_config), M_NOWAIT);
395			if (resp == NULL) {
396				error = ENOMEM;
397				break;
398			}
399			conf = (struct ng_bridge_config *)resp->data;
400			*conf = priv->conf;	/* no sanity checking needed */
401			break;
402		    }
403		case NGM_BRIDGE_SET_CONFIG:
404		    {
405			struct ng_bridge_config *conf;
406			int i;
407
408			if (msg->header.arglen
409			    != sizeof(struct ng_bridge_config)) {
410				error = EINVAL;
411				break;
412			}
413			conf = (struct ng_bridge_config *)msg->data;
414			priv->conf = *conf;
415			for (i = 0; i < NG_BRIDGE_MAX_LINKS; i++)
416				priv->conf.ipfw[i] = !!priv->conf.ipfw[i];
417			break;
418		    }
419		case NGM_BRIDGE_RESET:
420		    {
421			int i;
422
423			/* Flush all entries in the hash table */
424			ng_bridge_remove_hosts(priv, -1);
425
426			/* Reset all loop detection counters and stats */
427			for (i = 0; i < NG_BRIDGE_MAX_LINKS; i++) {
428				if (priv->links[i] == NULL)
429					continue;
430				priv->links[i]->loopCount = 0;
431				bzero(&priv->links[i]->stats,
432				    sizeof(priv->links[i]->stats));
433			}
434			break;
435		    }
436		case NGM_BRIDGE_GET_STATS:
437		case NGM_BRIDGE_CLR_STATS:
438		case NGM_BRIDGE_GETCLR_STATS:
439		    {
440			struct ng_bridge_link *link;
441			int linkNum;
442
443			/* Get link number */
444			if (msg->header.arglen != sizeof(u_int32_t)) {
445				error = EINVAL;
446				break;
447			}
448			linkNum = *((u_int32_t *)msg->data);
449			if (linkNum < 0 || linkNum >= NG_BRIDGE_MAX_LINKS) {
450				error = EINVAL;
451				break;
452			}
453			if ((link = priv->links[linkNum]) == NULL) {
454				error = ENOTCONN;
455				break;
456			}
457
458			/* Get/clear stats */
459			if (msg->header.cmd != NGM_BRIDGE_CLR_STATS) {
460				NG_MKRESPONSE(resp, msg,
461				    sizeof(link->stats), M_NOWAIT);
462				if (resp == NULL) {
463					error = ENOMEM;
464					break;
465				}
466				bcopy(&link->stats,
467				    resp->data, sizeof(link->stats));
468			}
469			if (msg->header.cmd != NGM_BRIDGE_GET_STATS)
470				bzero(&link->stats, sizeof(link->stats));
471			break;
472		    }
473		case NGM_BRIDGE_GET_TABLE:
474		    {
475			struct ng_bridge_host_ary *ary;
476			struct ng_bridge_hent *hent;
477			int i = 0, bucket;
478
479			NG_MKRESPONSE(resp, msg, sizeof(*ary)
480			    + (priv->numHosts * sizeof(*ary->hosts)), M_NOWAIT);
481			if (resp == NULL) {
482				error = ENOMEM;
483				break;
484			}
485			ary = (struct ng_bridge_host_ary *)resp->data;
486			ary->numHosts = priv->numHosts;
487			for (bucket = 0; bucket < priv->numBuckets; bucket++) {
488				SLIST_FOREACH(hent, &priv->tab[bucket], next)
489					ary->hosts[i++] = hent->host;
490			}
491			break;
492		    }
493		default:
494			error = EINVAL;
495			break;
496		}
497		break;
498	default:
499		error = EINVAL;
500		break;
501	}
502
503	/* Done */
504	NG_RESPOND_MSG(error, node, item, resp);
505	NG_FREE_MSG(msg);
506	return (error);
507}
508
509/*
510 * Receive data on a hook
511 */
512static int
513ng_bridge_rcvdata(hook_p hook, item_p item)
514{
515	const node_p node = NG_HOOK_NODE(hook);
516	const priv_p priv = NG_NODE_PRIVATE(node);
517	struct ng_bridge_host *host;
518	struct ng_bridge_link *link;
519	struct ether_header *eh;
520	int error = 0, linkNum, linksSeen;
521	int manycast;
522	struct mbuf *m;
523	struct ng_bridge_link *firstLink;
524
525	NGI_GET_M(item, m);
526	/* Get link number */
527	linkNum = (intptr_t)NG_HOOK_PRIVATE(hook);
528	KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
529	    ("%s: linkNum=%u", __func__, linkNum));
530	link = priv->links[linkNum];
531	KASSERT(link != NULL, ("%s: link%d null", __func__, linkNum));
532
533	/* Sanity check packet and pull up header */
534	if (m->m_pkthdr.len < ETHER_HDR_LEN) {
535		link->stats.recvRunts++;
536		NG_FREE_ITEM(item);
537		NG_FREE_M(m);
538		return (EINVAL);
539	}
540	if (m->m_len < ETHER_HDR_LEN && !(m = m_pullup(m, ETHER_HDR_LEN))) {
541		link->stats.memoryFailures++;
542		NG_FREE_ITEM(item);
543		return (ENOBUFS);
544	}
545	eh = mtod(m, struct ether_header *);
546	if ((eh->ether_shost[0] & 1) != 0) {
547		link->stats.recvInvalid++;
548		NG_FREE_ITEM(item);
549		NG_FREE_M(m);
550		return (EINVAL);
551	}
552
553	/* Is link disabled due to a loopback condition? */
554	if (link->loopCount != 0) {
555		link->stats.loopDrops++;
556		NG_FREE_ITEM(item);
557		NG_FREE_M(m);
558		return (ELOOP);		/* XXX is this an appropriate error? */
559	}
560
561	/* Update stats */
562	link->stats.recvPackets++;
563	link->stats.recvOctets += m->m_pkthdr.len;
564	if ((manycast = (eh->ether_dhost[0] & 1)) != 0) {
565		if (ETHER_EQUAL(eh->ether_dhost, ng_bridge_bcast_addr)) {
566			link->stats.recvBroadcasts++;
567			manycast = 2;
568		} else
569			link->stats.recvMulticasts++;
570	}
571
572	/* Look up packet's source Ethernet address in hashtable */
573	if ((host = ng_bridge_get(priv, eh->ether_shost)) != NULL) {
574
575		/* Update time since last heard from this host */
576		host->staleness = 0;
577
578		/* Did host jump to a different link? */
579		if (host->linkNum != linkNum) {
580
581			/*
582			 * If the host's old link was recently established
583			 * on the old link and it's already jumped to a new
584			 * link, declare a loopback condition.
585			 */
586			if (host->age < priv->conf.minStableAge) {
587
588				/* Log the problem */
589				if (priv->conf.debugLevel >= 2) {
590					struct ifnet *ifp = m->m_pkthdr.rcvif;
591					char suffix[32];
592
593					if (ifp != NULL)
594						snprintf(suffix, sizeof(suffix),
595						    " (%s)", ifp->if_xname);
596					else
597						*suffix = '\0';
598					log(LOG_WARNING, "ng_bridge: %s:"
599					    " loopback detected on %s%s\n",
600					    ng_bridge_nodename(node),
601					    NG_HOOK_NAME(hook), suffix);
602				}
603
604				/* Mark link as linka non grata */
605				link->loopCount = priv->conf.loopTimeout;
606				link->stats.loopDetects++;
607
608				/* Forget all hosts on this link */
609				ng_bridge_remove_hosts(priv, linkNum);
610
611				/* Drop packet */
612				link->stats.loopDrops++;
613				NG_FREE_ITEM(item);
614				NG_FREE_M(m);
615				return (ELOOP);		/* XXX appropriate? */
616			}
617
618			/* Move host over to new link */
619			host->linkNum = linkNum;
620			host->age = 0;
621		}
622	} else {
623		if (!ng_bridge_put(priv, eh->ether_shost, linkNum)) {
624			link->stats.memoryFailures++;
625			NG_FREE_ITEM(item);
626			NG_FREE_M(m);
627			return (ENOMEM);
628		}
629	}
630
631	/* Run packet through ipfw processing, if enabled */
632#if 0
633	if (priv->conf.ipfw[linkNum] && V_fw_enable && ip_fw_chk_ptr != NULL) {
634		/* XXX not implemented yet */
635	}
636#endif
637
638	/*
639	 * If unicast and destination host known, deliver to host's link,
640	 * unless it is the same link as the packet came in on.
641	 */
642	if (!manycast) {
643
644		/* Determine packet destination link */
645		if ((host = ng_bridge_get(priv, eh->ether_dhost)) != NULL) {
646			struct ng_bridge_link *const destLink
647			    = priv->links[host->linkNum];
648
649			/* If destination same as incoming link, do nothing */
650			KASSERT(destLink != NULL,
651			    ("%s: link%d null", __func__, host->linkNum));
652			if (destLink == link) {
653				NG_FREE_ITEM(item);
654				NG_FREE_M(m);
655				return (0);
656			}
657
658			/* Deliver packet out the destination link */
659			destLink->stats.xmitPackets++;
660			destLink->stats.xmitOctets += m->m_pkthdr.len;
661			NG_FWD_NEW_DATA(error, item, destLink->hook, m);
662			return (error);
663		}
664
665		/* Destination host is not known */
666		link->stats.recvUnknown++;
667	}
668
669	/* Distribute unknown, multicast, broadcast pkts to all other links */
670	firstLink = NULL;
671	for (linkNum = linksSeen = 0; linksSeen <= priv->numLinks; linkNum++) {
672		struct ng_bridge_link *destLink;
673		struct mbuf *m2 = NULL;
674
675		/*
676		 * If we have checked all the links then now
677		 * send the original on its reserved link
678		 */
679		if (linksSeen == priv->numLinks) {
680			/* If we never saw a good link, leave. */
681			if (firstLink == NULL) {
682				NG_FREE_ITEM(item);
683				NG_FREE_M(m);
684				return (0);
685			}
686			destLink = firstLink;
687		} else {
688			destLink = priv->links[linkNum];
689			if (destLink != NULL)
690				linksSeen++;
691			/* Skip incoming link and disconnected links */
692			if (destLink == NULL || destLink == link) {
693				continue;
694			}
695			if (firstLink == NULL) {
696				/*
697				 * This is the first usable link we have found.
698				 * Reserve it for the originals.
699				 * If we never find another we save a copy.
700				 */
701				firstLink = destLink;
702				continue;
703			}
704
705			/*
706			 * It's usable link but not the reserved (first) one.
707			 * Copy mbuf info for sending.
708			 */
709			m2 = m_dup(m, M_DONTWAIT);	/* XXX m_copypacket() */
710			if (m2 == NULL) {
711				link->stats.memoryFailures++;
712				NG_FREE_ITEM(item);
713				NG_FREE_M(m);
714				return (ENOBUFS);
715			}
716		}
717
718		/* Update stats */
719		destLink->stats.xmitPackets++;
720		destLink->stats.xmitOctets += m->m_pkthdr.len;
721		switch (manycast) {
722		case 0:					/* unicast */
723			break;
724		case 1:					/* multicast */
725			destLink->stats.xmitMulticasts++;
726			break;
727		case 2:					/* broadcast */
728			destLink->stats.xmitBroadcasts++;
729			break;
730		}
731
732		/* Send packet */
733		if (destLink == firstLink) {
734			/*
735			 * If we've sent all the others, send the original
736			 * on the first link we found.
737			 */
738			NG_FWD_NEW_DATA(error, item, destLink->hook, m);
739			break; /* always done last - not really needed. */
740		} else {
741			NG_SEND_DATA_ONLY(error, destLink->hook, m2);
742		}
743	}
744	return (error);
745}
746
747/*
748 * Shutdown node
749 */
750static int
751ng_bridge_shutdown(node_p node)
752{
753	const priv_p priv = NG_NODE_PRIVATE(node);
754
755	/*
756	 * Shut down everything including the timer.  Even if the
757	 * callout has already been dequeued and is about to be
758	 * run, ng_bridge_timeout() won't be fired as the node
759	 * is already marked NGF_INVALID, so we're safe to free
760	 * the node now.
761	 */
762	KASSERT(priv->numLinks == 0 && priv->numHosts == 0,
763	    ("%s: numLinks=%d numHosts=%d",
764	    __func__, priv->numLinks, priv->numHosts));
765	ng_uncallout(&priv->timer, node);
766	NG_NODE_SET_PRIVATE(node, NULL);
767	NG_NODE_UNREF(node);
768	free(priv->tab, M_NETGRAPH_BRIDGE);
769	free(priv, M_NETGRAPH_BRIDGE);
770	return (0);
771}
772
773/*
774 * Hook disconnection.
775 */
776static int
777ng_bridge_disconnect(hook_p hook)
778{
779	const priv_p priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
780	int linkNum;
781
782	/* Get link number */
783	linkNum = (intptr_t)NG_HOOK_PRIVATE(hook);
784	KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
785	    ("%s: linkNum=%u", __func__, linkNum));
786
787	/* Remove all hosts associated with this link */
788	ng_bridge_remove_hosts(priv, linkNum);
789
790	/* Free associated link information */
791	KASSERT(priv->links[linkNum] != NULL, ("%s: no link", __func__));
792	free(priv->links[linkNum], M_NETGRAPH_BRIDGE);
793	priv->links[linkNum] = NULL;
794	priv->numLinks--;
795
796	/* If no more hooks, go away */
797	if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
798	&& (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))) {
799		ng_rmnode_self(NG_HOOK_NODE(hook));
800	}
801	return (0);
802}
803
804/******************************************************************
805		    HASH TABLE FUNCTIONS
806******************************************************************/
807
808/*
809 * Hash algorithm
810 */
811#define HASH(addr,mask)		( (((const u_int16_t *)(addr))[0] 	\
812				 ^ ((const u_int16_t *)(addr))[1] 	\
813				 ^ ((const u_int16_t *)(addr))[2]) & (mask) )
814
815/*
816 * Find a host entry in the table.
817 */
818static struct ng_bridge_host *
819ng_bridge_get(priv_p priv, const u_char *addr)
820{
821	const int bucket = HASH(addr, priv->hashMask);
822	struct ng_bridge_hent *hent;
823
824	SLIST_FOREACH(hent, &priv->tab[bucket], next) {
825		if (ETHER_EQUAL(hent->host.addr, addr))
826			return (&hent->host);
827	}
828	return (NULL);
829}
830
831/*
832 * Add a new host entry to the table. This assumes the host doesn't
833 * already exist in the table. Returns 1 on success, 0 if there
834 * was a memory allocation failure.
835 */
836static int
837ng_bridge_put(priv_p priv, const u_char *addr, int linkNum)
838{
839	const int bucket = HASH(addr, priv->hashMask);
840	struct ng_bridge_hent *hent;
841
842#ifdef INVARIANTS
843	/* Assert that entry does not already exist in hashtable */
844	SLIST_FOREACH(hent, &priv->tab[bucket], next) {
845		KASSERT(!ETHER_EQUAL(hent->host.addr, addr),
846		    ("%s: entry %6D exists in table", __func__, addr, ":"));
847	}
848#endif
849
850	/* Allocate and initialize new hashtable entry */
851	hent = malloc(	    sizeof(*hent), M_NETGRAPH_BRIDGE, M_NOWAIT);
852	if (hent == NULL)
853		return (0);
854	bcopy(addr, hent->host.addr, ETHER_ADDR_LEN);
855	hent->host.linkNum = linkNum;
856	hent->host.staleness = 0;
857	hent->host.age = 0;
858
859	/* Add new element to hash bucket */
860	SLIST_INSERT_HEAD(&priv->tab[bucket], hent, next);
861	priv->numHosts++;
862
863	/* Resize table if necessary */
864	ng_bridge_rehash(priv);
865	return (1);
866}
867
868/*
869 * Resize the hash table. We try to maintain the number of buckets
870 * such that the load factor is in the range 0.25 to 1.0.
871 *
872 * If we can't get the new memory then we silently fail. This is OK
873 * because things will still work and we'll try again soon anyway.
874 */
875static void
876ng_bridge_rehash(priv_p priv)
877{
878	struct ng_bridge_bucket *newTab;
879	int oldBucket, newBucket;
880	int newNumBuckets;
881	u_int newMask;
882
883	/* Is table too full or too empty? */
884	if (priv->numHosts > priv->numBuckets
885	    && (priv->numBuckets << 1) <= MAX_BUCKETS)
886		newNumBuckets = priv->numBuckets << 1;
887	else if (priv->numHosts < (priv->numBuckets >> 2)
888	    && (priv->numBuckets >> 2) >= MIN_BUCKETS)
889		newNumBuckets = priv->numBuckets >> 2;
890	else
891		return;
892	newMask = newNumBuckets - 1;
893
894	/* Allocate and initialize new table */
895	newTab = malloc(	    newNumBuckets * sizeof(*newTab), M_NETGRAPH_BRIDGE, M_NOWAIT | M_ZERO);
896	if (newTab == NULL)
897		return;
898
899	/* Move all entries from old table to new table */
900	for (oldBucket = 0; oldBucket < priv->numBuckets; oldBucket++) {
901		struct ng_bridge_bucket *const oldList = &priv->tab[oldBucket];
902
903		while (!SLIST_EMPTY(oldList)) {
904			struct ng_bridge_hent *const hent
905			    = SLIST_FIRST(oldList);
906
907			SLIST_REMOVE_HEAD(oldList, next);
908			newBucket = HASH(hent->host.addr, newMask);
909			SLIST_INSERT_HEAD(&newTab[newBucket], hent, next);
910		}
911	}
912
913	/* Replace old table with new one */
914	if (priv->conf.debugLevel >= 3) {
915		log(LOG_INFO, "ng_bridge: %s: table size %d -> %d\n",
916		    ng_bridge_nodename(priv->node),
917		    priv->numBuckets, newNumBuckets);
918	}
919	free(priv->tab, M_NETGRAPH_BRIDGE);
920	priv->numBuckets = newNumBuckets;
921	priv->hashMask = newMask;
922	priv->tab = newTab;
923	return;
924}
925
926/******************************************************************
927		    MISC FUNCTIONS
928******************************************************************/
929
930/*
931 * Remove all hosts associated with a specific link from the hashtable.
932 * If linkNum == -1, then remove all hosts in the table.
933 */
934static void
935ng_bridge_remove_hosts(priv_p priv, int linkNum)
936{
937	int bucket;
938
939	for (bucket = 0; bucket < priv->numBuckets; bucket++) {
940		struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
941
942		while (*hptr != NULL) {
943			struct ng_bridge_hent *const hent = *hptr;
944
945			if (linkNum == -1 || hent->host.linkNum == linkNum) {
946				*hptr = SLIST_NEXT(hent, next);
947				free(hent, M_NETGRAPH_BRIDGE);
948				priv->numHosts--;
949			} else
950				hptr = &SLIST_NEXT(hent, next);
951		}
952	}
953}
954
955/*
956 * Handle our once-per-second timeout event. We do two things:
957 * we decrement link->loopCount for those links being muted due to
958 * a detected loopback condition, and we remove any hosts from
959 * the hashtable whom we haven't heard from in a long while.
960 */
961static void
962ng_bridge_timeout(node_p node, hook_p hook, void *arg1, int arg2)
963{
964	const priv_p priv = NG_NODE_PRIVATE(node);
965	int bucket;
966	int counter = 0;
967	int linkNum;
968
969	/* Update host time counters and remove stale entries */
970	for (bucket = 0; bucket < priv->numBuckets; bucket++) {
971		struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
972
973		while (*hptr != NULL) {
974			struct ng_bridge_hent *const hent = *hptr;
975
976			/* Make sure host's link really exists */
977			KASSERT(priv->links[hent->host.linkNum] != NULL,
978			    ("%s: host %6D on nonexistent link %d\n",
979			    __func__, hent->host.addr, ":",
980			    hent->host.linkNum));
981
982			/* Remove hosts we haven't heard from in a while */
983			if (++hent->host.staleness >= priv->conf.maxStaleness) {
984				*hptr = SLIST_NEXT(hent, next);
985				free(hent, M_NETGRAPH_BRIDGE);
986				priv->numHosts--;
987			} else {
988				if (hent->host.age < 0xffff)
989					hent->host.age++;
990				hptr = &SLIST_NEXT(hent, next);
991				counter++;
992			}
993		}
994	}
995	KASSERT(priv->numHosts == counter,
996	    ("%s: hosts: %d != %d", __func__, priv->numHosts, counter));
997
998	/* Decrease table size if necessary */
999	ng_bridge_rehash(priv);
1000
1001	/* Decrease loop counter on muted looped back links */
1002	for (counter = linkNum = 0; linkNum < NG_BRIDGE_MAX_LINKS; linkNum++) {
1003		struct ng_bridge_link *const link = priv->links[linkNum];
1004
1005		if (link != NULL) {
1006			if (link->loopCount != 0) {
1007				link->loopCount--;
1008				if (link->loopCount == 0
1009				    && priv->conf.debugLevel >= 2) {
1010					log(LOG_INFO, "ng_bridge: %s:"
1011					    " restoring looped back link%d\n",
1012					    ng_bridge_nodename(node), linkNum);
1013				}
1014			}
1015			counter++;
1016		}
1017	}
1018	KASSERT(priv->numLinks == counter,
1019	    ("%s: links: %d != %d", __func__, priv->numLinks, counter));
1020
1021	/* Register a new timeout, keeping the existing node reference */
1022	ng_callout(&priv->timer, node, NULL, hz, ng_bridge_timeout, NULL, 0);
1023}
1024
1025/*
1026 * Return node's "name", even if it doesn't have one.
1027 */
1028static const char *
1029ng_bridge_nodename(node_p node)
1030{
1031	static char name[NG_NODESIZ];
1032
1033	if (NG_NODE_NAME(node) != NULL)
1034		snprintf(name, sizeof(name), "%s", NG_NODE_NAME(node));
1035	else
1036		snprintf(name, sizeof(name), "[%x]", ng_node2ID(node));
1037	return name;
1038}
1039
1040