ng_bridge.c revision 66887
11638Srgrimes
21638Srgrimes/*
31638Srgrimes * ng_bridge.c
41638Srgrimes *
51638Srgrimes * Copyright (c) 2000 Whistle Communications, Inc.
61638Srgrimes * All rights reserved.
71638Srgrimes *
81638Srgrimes * Subject to the following obligations and disclaimer of warranty, use and
91638Srgrimes * redistribution of this software, in source or object code forms, with or
101638Srgrimes * without modifications are expressly permitted by Whistle Communications;
111638Srgrimes * provided, however, that:
121638Srgrimes * 1. Any and all reproductions of the source or object code must include the
131638Srgrimes *    copyright notice above and the following disclaimer of warranties; and
141638Srgrimes * 2. No rights are granted, in any manner or form, to use Whistle
151638Srgrimes *    Communications, Inc. trademarks, including the mark "WHISTLE
161638Srgrimes *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
171638Srgrimes *    such appears in the above copyright notice or in the software.
181638Srgrimes *
191638Srgrimes * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
201638Srgrimes * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
211638Srgrimes * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
221638Srgrimes * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
231638Srgrimes * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
241638Srgrimes * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
251638Srgrimes * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
261638Srgrimes * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
271638Srgrimes * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
281638Srgrimes * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
291638Srgrimes * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
301638Srgrimes * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
311638Srgrimes * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
321638Srgrimes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
331638Srgrimes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
341638Srgrimes * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
351638Srgrimes * OF SUCH DAMAGE.
361638Srgrimes *
371638Srgrimes * Author: Archie Cobbs <archie@freebsd.org>
381638Srgrimes *
391638Srgrimes * $FreeBSD: head/sys/netgraph/ng_bridge.c 66887 2000-10-09 18:37:11Z archie $
401638Srgrimes */
411638Srgrimes
421638Srgrimes/*
431638Srgrimes * ng_bridge(4) netgraph node type
441638Srgrimes *
451638Srgrimes * The node performs standard intelligent Ethernet bridging over
461638Srgrimes * each of its connected hooks, or links.  A simple loop detection
471638Srgrimes * algorithm is included which disables a link for priv->conf.loopTimeout
481638Srgrimes * seconds when a host is seen to have jumped from one link to
491638Srgrimes * another within priv->conf.minStableAge seconds.
501638Srgrimes *
511638Srgrimes * We keep a hashtable that maps Ethernet addresses to host info,
521638Srgrimes * which is contained in struct ng_bridge_host's. These structures
531638Srgrimes * tell us on which link the host may be found. A host's entry will
541638Srgrimes * expire after priv->conf.maxStaleness seconds.
551638Srgrimes *
561638Srgrimes * This node is optimzed for stable networks, where machines jump
571638Srgrimes * from one port to the other only rarely.
581638Srgrimes */
591638Srgrimes
601638Srgrimes#include <sys/param.h>
611638Srgrimes#include <sys/systm.h>
621638Srgrimes#include <sys/kernel.h>
631638Srgrimes#include <sys/malloc.h>
641638Srgrimes#include <sys/mbuf.h>
651638Srgrimes#include <sys/errno.h>
661638Srgrimes#include <sys/syslog.h>
671638Srgrimes#include <sys/socket.h>
681638Srgrimes#include <sys/ctype.h>
691638Srgrimes
701638Srgrimes#include <net/if.h>
711638Srgrimes#include <net/ethernet.h>
721638Srgrimes
731638Srgrimes#include <netinet/in.h>
741638Srgrimes#include <netinet/ip_fw.h>
751638Srgrimes
761638Srgrimes#include <netgraph/ng_message.h>
771638Srgrimes#include <netgraph/netgraph.h>
781638Srgrimes#include <netgraph/ng_parse.h>
791638Srgrimes#include <netgraph/ng_bridge.h>
801638Srgrimes#include <netgraph/ng_ether.h>
811638Srgrimes
821638Srgrimes/* Per-link private data */
831638Srgrimesstruct ng_bridge_link {
841638Srgrimes	hook_p				hook;		/* netgraph hook */
851638Srgrimes	u_int16_t			loopCount;	/* loop ignore timer */
861638Srgrimes	struct ng_bridge_link_stats	stats;		/* link stats */
871638Srgrimes};
881638Srgrimes
891638Srgrimes/* Per-node private data */
901638Srgrimesstruct ng_bridge_private {
911638Srgrimes	struct ng_bridge_bucket	*tab;		/* hash table bucket array */
921638Srgrimes	struct ng_bridge_link	*links[NG_BRIDGE_MAX_LINKS];
931638Srgrimes	struct ng_bridge_config	conf;		/* node configuration */
941638Srgrimes	node_p			node;		/* netgraph node */
951638Srgrimes	u_int			numHosts;	/* num entries in table */
961638Srgrimes	u_int			numBuckets;	/* num buckets in table */
971638Srgrimes	u_int			hashMask;	/* numBuckets - 1 */
981638Srgrimes	int			numLinks;	/* num connected links */
991638Srgrimes	struct callout		timer;		/* one second periodic timer */
1001638Srgrimes};
1011638Srgrimestypedef struct ng_bridge_private *priv_p;
1021638Srgrimes
1031638Srgrimes/* Information about a host, stored in a hash table entry */
1041638Srgrimesstruct ng_bridge_hent {
1051638Srgrimes	struct ng_bridge_host		host;	/* actual host info */
1061638Srgrimes	SLIST_ENTRY(ng_bridge_hent)	next;	/* next entry in bucket */
1071638Srgrimes};
1081638Srgrimes
1091638Srgrimes/* Hash table bucket declaration */
1101638SrgrimesSLIST_HEAD(ng_bridge_bucket, ng_bridge_hent);
1111638Srgrimes
1121638Srgrimes/* Netgraph node methods */
1131638Srgrimesstatic ng_constructor_t	ng_bridge_constructor;
1141638Srgrimesstatic ng_rcvmsg_t	ng_bridge_rcvmsg;
1151638Srgrimesstatic ng_shutdown_t	ng_bridge_rmnode;
1161638Srgrimesstatic 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_VERSION,
270	NG_BRIDGE_NODE_TYPE,
271	NULL,
272	ng_bridge_constructor,
273	ng_bridge_rcvmsg,
274	ng_bridge_rmnode,
275	ng_bridge_newhook,
276	NULL,
277	NULL,
278	ng_bridge_rcvdata,
279	ng_bridge_rcvdata,
280	ng_bridge_disconnect,
281	ng_bridge_cmdlist,
282};
283NETGRAPH_INIT(bridge, &ng_bridge_typestruct);
284
285/* Depend on ng_ether so we can use the Ethernet parse type */
286MODULE_DEPEND(ng_bridge, ng_ether, 1, 1, 1);
287
288/******************************************************************
289		    NETGRAPH NODE METHODS
290******************************************************************/
291
292/*
293 * Node constructor
294 */
295static int
296ng_bridge_constructor(node_p *nodep)
297{
298	priv_p priv;
299	int error;
300
301	/* Allocate and initialize private info */
302	MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH, M_NOWAIT);
303	if (priv == NULL)
304		return (ENOMEM);
305	bzero(priv, sizeof(*priv));
306	callout_init(&priv->timer);
307
308	/* Allocate and initialize hash table, etc. */
309	MALLOC(priv->tab, struct ng_bridge_bucket *,
310	    MIN_BUCKETS * sizeof(*priv->tab), M_NETGRAPH, M_NOWAIT);
311	if (priv->tab == NULL) {
312		FREE(priv, M_NETGRAPH);
313		return (ENOMEM);
314	}
315	bzero(priv->tab, MIN_BUCKETS * sizeof(*priv->tab));  /* init SLIST's */
316	priv->numBuckets = MIN_BUCKETS;
317	priv->hashMask = MIN_BUCKETS - 1;
318	priv->conf.debugLevel = 1;
319	priv->conf.loopTimeout = DEFAULT_LOOP_TIMEOUT;
320	priv->conf.maxStaleness = DEFAULT_MAX_STALENESS;
321	priv->conf.minStableAge = DEFAULT_MIN_STABLE_AGE;
322
323	/* Call superclass constructor */
324	if ((error = ng_make_node_common(&ng_bridge_typestruct, nodep))) {
325		FREE(priv, M_NETGRAPH);
326		return (error);
327	}
328	(*nodep)->private = priv;
329	priv->node = *nodep;
330
331	/* Start timer by faking a timeout event */
332	(*nodep)->refs++;
333	ng_bridge_timeout(*nodep);
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);
362		if (priv->links[linkNum] == NULL)
363			return (ENOMEM);
364		bzero(priv->links[linkNum], sizeof(*priv->links[linkNum]));
365		priv->links[linkNum]->hook = hook;
366		LINK_NUM(hook) = linkNum;
367		priv->numLinks++;
368		return (0);
369	}
370
371	/* Unknown hook name */
372	return (EINVAL);
373}
374
375/*
376 * Receive a control message
377 */
378static int
379ng_bridge_rcvmsg(node_p node, struct ng_mesg *msg, const char *retaddr,
380		struct ng_mesg **rptr, hook_p lasthook)
381{
382	const priv_p priv = node->private;
383	struct ng_mesg *resp = NULL;
384	int error = 0;
385
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	if (rptr)
505		*rptr = resp;
506	else if (resp != NULL)
507		FREE(resp, M_NETGRAPH);
508	FREE(msg, M_NETGRAPH);
509	return (error);
510}
511
512/*
513 * Receive data on a hook
514 */
515static int
516ng_bridge_rcvdata(hook_p hook, struct mbuf *m, meta_p meta,
517		struct mbuf **ret_m, meta_p *ret_meta)
518{
519	const node_p node = hook->node;
520	const priv_p priv = node->private;
521	struct ng_bridge_host *host;
522	struct ng_bridge_link *link;
523	struct ether_header *eh;
524	int error = 0, linkNum;
525	int i, manycast;
526
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_DATA(m, meta);
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_META(meta);
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_DATA(m, meta);
549		return (EINVAL);
550	}
551
552	/* Is link disabled due to a loopback condition? */
553	if (link->loopCount != 0) {
554		link->stats.loopDrops++;
555		NG_FREE_DATA(m, meta);
556		return (ELOOP);		/* XXX is this an appropriate error? */
557	}
558
559	/* Update stats */
560	link->stats.recvPackets++;
561	link->stats.recvOctets += m->m_pkthdr.len;
562	if ((manycast = (eh->ether_dhost[0] & 1)) != 0) {
563		if (ETHER_EQUAL(eh->ether_dhost, ng_bridge_bcast_addr)) {
564			link->stats.recvBroadcasts++;
565			manycast = 2;
566		} else
567			link->stats.recvMulticasts++;
568	}
569
570	/* Look up packet's source Ethernet address in hashtable */
571	if ((host = ng_bridge_get(priv, eh->ether_shost)) != NULL) {
572
573		/* Update time since last heard from this host */
574		host->staleness = 0;
575
576		/* Did host jump to a different link? */
577		if (host->linkNum != linkNum) {
578
579			/*
580			 * If the host's old link was recently established
581			 * on the old link and it's already jumped to a new
582			 * link, declare a loopback condition.
583			 */
584			if (host->age < priv->conf.minStableAge) {
585
586				/* Log the problem */
587				if (priv->conf.debugLevel >= 2) {
588					struct ifnet *ifp = m->m_pkthdr.rcvif;
589					char suffix[32];
590
591					if (ifp != NULL)
592						snprintf(suffix, sizeof(suffix),
593						    " (%s%d)", ifp->if_name,
594						    ifp->if_unit);
595					else
596						*suffix = '\0';
597					log(LOG_WARNING, "ng_bridge: %s:"
598					    " loopback detected on %s%s\n",
599					    ng_bridge_nodename(node),
600					    hook->name, suffix);
601				}
602
603				/* Mark link as linka non grata */
604				link->loopCount = priv->conf.loopTimeout;
605				link->stats.loopDetects++;
606
607				/* Forget all hosts on this link */
608				ng_bridge_remove_hosts(priv, linkNum);
609
610				/* Drop packet */
611				link->stats.loopDrops++;
612				NG_FREE_DATA(m, meta);
613				return (ELOOP);		/* XXX appropriate? */
614			}
615
616			/* Move host over to new link */
617			host->linkNum = linkNum;
618			host->age = 0;
619		}
620	} else {
621		if (!ng_bridge_put(priv, eh->ether_shost, linkNum)) {
622			link->stats.memoryFailures++;
623			NG_FREE_DATA(m, meta);
624			return (ENOMEM);
625		}
626	}
627
628	/* Run packet through ipfw processing, if enabled */
629	if (priv->conf.ipfw[linkNum] && fw_enable && ip_fw_chk_ptr != NULL) {
630		/* XXX not implemented yet */
631	}
632
633	/*
634	 * If unicast and destination host known, deliver to host's link,
635	 * unless it is the same link as the packet came in on.
636	 */
637	if (!manycast) {
638
639		/* Determine packet destination link */
640		if ((host = ng_bridge_get(priv, eh->ether_dhost)) != NULL) {
641			struct ng_bridge_link *const destLink
642			    = priv->links[host->linkNum];
643
644			/* If destination same as incoming link, do nothing */
645			KASSERT(destLink != NULL,
646			    ("%s: link%d null", __FUNCTION__, host->linkNum));
647			if (destLink == link) {
648				NG_FREE_DATA(m, meta);
649				return (0);
650			}
651
652			/* Deliver packet out the destination link */
653			destLink->stats.xmitPackets++;
654			destLink->stats.xmitOctets += m->m_pkthdr.len;
655			NG_SEND_DATA(error, destLink->hook, m, meta);
656			return (error);
657		}
658
659		/* Destination host is not known */
660		link->stats.recvUnknown++;
661	}
662
663	/* Distribute unknown, multicast, broadcast pkts to all other links */
664	for (linkNum = i = 0; i < priv->numLinks - 1; linkNum++) {
665		struct ng_bridge_link *const destLink = priv->links[linkNum];
666		meta_p meta2 = NULL;
667		struct mbuf *m2;
668
669		/* Skip incoming link and disconnected links */
670		if (destLink == NULL || destLink == link)
671			continue;
672
673		/* Copy mbuf and meta info */
674		if (++i == priv->numLinks - 1) {		/* last link */
675			m2 = m;
676			meta2 = meta;
677		}  else {
678			m2 = m_dup(m, M_NOWAIT);	/* XXX m_copypacket() */
679			if (m2 == NULL) {
680				link->stats.memoryFailures++;
681				NG_FREE_DATA(m, meta);
682				return (ENOBUFS);
683			}
684			if (meta != NULL
685			    && (meta2 = ng_copy_meta(meta)) == NULL) {
686				link->stats.memoryFailures++;
687				m_freem(m2);
688				NG_FREE_DATA(m, meta);
689				return (ENOMEM);
690			}
691		}
692
693		/* Update stats */
694		destLink->stats.xmitPackets++;
695		destLink->stats.xmitOctets += m->m_pkthdr.len;
696		switch (manycast) {
697		case 0:					/* unicast */
698			break;
699		case 1:					/* multicast */
700			destLink->stats.xmitMulticasts++;
701			break;
702		case 2:					/* broadcast */
703			destLink->stats.xmitBroadcasts++;
704			break;
705		}
706
707		/* Send packet */
708		NG_SEND_DATA(error, destLink->hook, m2, meta2);
709	}
710	return (error);
711}
712
713/*
714 * Shutdown node
715 */
716static int
717ng_bridge_rmnode(node_p node)
718{
719	const priv_p priv = node->private;
720
721	ng_unname(node);
722	ng_cutlinks(node);		/* frees all link and host info */
723	KASSERT(priv->numLinks == 0 && priv->numHosts == 0,
724	    ("%s: numLinks=%d numHosts=%d",
725	    __FUNCTION__, priv->numLinks, priv->numHosts));
726	FREE(priv->tab, M_NETGRAPH);
727	FREE(priv, M_NETGRAPH);
728	node->private = NULL;
729	ng_unref(node);
730	return (0);
731}
732
733/*
734 * Hook disconnection.
735 */
736static int
737ng_bridge_disconnect(hook_p hook)
738{
739	const priv_p priv = hook->node->private;
740	int linkNum;
741
742	/* Get link number */
743	linkNum = LINK_NUM(hook);
744	KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
745	    ("%s: linkNum=%u", __FUNCTION__, linkNum));
746
747	/* Remove all hosts associated with this link */
748	ng_bridge_remove_hosts(priv, linkNum);
749
750	/* Free associated link information */
751	KASSERT(priv->links[linkNum] != NULL, ("%s: no link", __FUNCTION__));
752	FREE(priv->links[linkNum], M_NETGRAPH);
753	priv->links[linkNum] = NULL;
754	priv->numLinks--;
755
756	/* If no more hooks, go away */
757	if (hook->node->numhooks == 0)
758		ng_rmnode(hook->node);
759	return (0);
760}
761
762/******************************************************************
763		    HASH TABLE FUNCTIONS
764******************************************************************/
765
766/*
767 * Hash algorithm
768 *
769 * Only hashing bytes 3-6 of the Ethernet address is sufficient and fast.
770 */
771#define HASH(addr,mask)		( (((const u_int16_t *)(addr))[0] 	\
772				 ^ ((const u_int16_t *)(addr))[1] 	\
773				 ^ ((const u_int16_t *)(addr))[2]) & (mask) )
774
775/*
776 * Find a host entry in the table.
777 */
778static struct ng_bridge_host *
779ng_bridge_get(priv_p priv, const u_char *addr)
780{
781	const int bucket = HASH(addr, priv->hashMask);
782	struct ng_bridge_hent *hent;
783
784	SLIST_FOREACH(hent, &priv->tab[bucket], next) {
785		if (ETHER_EQUAL(hent->host.addr, addr))
786			return (&hent->host);
787	}
788	return (NULL);
789}
790
791/*
792 * Add a new host entry to the table. This assumes the host doesn't
793 * already exist in the table. Returns 1 on success, 0 if there
794 * was a memory allocation failure.
795 */
796static int
797ng_bridge_put(priv_p priv, const u_char *addr, int linkNum)
798{
799	const int bucket = HASH(addr, priv->hashMask);
800	struct ng_bridge_hent *hent;
801
802#ifdef INVARIANTS
803	/* Assert that entry does not already exist in hashtable */
804	SLIST_FOREACH(hent, &priv->tab[bucket], next) {
805		KASSERT(!ETHER_EQUAL(hent->host.addr, addr),
806		    ("%s: entry %6D exists in table", __FUNCTION__, addr, ":"));
807	}
808#endif
809
810	/* Allocate and initialize new hashtable entry */
811	MALLOC(hent, struct ng_bridge_hent *,
812	    sizeof(*hent), M_NETGRAPH, M_NOWAIT);
813	if (hent == NULL)
814		return (0);
815	bcopy(addr, hent->host.addr, ETHER_ADDR_LEN);
816	hent->host.linkNum = linkNum;
817	hent->host.staleness = 0;
818	hent->host.age = 0;
819
820	/* Add new element to hash bucket */
821	SLIST_INSERT_HEAD(&priv->tab[bucket], hent, next);
822	priv->numHosts++;
823
824	/* Resize table if necessary */
825	ng_bridge_rehash(priv);
826	return (1);
827}
828
829/*
830 * Resize the hash table. We try to maintain the number of buckets
831 * such that the load factor is in the range 0.25 to 1.0.
832 *
833 * If we can't get the new memory then we silently fail. This is OK
834 * because things will still work and we'll try again soon anyway.
835 */
836static void
837ng_bridge_rehash(priv_p priv)
838{
839	struct ng_bridge_bucket *newTab;
840	int oldBucket, newBucket;
841	int newNumBuckets;
842	u_int newMask;
843
844	/* Is table too full or too empty? */
845	if (priv->numHosts > priv->numBuckets
846	    && (priv->numBuckets << 1) <= MAX_BUCKETS)
847		newNumBuckets = priv->numBuckets << 1;
848	else if (priv->numHosts < (priv->numBuckets >> 2)
849	    && (priv->numBuckets >> 2) >= MIN_BUCKETS)
850		newNumBuckets = priv->numBuckets >> 2;
851	else
852		return;
853	newMask = newNumBuckets - 1;
854
855	/* Allocate and initialize new table */
856	MALLOC(newTab, struct ng_bridge_bucket *,
857	    newNumBuckets * sizeof(*newTab), M_NETGRAPH, M_NOWAIT);
858	if (newTab == NULL)
859		return;
860	bzero(newTab, newNumBuckets * sizeof(*newTab));
861
862	/* Move all entries from old table to new table */
863	for (oldBucket = 0; oldBucket < priv->numBuckets; oldBucket++) {
864		struct ng_bridge_bucket *const oldList = &priv->tab[oldBucket];
865
866		while (!SLIST_EMPTY(oldList)) {
867			struct ng_bridge_hent *const hent
868			    = SLIST_FIRST(oldList);
869
870			SLIST_REMOVE_HEAD(oldList, next);
871			newBucket = HASH(hent->host.addr, newMask);
872			SLIST_INSERT_HEAD(&newTab[newBucket], hent, next);
873		}
874	}
875
876	/* Replace old table with new one */
877	if (priv->conf.debugLevel >= 3) {
878		log(LOG_INFO, "ng_bridge: %s: table size %d -> %d\n",
879		    ng_bridge_nodename(priv->node),
880		    priv->numBuckets, newNumBuckets);
881	}
882	FREE(priv->tab, M_NETGRAPH);
883	priv->numBuckets = newNumBuckets;
884	priv->hashMask = newMask;
885	priv->tab = newTab;
886	return;
887}
888
889/******************************************************************
890		    MISC FUNCTIONS
891******************************************************************/
892
893/*
894 * Remove all hosts associated with a specific link from the hashtable.
895 * If linkNum == -1, then remove all hosts in the table.
896 */
897static void
898ng_bridge_remove_hosts(priv_p priv, int linkNum)
899{
900	int bucket;
901
902	for (bucket = 0; bucket < priv->numBuckets; bucket++) {
903		struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
904
905		while (*hptr != NULL) {
906			struct ng_bridge_hent *const hent = *hptr;
907
908			if (linkNum == -1 || hent->host.linkNum == linkNum) {
909				*hptr = SLIST_NEXT(hent, next);
910				FREE(hent, M_NETGRAPH);
911				priv->numHosts--;
912			} else
913				hptr = &SLIST_NEXT(hent, next);
914		}
915	}
916}
917
918/*
919 * Handle our once-per-second timeout event. We do two things:
920 * we decrement link->loopCount for those links being muted due to
921 * a detected loopback condition, and we remove any hosts from
922 * the hashtable whom we haven't heard from in a long while.
923 */
924static void
925ng_bridge_timeout(void *arg)
926{
927	const node_p node = arg;
928	const priv_p priv = node->private;
929	int s, bucket;
930	int counter = 0;
931	int linkNum;
932
933	/* Avoid race condition with ng_bridge_shutdown() */
934	s = splnet();
935	if ((node->flags & NG_INVALID) != 0 || priv == NULL) {
936		ng_unref(node);
937		splx(s);
938		return;
939	}
940
941	/* Register a new timeout, keeping the existing node reference */
942	callout_reset(&priv->timer, hz, ng_bridge_timeout, node);
943
944	/* Update host time counters and remove stale entries */
945	for (bucket = 0; bucket < priv->numBuckets; bucket++) {
946		struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
947
948		while (*hptr != NULL) {
949			struct ng_bridge_hent *const hent = *hptr;
950
951			/* Make sure host's link really exists */
952			KASSERT(priv->links[hent->host.linkNum] != NULL,
953			    ("%s: host %6D on nonexistent link %d\n",
954			    __FUNCTION__, hent->host.addr, ":",
955			    hent->host.linkNum));
956
957			/* Remove hosts we haven't heard from in a while */
958			if (++hent->host.staleness >= priv->conf.maxStaleness) {
959				*hptr = SLIST_NEXT(hent, next);
960				FREE(hent, M_NETGRAPH);
961				priv->numHosts--;
962			} else {
963				if (hent->host.age < 0xffff)
964					hent->host.age++;
965				hptr = &SLIST_NEXT(hent, next);
966				counter++;
967			}
968		}
969	}
970	KASSERT(priv->numHosts == counter,
971	    ("%s: hosts: %d != %d", __FUNCTION__, priv->numHosts, counter));
972
973	/* Decrease table size if necessary */
974	ng_bridge_rehash(priv);
975
976	/* Decrease loop counter on muted looped back links */
977	for (counter = linkNum = 0; linkNum < NG_BRIDGE_MAX_LINKS; linkNum++) {
978		struct ng_bridge_link *const link = priv->links[linkNum];
979
980		if (link != NULL) {
981			if (link->loopCount != 0) {
982				link->loopCount--;
983				if (link->loopCount == 0
984				    && priv->conf.debugLevel >= 2) {
985					log(LOG_INFO, "ng_bridge: %s:"
986					    " restoring looped back link%d\n",
987					    ng_bridge_nodename(node), linkNum);
988				}
989			}
990			counter++;
991		}
992	}
993	KASSERT(priv->numLinks == counter,
994	    ("%s: links: %d != %d", __FUNCTION__, priv->numLinks, counter));
995
996	/* Done */
997	splx(s);
998}
999
1000/*
1001 * Return node's "name", even if it doesn't have one.
1002 */
1003static const char *
1004ng_bridge_nodename(node_p node)
1005{
1006	static char name[NG_NODELEN+1];
1007
1008	if (node->name != NULL)
1009		snprintf(name, sizeof(name), "%s", node->name);
1010	else
1011		snprintf(name, sizeof(name), "[%x]", ng_node2ID(node));
1012	return name;
1013}
1014
1015