ng_bridge.c revision 70700
1
2/*
3 * ng_bridge.c
4 *
5 * Copyright (c) 2000 Whistle Communications, Inc.
6 * All rights reserved.
7 *
8 * Subject to the following obligations and disclaimer of warranty, use and
9 * redistribution of this software, in source or object code forms, with or
10 * without modifications are expressly permitted by Whistle Communications;
11 * provided, however, that:
12 * 1. Any and all reproductions of the source or object code must include the
13 *    copyright notice above and the following disclaimer of warranties; and
14 * 2. No rights are granted, in any manner or form, to use Whistle
15 *    Communications, Inc. trademarks, including the mark "WHISTLE
16 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17 *    such appears in the above copyright notice or in the software.
18 *
19 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35 * OF SUCH DAMAGE.
36 *
37 * Author: Archie Cobbs <archie@freebsd.org>
38 *
39 * $FreeBSD: head/sys/netgraph/ng_bridge.c 70700 2001-01-06 00:46:47Z julian $
40 */
41
42/*
43 * ng_bridge(4) netgraph node type
44 *
45 * The node performs standard intelligent Ethernet bridging over
46 * each of its connected hooks, or links.  A simple loop detection
47 * algorithm is included which disables a link for priv->conf.loopTimeout
48 * seconds when a host is seen to have jumped from one link to
49 * another within priv->conf.minStableAge seconds.
50 *
51 * We keep a hashtable that maps Ethernet addresses to host info,
52 * which is contained in struct ng_bridge_host's. These structures
53 * tell us on which link the host may be found. A host's entry will
54 * expire after priv->conf.maxStaleness seconds.
55 *
56 * This node is optimzed for stable networks, where machines jump
57 * from one port to the other only rarely.
58 */
59
60#include <sys/param.h>
61#include <sys/systm.h>
62#include <sys/kernel.h>
63#include <sys/malloc.h>
64#include <sys/mbuf.h>
65#include <sys/errno.h>
66#include <sys/syslog.h>
67#include <sys/socket.h>
68#include <sys/ctype.h>
69
70#include <net/if.h>
71#include <net/ethernet.h>
72
73#include <netinet/in.h>
74#include <netinet/ip_fw.h>
75
76#include <netgraph/ng_message.h>
77#include <netgraph/netgraph.h>
78#include <netgraph/ng_parse.h>
79#include <netgraph/ng_bridge.h>
80#include <netgraph/ng_ether.h>
81
82/* Per-link private data */
83struct ng_bridge_link {
84	hook_p				hook;		/* netgraph hook */
85	u_int16_t			loopCount;	/* loop ignore timer */
86	struct ng_bridge_link_stats	stats;		/* link stats */
87};
88
89/* Per-node private data */
90struct ng_bridge_private {
91	struct ng_bridge_bucket	*tab;		/* hash table bucket array */
92	struct ng_bridge_link	*links[NG_BRIDGE_MAX_LINKS];
93	struct ng_bridge_config	conf;		/* node configuration */
94	node_p			node;		/* netgraph node */
95	u_int			numHosts;	/* num entries in table */
96	u_int			numBuckets;	/* num buckets in table */
97	u_int			hashMask;	/* numBuckets - 1 */
98	int			numLinks;	/* num connected links */
99	struct callout		timer;		/* one second periodic timer */
100};
101typedef struct ng_bridge_private *priv_p;
102
103/* Information about a host, stored in a hash table entry */
104struct ng_bridge_hent {
105	struct ng_bridge_host		host;	/* actual host info */
106	SLIST_ENTRY(ng_bridge_hent)	next;	/* next entry in bucket */
107};
108
109/* Hash table bucket declaration */
110SLIST_HEAD(ng_bridge_bucket, ng_bridge_hent);
111
112/* Netgraph node methods */
113static ng_constructor_t	ng_bridge_constructor;
114static ng_rcvmsg_t	ng_bridge_rcvmsg;
115static ng_shutdown_t	ng_bridge_shutdown;
116static ng_newhook_t	ng_bridge_newhook;
117static ng_rcvdata_t	ng_bridge_rcvdata;
118static ng_disconnect_t	ng_bridge_disconnect;
119
120/* Other internal functions */
121static struct	ng_bridge_host *ng_bridge_get(priv_p priv, const u_char *addr);
122static int	ng_bridge_put(priv_p priv, const u_char *addr, int linkNum);
123static void	ng_bridge_rehash(priv_p priv);
124static void	ng_bridge_remove_hosts(priv_p priv, int linkNum);
125static void	ng_bridge_timeout(void *arg);
126static const	char *ng_bridge_nodename(node_p node);
127
128/* Ethernet broadcast */
129static const u_char ng_bridge_bcast_addr[ETHER_ADDR_LEN] =
130    { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
131
132/* Store each hook's link number in the private field */
133#define LINK_NUM(hook)		(*(u_int16_t *)(&(hook)->private))
134
135/* Compare Ethernet addresses using 32 and 16 bit words instead of bytewise */
136#define ETHER_EQUAL(a,b)	(((const u_int32_t *)(a))[0] \
137					== ((const u_int32_t *)(b))[0] \
138				    && ((const u_int16_t *)(a))[2] \
139					== ((const u_int16_t *)(b))[2])
140
141/* Minimum and maximum number of hash buckets. Must be a power of two. */
142#define MIN_BUCKETS		(1 << 5)	/* 32 */
143#define MAX_BUCKETS		(1 << 14)	/* 16384 */
144
145/* Configuration default values */
146#define DEFAULT_LOOP_TIMEOUT	60
147#define DEFAULT_MAX_STALENESS	(15 * 60)	/* same as ARP timeout */
148#define DEFAULT_MIN_STABLE_AGE	1
149
150/******************************************************************
151		    NETGRAPH PARSE TYPES
152******************************************************************/
153
154/*
155 * How to determine the length of the table returned by NGM_BRIDGE_GET_TABLE
156 */
157static int
158ng_bridge_getTableLength(const struct ng_parse_type *type,
159	const u_char *start, const u_char *buf)
160{
161	const struct ng_bridge_host_ary *const hary
162	    = (const struct ng_bridge_host_ary *)(buf - sizeof(u_int32_t));
163
164	return hary->numHosts;
165}
166
167/* Parse type for struct ng_bridge_host_ary */
168static const struct ng_parse_struct_info ng_bridge_host_type_info
169	= NG_BRIDGE_HOST_TYPE_INFO(&ng_ether_enaddr_type);
170static const struct ng_parse_type ng_bridge_host_type = {
171	&ng_parse_struct_type,
172	&ng_bridge_host_type_info
173};
174static const struct ng_parse_array_info ng_bridge_hary_type_info = {
175	&ng_bridge_host_type,
176	ng_bridge_getTableLength
177};
178static const struct ng_parse_type ng_bridge_hary_type = {
179	&ng_parse_array_type,
180	&ng_bridge_hary_type_info
181};
182static const struct ng_parse_struct_info ng_bridge_host_ary_type_info
183	= NG_BRIDGE_HOST_ARY_TYPE_INFO(&ng_bridge_hary_type);
184static const struct ng_parse_type ng_bridge_host_ary_type = {
185	&ng_parse_struct_type,
186	&ng_bridge_host_ary_type_info
187};
188
189/* Parse type for struct ng_bridge_config */
190static const struct ng_parse_fixedarray_info ng_bridge_ipfwary_type_info = {
191	&ng_parse_uint8_type,
192	NG_BRIDGE_MAX_LINKS
193};
194static const struct ng_parse_type ng_bridge_ipfwary_type = {
195	&ng_parse_fixedarray_type,
196	&ng_bridge_ipfwary_type_info
197};
198static const struct ng_parse_struct_info ng_bridge_config_type_info
199	= NG_BRIDGE_CONFIG_TYPE_INFO(&ng_bridge_ipfwary_type);
200static const struct ng_parse_type ng_bridge_config_type = {
201	&ng_parse_struct_type,
202	&ng_bridge_config_type_info
203};
204
205/* Parse type for struct ng_bridge_link_stat */
206static const struct ng_parse_struct_info
207	ng_bridge_stats_type_info = NG_BRIDGE_STATS_TYPE_INFO;
208static const struct ng_parse_type ng_bridge_stats_type = {
209	&ng_parse_struct_type,
210	&ng_bridge_stats_type_info
211};
212
213/* List of commands and how to convert arguments to/from ASCII */
214static const struct ng_cmdlist ng_bridge_cmdlist[] = {
215	{
216	  NGM_BRIDGE_COOKIE,
217	  NGM_BRIDGE_SET_CONFIG,
218	  "setconfig",
219	  &ng_bridge_config_type,
220	  NULL
221	},
222	{
223	  NGM_BRIDGE_COOKIE,
224	  NGM_BRIDGE_GET_CONFIG,
225	  "getconfig",
226	  NULL,
227	  &ng_bridge_config_type
228	},
229	{
230	  NGM_BRIDGE_COOKIE,
231	  NGM_BRIDGE_RESET,
232	  "reset",
233	  NULL,
234	  NULL
235	},
236	{
237	  NGM_BRIDGE_COOKIE,
238	  NGM_BRIDGE_GET_STATS,
239	  "getstats",
240	  &ng_parse_uint32_type,
241	  &ng_bridge_stats_type
242	},
243	{
244	  NGM_BRIDGE_COOKIE,
245	  NGM_BRIDGE_CLR_STATS,
246	  "clrstats",
247	  &ng_parse_uint32_type,
248	  NULL
249	},
250	{
251	  NGM_BRIDGE_COOKIE,
252	  NGM_BRIDGE_GETCLR_STATS,
253	  "getclrstats",
254	  &ng_parse_uint32_type,
255	  &ng_bridge_stats_type
256	},
257	{
258	  NGM_BRIDGE_COOKIE,
259	  NGM_BRIDGE_GET_TABLE,
260	  "gettable",
261	  NULL,
262	  &ng_bridge_host_ary_type
263	},
264	{ 0 }
265};
266
267/* Node type descriptor */
268static struct ng_type ng_bridge_typestruct = {
269	NG_ABI_VERSION,
270	NG_BRIDGE_NODE_TYPE,
271	NULL,
272	ng_bridge_constructor,
273	ng_bridge_rcvmsg,
274	ng_bridge_shutdown,
275	ng_bridge_newhook,
276	NULL,
277	NULL,
278	ng_bridge_rcvdata,
279	ng_bridge_disconnect,
280	ng_bridge_cmdlist,
281};
282NETGRAPH_INIT(bridge, &ng_bridge_typestruct);
283
284/* Depend on ng_ether so we can use the Ethernet parse type */
285MODULE_DEPEND(ng_bridge, ng_ether, 1, 1, 1);
286
287/******************************************************************
288		    NETGRAPH NODE METHODS
289******************************************************************/
290
291/*
292 * Node constructor
293 */
294static int
295ng_bridge_constructor(node_p node)
296{
297	priv_p priv;
298
299	/* Allocate and initialize private info */
300	MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH, M_NOWAIT | M_ZERO);
301	if (priv == NULL)
302		return (ENOMEM);
303	callout_init(&priv->timer, 0);
304
305	/* Allocate and initialize hash table, etc. */
306	MALLOC(priv->tab, struct ng_bridge_bucket *,
307	    MIN_BUCKETS * sizeof(*priv->tab), M_NETGRAPH, M_NOWAIT | M_ZERO);
308	if (priv->tab == NULL) {
309		FREE(priv, M_NETGRAPH);
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	node->flags |= NG_FORCE_WRITER;
328	node->private = priv;
329	priv->node = node;
330
331	/* Start timer by faking a timeout event */
332	node->refs++; /* XXX ????  because of the timeout?*/
333	ng_bridge_timeout(node);
334	return (0);
335}
336
337/*
338 * Method for attaching a new hook
339 */
340static	int
341ng_bridge_newhook(node_p node, hook_p hook, const char *name)
342{
343	const priv_p priv = node->private;
344
345	/* Check for a link hook */
346	if (strncmp(name, NG_BRIDGE_HOOK_LINK_PREFIX,
347	    strlen(NG_BRIDGE_HOOK_LINK_PREFIX)) == 0) {
348		const char *cp;
349		char *eptr;
350		u_long linkNum;
351
352		cp = name + strlen(NG_BRIDGE_HOOK_LINK_PREFIX);
353		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
354			return (EINVAL);
355		linkNum = strtoul(cp, &eptr, 10);
356		if (*eptr != '\0' || linkNum >= NG_BRIDGE_MAX_LINKS)
357			return (EINVAL);
358		if (priv->links[linkNum] != NULL)
359			return (EISCONN);
360		MALLOC(priv->links[linkNum], struct ng_bridge_link *,
361		    sizeof(*priv->links[linkNum]), M_NETGRAPH, M_NOWAIT|M_ZERO);
362		if (priv->links[linkNum] == NULL)
363			return (ENOMEM);
364		priv->links[linkNum]->hook = hook;
365		LINK_NUM(hook) = 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 = node->private;
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 = hook->node;
516	const priv_p priv = node->private;
517	struct ng_bridge_host *host;
518	struct ng_bridge_link *link;
519	struct ether_header *eh;
520	int error = 0, linkNum;
521	int manycast;
522	struct mbuf *m;
523	meta_p meta;
524	struct ng_bridge_link *firstLink;
525
526	NGI_GET_M(item, m);
527	/* Get link number */
528	linkNum = LINK_NUM(hook);
529	KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
530	    ("%s: linkNum=%u", __FUNCTION__, linkNum));
531	link = priv->links[linkNum];
532	KASSERT(link != NULL, ("%s: link%d null", __FUNCTION__, linkNum));
533
534	/* Sanity check packet and pull up header */
535	if (m->m_pkthdr.len < ETHER_HDR_LEN) {
536		link->stats.recvRunts++;
537		NG_FREE_ITEM(item);
538		NG_FREE_M(m);
539		return (EINVAL);
540	}
541	if (m->m_len < ETHER_HDR_LEN && !(m = m_pullup(m, ETHER_HDR_LEN))) {
542		link->stats.memoryFailures++;
543		NG_FREE_ITEM(item);
544		return (ENOBUFS);
545	}
546	eh = mtod(m, struct ether_header *);
547	if ((eh->ether_shost[0] & 1) != 0) {
548		link->stats.recvInvalid++;
549		NG_FREE_ITEM(item);
550		NG_FREE_M(m);
551		return (EINVAL);
552	}
553
554	/* Is link disabled due to a loopback condition? */
555	if (link->loopCount != 0) {
556		link->stats.loopDrops++;
557		NG_FREE_ITEM(item);
558		NG_FREE_M(m);
559		return (ELOOP);		/* XXX is this an appropriate error? */
560	}
561
562	/* Update stats */
563	link->stats.recvPackets++;
564	link->stats.recvOctets += m->m_pkthdr.len;
565	if ((manycast = (eh->ether_dhost[0] & 1)) != 0) {
566		if (ETHER_EQUAL(eh->ether_dhost, ng_bridge_bcast_addr)) {
567			link->stats.recvBroadcasts++;
568			manycast = 2;
569		} else
570			link->stats.recvMulticasts++;
571	}
572
573	/* Look up packet's source Ethernet address in hashtable */
574	if ((host = ng_bridge_get(priv, eh->ether_shost)) != NULL) {
575
576		/* Update time since last heard from this host */
577		host->staleness = 0;
578
579		/* Did host jump to a different link? */
580		if (host->linkNum != linkNum) {
581
582			/*
583			 * If the host's old link was recently established
584			 * on the old link and it's already jumped to a new
585			 * link, declare a loopback condition.
586			 */
587			if (host->age < priv->conf.minStableAge) {
588
589				/* Log the problem */
590				if (priv->conf.debugLevel >= 2) {
591					struct ifnet *ifp = m->m_pkthdr.rcvif;
592					char suffix[32];
593
594					if (ifp != NULL)
595						snprintf(suffix, sizeof(suffix),
596						    " (%s%d)", ifp->if_name,
597						    ifp->if_unit);
598					else
599						*suffix = '\0';
600					log(LOG_WARNING, "ng_bridge: %s:"
601					    " loopback detected on %s%s\n",
602					    ng_bridge_nodename(node),
603					    hook->name, suffix);
604				}
605
606				/* Mark link as linka non grata */
607				link->loopCount = priv->conf.loopTimeout;
608				link->stats.loopDetects++;
609
610				/* Forget all hosts on this link */
611				ng_bridge_remove_hosts(priv, linkNum);
612
613				/* Drop packet */
614				link->stats.loopDrops++;
615				NG_FREE_ITEM(item);
616				NG_FREE_M(m);
617				return (ELOOP);		/* XXX appropriate? */
618			}
619
620			/* Move host over to new link */
621			host->linkNum = linkNum;
622			host->age = 0;
623		}
624	} else {
625		if (!ng_bridge_put(priv, eh->ether_shost, linkNum)) {
626			link->stats.memoryFailures++;
627			NG_FREE_ITEM(item);
628			NG_FREE_M(m);
629			return (ENOMEM);
630		}
631	}
632
633	/* Run packet through ipfw processing, if enabled */
634	if (priv->conf.ipfw[linkNum] && fw_enable && ip_fw_chk_ptr != NULL) {
635		/* XXX not implemented yet */
636	}
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", __FUNCTION__, 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	meta = NGI_META(item); /* peek.. */
671	firstLink = NULL;
672	for (linkNum = 0; linkNum <= priv->numLinks; linkNum++) {
673		struct ng_bridge_link *destLink;
674		meta_p meta2 = NULL;
675		struct mbuf *m2 = NULL;
676
677		/*
678		 * If we have checked all the links then now
679		 * send the original on its reserved link
680		 */
681		if (linkNum == priv->numLinks) {
682			/* If we never saw a good link, leave. */
683			if (firstLink == NULL) {
684				NG_FREE_ITEM(item);
685				NG_FREE_M(m);
686				return (0);
687			}
688			destLink = firstLink;
689		} else {
690			destLink = priv->links[linkNum];
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 and meta info for sending.
708			 */
709			m2 = m_dup(m, M_NOWAIT);	/* 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			if (meta != NULL
717			    && (meta2 = ng_copy_meta(meta)) == NULL) {
718				link->stats.memoryFailures++;
719				m_freem(m2);
720				NG_FREE_ITEM(item);
721				NG_FREE_M(m);
722				return (ENOMEM);
723			}
724		}
725
726		/* Update stats */
727		destLink->stats.xmitPackets++;
728		destLink->stats.xmitOctets += m->m_pkthdr.len;
729		switch (manycast) {
730		case 0:					/* unicast */
731			break;
732		case 1:					/* multicast */
733			destLink->stats.xmitMulticasts++;
734			break;
735		case 2:					/* broadcast */
736			destLink->stats.xmitBroadcasts++;
737			break;
738		}
739
740		/* Send packet */
741		if (destLink == firstLink) {
742			/*
743			 * If we've sent all the others, send the original
744			 * on the first link we found.
745			 */
746			NG_FWD_NEW_DATA(error, item, destLink->hook, m);
747			break; /* always done last - not really needed. */
748		} else {
749			NG_SEND_DATA(error, destLink->hook, m2, meta2);
750		}
751	}
752	return (error);
753}
754
755/*
756 * Shutdown node
757 */
758static int
759ng_bridge_shutdown(node_p node)
760{
761	const priv_p priv = node->private;
762
763	KASSERT(priv->numLinks == 0 && priv->numHosts == 0,
764	    ("%s: numLinks=%d numHosts=%d",
765	    __FUNCTION__, priv->numLinks, priv->numHosts));
766	FREE(priv->tab, M_NETGRAPH);
767	FREE(priv, M_NETGRAPH);
768	node->private = NULL;
769	ng_unref(node);
770	return (0);
771}
772
773/*
774 * Hook disconnection.
775 */
776static int
777ng_bridge_disconnect(hook_p hook)
778{
779	const priv_p priv = hook->node->private;
780	int linkNum;
781
782	/* Get link number */
783	linkNum = LINK_NUM(hook);
784	KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
785	    ("%s: linkNum=%u", __FUNCTION__, 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", __FUNCTION__));
792	FREE(priv->links[linkNum], M_NETGRAPH);
793	priv->links[linkNum] = NULL;
794	priv->numLinks--;
795
796	/* If no more hooks, go away */
797	if ((hook->node->numhooks == 0)
798	&& (( hook->node->flags & NG_INVALID) == 0))
799		ng_rmnode_self(hook->node);
800	return (0);
801}
802
803/******************************************************************
804		    HASH TABLE FUNCTIONS
805******************************************************************/
806
807/*
808 * Hash algorithm
809 *
810 * Only hashing bytes 3-6 of the Ethernet address is sufficient and fast.
811 */
812#define HASH(addr,mask)		( (((const u_int16_t *)(addr))[0] 	\
813				 ^ ((const u_int16_t *)(addr))[1] 	\
814				 ^ ((const u_int16_t *)(addr))[2]) & (mask) )
815
816/*
817 * Find a host entry in the table.
818 */
819static struct ng_bridge_host *
820ng_bridge_get(priv_p priv, const u_char *addr)
821{
822	const int bucket = HASH(addr, priv->hashMask);
823	struct ng_bridge_hent *hent;
824
825	SLIST_FOREACH(hent, &priv->tab[bucket], next) {
826		if (ETHER_EQUAL(hent->host.addr, addr))
827			return (&hent->host);
828	}
829	return (NULL);
830}
831
832/*
833 * Add a new host entry to the table. This assumes the host doesn't
834 * already exist in the table. Returns 1 on success, 0 if there
835 * was a memory allocation failure.
836 */
837static int
838ng_bridge_put(priv_p priv, const u_char *addr, int linkNum)
839{
840	const int bucket = HASH(addr, priv->hashMask);
841	struct ng_bridge_hent *hent;
842
843#ifdef INVARIANTS
844	/* Assert that entry does not already exist in hashtable */
845	SLIST_FOREACH(hent, &priv->tab[bucket], next) {
846		KASSERT(!ETHER_EQUAL(hent->host.addr, addr),
847		    ("%s: entry %6D exists in table", __FUNCTION__, addr, ":"));
848	}
849#endif
850
851	/* Allocate and initialize new hashtable entry */
852	MALLOC(hent, struct ng_bridge_hent *,
853	    sizeof(*hent), M_NETGRAPH, M_NOWAIT);
854	if (hent == NULL)
855		return (0);
856	bcopy(addr, hent->host.addr, ETHER_ADDR_LEN);
857	hent->host.linkNum = linkNum;
858	hent->host.staleness = 0;
859	hent->host.age = 0;
860
861	/* Add new element to hash bucket */
862	SLIST_INSERT_HEAD(&priv->tab[bucket], hent, next);
863	priv->numHosts++;
864
865	/* Resize table if necessary */
866	ng_bridge_rehash(priv);
867	return (1);
868}
869
870/*
871 * Resize the hash table. We try to maintain the number of buckets
872 * such that the load factor is in the range 0.25 to 1.0.
873 *
874 * If we can't get the new memory then we silently fail. This is OK
875 * because things will still work and we'll try again soon anyway.
876 */
877static void
878ng_bridge_rehash(priv_p priv)
879{
880	struct ng_bridge_bucket *newTab;
881	int oldBucket, newBucket;
882	int newNumBuckets;
883	u_int newMask;
884
885	/* Is table too full or too empty? */
886	if (priv->numHosts > priv->numBuckets
887	    && (priv->numBuckets << 1) <= MAX_BUCKETS)
888		newNumBuckets = priv->numBuckets << 1;
889	else if (priv->numHosts < (priv->numBuckets >> 2)
890	    && (priv->numBuckets >> 2) >= MIN_BUCKETS)
891		newNumBuckets = priv->numBuckets >> 2;
892	else
893		return;
894	newMask = newNumBuckets - 1;
895
896	/* Allocate and initialize new table */
897	MALLOC(newTab, struct ng_bridge_bucket *,
898	    newNumBuckets * sizeof(*newTab), M_NETGRAPH, M_NOWAIT | M_ZERO);
899	if (newTab == NULL)
900		return;
901
902	/* Move all entries from old table to new table */
903	for (oldBucket = 0; oldBucket < priv->numBuckets; oldBucket++) {
904		struct ng_bridge_bucket *const oldList = &priv->tab[oldBucket];
905
906		while (!SLIST_EMPTY(oldList)) {
907			struct ng_bridge_hent *const hent
908			    = SLIST_FIRST(oldList);
909
910			SLIST_REMOVE_HEAD(oldList, next);
911			newBucket = HASH(hent->host.addr, newMask);
912			SLIST_INSERT_HEAD(&newTab[newBucket], hent, next);
913		}
914	}
915
916	/* Replace old table with new one */
917	if (priv->conf.debugLevel >= 3) {
918		log(LOG_INFO, "ng_bridge: %s: table size %d -> %d\n",
919		    ng_bridge_nodename(priv->node),
920		    priv->numBuckets, newNumBuckets);
921	}
922	FREE(priv->tab, M_NETGRAPH);
923	priv->numBuckets = newNumBuckets;
924	priv->hashMask = newMask;
925	priv->tab = newTab;
926	return;
927}
928
929/******************************************************************
930		    MISC FUNCTIONS
931******************************************************************/
932
933/*
934 * Remove all hosts associated with a specific link from the hashtable.
935 * If linkNum == -1, then remove all hosts in the table.
936 */
937static void
938ng_bridge_remove_hosts(priv_p priv, int linkNum)
939{
940	int bucket;
941
942	for (bucket = 0; bucket < priv->numBuckets; bucket++) {
943		struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
944
945		while (*hptr != NULL) {
946			struct ng_bridge_hent *const hent = *hptr;
947
948			if (linkNum == -1 || hent->host.linkNum == linkNum) {
949				*hptr = SLIST_NEXT(hent, next);
950				FREE(hent, M_NETGRAPH);
951				priv->numHosts--;
952			} else
953				hptr = &SLIST_NEXT(hent, next);
954		}
955	}
956}
957
958/*
959 * Handle our once-per-second timeout event. We do two things:
960 * we decrement link->loopCount for those links being muted due to
961 * a detected loopback condition, and we remove any hosts from
962 * the hashtable whom we haven't heard from in a long while.
963 */
964static void
965ng_bridge_timeout(void *arg)
966{
967	const node_p node = arg;
968	const priv_p priv = node->private;
969	int s, bucket;
970	int counter = 0;
971	int linkNum;
972
973	/* Avoid race condition with ng_bridge_shutdown() */
974	s = splnet();
975	if ((node->flags & NG_INVALID) != 0 || priv == NULL) {
976		ng_unref(node);
977		splx(s);
978		return;
979	}
980
981	/* Register a new timeout, keeping the existing node reference */
982	callout_reset(&priv->timer, hz, ng_bridge_timeout, node);
983
984	/* Update host time counters and remove stale entries */
985	for (bucket = 0; bucket < priv->numBuckets; bucket++) {
986		struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
987
988		while (*hptr != NULL) {
989			struct ng_bridge_hent *const hent = *hptr;
990
991			/* Make sure host's link really exists */
992			KASSERT(priv->links[hent->host.linkNum] != NULL,
993			    ("%s: host %6D on nonexistent link %d\n",
994			    __FUNCTION__, hent->host.addr, ":",
995			    hent->host.linkNum));
996
997			/* Remove hosts we haven't heard from in a while */
998			if (++hent->host.staleness >= priv->conf.maxStaleness) {
999				*hptr = SLIST_NEXT(hent, next);
1000				FREE(hent, M_NETGRAPH);
1001				priv->numHosts--;
1002			} else {
1003				if (hent->host.age < 0xffff)
1004					hent->host.age++;
1005				hptr = &SLIST_NEXT(hent, next);
1006				counter++;
1007			}
1008		}
1009	}
1010	KASSERT(priv->numHosts == counter,
1011	    ("%s: hosts: %d != %d", __FUNCTION__, priv->numHosts, counter));
1012
1013	/* Decrease table size if necessary */
1014	ng_bridge_rehash(priv);
1015
1016	/* Decrease loop counter on muted looped back links */
1017	for (counter = linkNum = 0; linkNum < NG_BRIDGE_MAX_LINKS; linkNum++) {
1018		struct ng_bridge_link *const link = priv->links[linkNum];
1019
1020		if (link != NULL) {
1021			if (link->loopCount != 0) {
1022				link->loopCount--;
1023				if (link->loopCount == 0
1024				    && priv->conf.debugLevel >= 2) {
1025					log(LOG_INFO, "ng_bridge: %s:"
1026					    " restoring looped back link%d\n",
1027					    ng_bridge_nodename(node), linkNum);
1028				}
1029			}
1030			counter++;
1031		}
1032	}
1033	KASSERT(priv->numLinks == counter,
1034	    ("%s: links: %d != %d", __FUNCTION__, priv->numLinks, counter));
1035
1036	/* Done */
1037	splx(s);
1038}
1039
1040/*
1041 * Return node's "name", even if it doesn't have one.
1042 */
1043static const char *
1044ng_bridge_nodename(node_p node)
1045{
1046	static char name[NG_NODELEN+1];
1047
1048	if (node->name != NULL)
1049		snprintf(name, sizeof(name), "%s", node->name);
1050	else
1051		snprintf(name, sizeof(name), "[%x]", ng_node2ID(node));
1052	return name;
1053}
1054
1055