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