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