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