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