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: releng/5.4/sys/netgraph/ng_bridge.c 142482 2005-02-25 17:17:27Z glebius $
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/malloc.h>
65 #include <sys/mbuf.h>
66 #include <sys/errno.h>
67 #include <sys/syslog.h>
68 #include <sys/socket.h>
69 #include <sys/ctype.h>
70
71 #include <net/if.h>
72 #include <net/ethernet.h>
73
74 #include <netinet/in.h>
75 #include <netinet/ip_fw.h>
76
77 #include <netgraph/ng_message.h>
78 #include <netgraph/netgraph.h>
79 #include <netgraph/ng_parse.h>
80 #include <netgraph/ng_bridge.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(node_p node, hook_p hook, void *arg1, int arg2);
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_field ng_bridge_host_type_fields[]
175 = NG_BRIDGE_HOST_TYPE_INFO(&ng_parse_enaddr_type);
176 static const struct ng_parse_type ng_bridge_host_type = {
177 &ng_parse_struct_type,
178 &ng_bridge_host_type_fields
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_field ng_bridge_host_ary_type_fields[]
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_fields
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_field ng_bridge_config_type_fields[]
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_fields
209 };
210
211 /* Parse type for struct ng_bridge_link_stat */
212 static const struct ng_parse_struct_field ng_bridge_stats_type_fields[]
213 = 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_fields
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 .version = NG_ABI_VERSION,
276 .name = NG_BRIDGE_NODE_TYPE,
277 .constructor = ng_bridge_constructor,
278 .rcvmsg = ng_bridge_rcvmsg,
279 .shutdown = ng_bridge_shutdown,
280 .newhook = ng_bridge_newhook,
281 .rcvdata = ng_bridge_rcvdata,
282 .disconnect = ng_bridge_disconnect,
283 .cmdlist = ng_bridge_cmdlist,
284 };
285 NETGRAPH_INIT(bridge, &ng_bridge_typestruct);
286
287 /******************************************************************
288 NETGRAPH NODE METHODS
289 ******************************************************************/
290
291 /*
292 * Node constructor
293 */
294 static int
295 ng_bridge_constructor(node_p node)
296 {
297 priv_p priv;
298
299 /* Allocate and initialize private info */
300 MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH_BRIDGE, M_NOWAIT | M_ZERO);
301 if (priv == NULL)
302 return (ENOMEM);
303 ng_callout_init(&priv->timer);
304
305 /* Allocate and initialize hash table, etc. */
306 MALLOC(priv->tab, struct ng_bridge_bucket *,
307 MIN_BUCKETS * sizeof(*priv->tab), M_NETGRAPH_BRIDGE, M_NOWAIT | M_ZERO);
308 if (priv->tab == NULL) {
309 FREE(priv, M_NETGRAPH_BRIDGE);
310 return (ENOMEM);
311 }
312 priv->numBuckets = MIN_BUCKETS;
313 priv->hashMask = MIN_BUCKETS - 1;
314 priv->conf.debugLevel = 1;
315 priv->conf.loopTimeout = DEFAULT_LOOP_TIMEOUT;
316 priv->conf.maxStaleness = DEFAULT_MAX_STALENESS;
317 priv->conf.minStableAge = DEFAULT_MIN_STABLE_AGE;
318
319 /*
320 * This node has all kinds of stuff that could be screwed by SMP.
321 * Until it gets it's own internal protection, we go through in
322 * single file. This could hurt a machine bridging beteen two
323 * GB ethernets so it should be fixed.
324 * When it's fixed the process SHOULD NOT SLEEP, spinlocks please!
325 * (and atomic ops )
326 */
327 NG_NODE_FORCE_WRITER(node);
328 NG_NODE_SET_PRIVATE(node, priv);
329 priv->node = node;
330
331 /* Start timer; timer is always running while node is alive */
332 ng_callout(&priv->timer, node, NULL, hz, ng_bridge_timeout, NULL, 0);
333
334 /* Done */
335 return (0);
336 }
337
338 /*
339 * Method for attaching a new hook
340 */
341 static int
342 ng_bridge_newhook(node_p node, hook_p hook, const char *name)
343 {
344 const priv_p priv = NG_NODE_PRIVATE(node);
345
346 /* Check for a link hook */
347 if (strncmp(name, NG_BRIDGE_HOOK_LINK_PREFIX,
348 strlen(NG_BRIDGE_HOOK_LINK_PREFIX)) == 0) {
349 const char *cp;
350 char *eptr;
351 u_long linkNum;
352
353 cp = name + strlen(NG_BRIDGE_HOOK_LINK_PREFIX);
354 if (!isdigit(*cp) || (cp[0] == '' && cp[1] != '\0'))
355 return (EINVAL);
356 linkNum = strtoul(cp, &eptr, 10);
357 if (*eptr != '\0' || linkNum >= NG_BRIDGE_MAX_LINKS)
358 return (EINVAL);
359 if (priv->links[linkNum] != NULL)
360 return (EISCONN);
361 MALLOC(priv->links[linkNum], struct ng_bridge_link *,
362 sizeof(*priv->links[linkNum]), M_NETGRAPH_BRIDGE, M_NOWAIT|M_ZERO);
363 if (priv->links[linkNum] == NULL)
364 return (ENOMEM);
365 priv->links[linkNum]->hook = hook;
366 NG_HOOK_SET_PRIVATE(hook, (void *)linkNum);
367 priv->numLinks++;
368 return (0);
369 }
370
371 /* Unknown hook name */
372 return (EINVAL);
373 }
374
375 /*
376 * Receive a control message
377 */
378 static int
379 ng_bridge_rcvmsg(node_p node, item_p item, hook_p lasthook)
380 {
381 const priv_p priv = NG_NODE_PRIVATE(node);
382 struct ng_mesg *resp = NULL;
383 int error = 0;
384 struct ng_mesg *msg;
385
386 NGI_GET_MSG(item, msg);
387 switch (msg->header.typecookie) {
388 case NGM_BRIDGE_COOKIE:
389 switch (msg->header.cmd) {
390 case NGM_BRIDGE_GET_CONFIG:
391 {
392 struct ng_bridge_config *conf;
393
394 NG_MKRESPONSE(resp, msg,
395 sizeof(struct ng_bridge_config), M_NOWAIT);
396 if (resp == NULL) {
397 error = ENOMEM;
398 break;
399 }
400 conf = (struct ng_bridge_config *)resp->data;
401 *conf = priv->conf; /* no sanity checking needed */
402 break;
403 }
404 case NGM_BRIDGE_SET_CONFIG:
405 {
406 struct ng_bridge_config *conf;
407 int i;
408
409 if (msg->header.arglen
410 != sizeof(struct ng_bridge_config)) {
411 error = EINVAL;
412 break;
413 }
414 conf = (struct ng_bridge_config *)msg->data;
415 priv->conf = *conf;
416 for (i = 0; i < NG_BRIDGE_MAX_LINKS; i++)
417 priv->conf.ipfw[i] = !!priv->conf.ipfw[i];
418 break;
419 }
420 case NGM_BRIDGE_RESET:
421 {
422 int i;
423
424 /* Flush all entries in the hash table */
425 ng_bridge_remove_hosts(priv, -1);
426
427 /* Reset all loop detection counters and stats */
428 for (i = 0; i < NG_BRIDGE_MAX_LINKS; i++) {
429 if (priv->links[i] == NULL)
430 continue;
431 priv->links[i]->loopCount = 0;
432 bzero(&priv->links[i]->stats,
433 sizeof(priv->links[i]->stats));
434 }
435 break;
436 }
437 case NGM_BRIDGE_GET_STATS:
438 case NGM_BRIDGE_CLR_STATS:
439 case NGM_BRIDGE_GETCLR_STATS:
440 {
441 struct ng_bridge_link *link;
442 int linkNum;
443
444 /* Get link number */
445 if (msg->header.arglen != sizeof(u_int32_t)) {
446 error = EINVAL;
447 break;
448 }
449 linkNum = *((u_int32_t *)msg->data);
450 if (linkNum < 0 || linkNum >= NG_BRIDGE_MAX_LINKS) {
451 error = EINVAL;
452 break;
453 }
454 if ((link = priv->links[linkNum]) == NULL) {
455 error = ENOTCONN;
456 break;
457 }
458
459 /* Get/clear stats */
460 if (msg->header.cmd != NGM_BRIDGE_CLR_STATS) {
461 NG_MKRESPONSE(resp, msg,
462 sizeof(link->stats), M_NOWAIT);
463 if (resp == NULL) {
464 error = ENOMEM;
465 break;
466 }
467 bcopy(&link->stats,
468 resp->data, sizeof(link->stats));
469 }
470 if (msg->header.cmd != NGM_BRIDGE_GET_STATS)
471 bzero(&link->stats, sizeof(link->stats));
472 break;
473 }
474 case NGM_BRIDGE_GET_TABLE:
475 {
476 struct ng_bridge_host_ary *ary;
477 struct ng_bridge_hent *hent;
478 int i = 0, bucket;
479
480 NG_MKRESPONSE(resp, msg, sizeof(*ary)
481 + (priv->numHosts * sizeof(*ary->hosts)), M_NOWAIT);
482 if (resp == NULL) {
483 error = ENOMEM;
484 break;
485 }
486 ary = (struct ng_bridge_host_ary *)resp->data;
487 ary->numHosts = priv->numHosts;
488 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
489 SLIST_FOREACH(hent, &priv->tab[bucket], next)
490 ary->hosts[i++] = hent->host;
491 }
492 break;
493 }
494 default:
495 error = EINVAL;
496 break;
497 }
498 break;
499 default:
500 error = EINVAL;
501 break;
502 }
503
504 /* Done */
505 NG_RESPOND_MSG(error, node, item, resp);
506 NG_FREE_MSG(msg);
507 return (error);
508 }
509
510 /*
511 * Receive data on a hook
512 */
513 static int
514 ng_bridge_rcvdata(hook_p hook, item_p item)
515 {
516 const node_p node = NG_HOOK_NODE(hook);
517 const priv_p priv = NG_NODE_PRIVATE(node);
518 struct ng_bridge_host *host;
519 struct ng_bridge_link *link;
520 struct ether_header *eh;
521 int error = 0, linkNum, linksSeen;
522 int manycast;
523 struct mbuf *m;
524 struct ng_bridge_link *firstLink;
525
526 NGI_GET_M(item, m);
527 /* Get link number */
528 linkNum = (intptr_t)NG_HOOK_PRIVATE(hook);
529 KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
530 ("%s: linkNum=%u", __func__, linkNum));
531 link = priv->links[linkNum];
532 KASSERT(link != NULL, ("%s: link%d null", __func__, linkNum));
533
534 /* Sanity check packet and pull up header */
535 if (m->m_pkthdr.len < ETHER_HDR_LEN) {
536 link->stats.recvRunts++;
537 NG_FREE_ITEM(item);
538 NG_FREE_M(m);
539 return (EINVAL);
540 }
541 if (m->m_len < ETHER_HDR_LEN && !(m = m_pullup(m, ETHER_HDR_LEN))) {
542 link->stats.memoryFailures++;
543 NG_FREE_ITEM(item);
544 return (ENOBUFS);
545 }
546 eh = mtod(m, struct ether_header *);
547 if ((eh->ether_shost[0] & 1) != 0) {
548 link->stats.recvInvalid++;
549 NG_FREE_ITEM(item);
550 NG_FREE_M(m);
551 return (EINVAL);
552 }
553
554 /* Is link disabled due to a loopback condition? */
555 if (link->loopCount != 0) {
556 link->stats.loopDrops++;
557 NG_FREE_ITEM(item);
558 NG_FREE_M(m);
559 return (ELOOP); /* XXX is this an appropriate error? */
560 }
561
562 /* Update stats */
563 link->stats.recvPackets++;
564 link->stats.recvOctets += m->m_pkthdr.len;
565 if ((manycast = (eh->ether_dhost[0] & 1)) != 0) {
566 if (ETHER_EQUAL(eh->ether_dhost, ng_bridge_bcast_addr)) {
567 link->stats.recvBroadcasts++;
568 manycast = 2;
569 } else
570 link->stats.recvMulticasts++;
571 }
572
573 /* Look up packet's source Ethernet address in hashtable */
574 if ((host = ng_bridge_get(priv, eh->ether_shost)) != NULL) {
575
576 /* Update time since last heard from this host */
577 host->staleness = 0;
578
579 /* Did host jump to a different link? */
580 if (host->linkNum != linkNum) {
581
582 /*
583 * If the host's old link was recently established
584 * on the old link and it's already jumped to a new
585 * link, declare a loopback condition.
586 */
587 if (host->age < priv->conf.minStableAge) {
588
589 /* Log the problem */
590 if (priv->conf.debugLevel >= 2) {
591 struct ifnet *ifp = m->m_pkthdr.rcvif;
592 char suffix[32];
593
594 if (ifp != NULL)
595 snprintf(suffix, sizeof(suffix),
596 " (%s)", ifp->if_xname);
597 else
598 *suffix = '\0';
599 log(LOG_WARNING, "ng_bridge: %s:"
600 " loopback detected on %s%s\n",
601 ng_bridge_nodename(node),
602 NG_HOOK_NAME(hook), suffix);
603 }
604
605 /* Mark link as linka non grata */
606 link->loopCount = priv->conf.loopTimeout;
607 link->stats.loopDetects++;
608
609 /* Forget all hosts on this link */
610 ng_bridge_remove_hosts(priv, linkNum);
611
612 /* Drop packet */
613 link->stats.loopDrops++;
614 NG_FREE_ITEM(item);
615 NG_FREE_M(m);
616 return (ELOOP); /* XXX appropriate? */
617 }
618
619 /* Move host over to new link */
620 host->linkNum = linkNum;
621 host->age = 0;
622 }
623 } else {
624 if (!ng_bridge_put(priv, eh->ether_shost, linkNum)) {
625 link->stats.memoryFailures++;
626 NG_FREE_ITEM(item);
627 NG_FREE_M(m);
628 return (ENOMEM);
629 }
630 }
631
632 /* Run packet through ipfw processing, if enabled */
633 #if 0
634 if (priv->conf.ipfw[linkNum] && fw_enable && ip_fw_chk_ptr != NULL) {
635 /* XXX not implemented yet */
636 }
637 #endif
638
639 /*
640 * If unicast and destination host known, deliver to host's link,
641 * unless it is the same link as the packet came in on.
642 */
643 if (!manycast) {
644
645 /* Determine packet destination link */
646 if ((host = ng_bridge_get(priv, eh->ether_dhost)) != NULL) {
647 struct ng_bridge_link *const destLink
648 = priv->links[host->linkNum];
649
650 /* If destination same as incoming link, do nothing */
651 KASSERT(destLink != NULL,
652 ("%s: link%d null", __func__, host->linkNum));
653 if (destLink == link) {
654 NG_FREE_ITEM(item);
655 NG_FREE_M(m);
656 return (0);
657 }
658
659 /* Deliver packet out the destination link */
660 destLink->stats.xmitPackets++;
661 destLink->stats.xmitOctets += m->m_pkthdr.len;
662 NG_FWD_NEW_DATA(error, item, destLink->hook, m);
663 return (error);
664 }
665
666 /* Destination host is not known */
667 link->stats.recvUnknown++;
668 }
669
670 /* Distribute unknown, multicast, broadcast pkts to all other links */
671 firstLink = NULL;
672 for (linkNum = linksSeen = 0; linksSeen <= priv->numLinks; linkNum++) {
673 struct ng_bridge_link *destLink;
674 struct mbuf *m2 = NULL;
675
676 /*
677 * If we have checked all the links then now
678 * send the original on its reserved link
679 */
680 if (linksSeen == priv->numLinks) {
681 /* If we never saw a good link, leave. */
682 if (firstLink == NULL) {
683 NG_FREE_ITEM(item);
684 NG_FREE_M(m);
685 return (0);
686 }
687 destLink = firstLink;
688 } else {
689 destLink = priv->links[linkNum];
690 if (destLink != NULL)
691 linksSeen++;
692 /* Skip incoming link and disconnected links */
693 if (destLink == NULL || destLink == link) {
694 continue;
695 }
696 if (firstLink == NULL) {
697 /*
698 * This is the first usable link we have found.
699 * Reserve it for the originals.
700 * If we never find another we save a copy.
701 */
702 firstLink = destLink;
703 continue;
704 }
705
706 /*
707 * It's usable link but not the reserved (first) one.
708 * Copy mbuf info for sending.
709 */
710 m2 = m_dup(m, M_DONTWAIT); /* XXX m_copypacket() */
711 if (m2 == NULL) {
712 link->stats.memoryFailures++;
713 NG_FREE_ITEM(item);
714 NG_FREE_M(m);
715 return (ENOBUFS);
716 }
717 }
718
719 /* Update stats */
720 destLink->stats.xmitPackets++;
721 destLink->stats.xmitOctets += m->m_pkthdr.len;
722 switch (manycast) {
723 case 0: /* unicast */
724 break;
725 case 1: /* multicast */
726 destLink->stats.xmitMulticasts++;
727 break;
728 case 2: /* broadcast */
729 destLink->stats.xmitBroadcasts++;
730 break;
731 }
732
733 /* Send packet */
734 if (destLink == firstLink) {
735 /*
736 * If we've sent all the others, send the original
737 * on the first link we found.
738 */
739 NG_FWD_NEW_DATA(error, item, destLink->hook, m);
740 break; /* always done last - not really needed. */
741 } else {
742 NG_SEND_DATA_ONLY(error, destLink->hook, m2);
743 }
744 }
745 return (error);
746 }
747
748 /*
749 * Shutdown node
750 */
751 static int
752 ng_bridge_shutdown(node_p node)
753 {
754 const priv_p priv = NG_NODE_PRIVATE(node);
755
756 /*
757 * Shut down everything including the timer. Even if the
758 * callout has already been dequeued and is about to be
759 * run, ng_bridge_timeout() won't be fired as the node
760 * is already marked NGF_INVALID, so we're safe to free
761 * the node now.
762 */
763 KASSERT(priv->numLinks == 0 && priv->numHosts == 0,
764 ("%s: numLinks=%d numHosts=%d",
765 __func__, priv->numLinks, priv->numHosts));
766 ng_uncallout(&priv->timer, node);
767 NG_NODE_SET_PRIVATE(node, NULL);
768 NG_NODE_UNREF(node);
769 FREE(priv->tab, M_NETGRAPH_BRIDGE);
770 FREE(priv, M_NETGRAPH_BRIDGE);
771 return (0);
772 }
773
774 /*
775 * Hook disconnection.
776 */
777 static int
778 ng_bridge_disconnect(hook_p hook)
779 {
780 const priv_p priv = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
781 int linkNum;
782
783 /* Get link number */
784 linkNum = (intptr_t)NG_HOOK_PRIVATE(hook);
785 KASSERT(linkNum >= 0 && linkNum < NG_BRIDGE_MAX_LINKS,
786 ("%s: linkNum=%u", __func__, linkNum));
787
788 /* Remove all hosts associated with this link */
789 ng_bridge_remove_hosts(priv, linkNum);
790
791 /* Free associated link information */
792 KASSERT(priv->links[linkNum] != NULL, ("%s: no link", __func__));
793 FREE(priv->links[linkNum], M_NETGRAPH_BRIDGE);
794 priv->links[linkNum] = NULL;
795 priv->numLinks--;
796
797 /* If no more hooks, go away */
798 if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
799 && (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))) {
800 ng_rmnode_self(NG_HOOK_NODE(hook));
801 }
802 return (0);
803 }
804
805 /******************************************************************
806 HASH TABLE FUNCTIONS
807 ******************************************************************/
808
809 /*
810 * Hash algorithm
811 */
812 #define HASH(addr,mask) ( (((const u_int16_t *)(addr))[0] \
813 ^ ((const u_int16_t *)(addr))[1] \
814 ^ ((const u_int16_t *)(addr))[2]) & (mask) )
815
816 /*
817 * Find a host entry in the table.
818 */
819 static struct ng_bridge_host *
820 ng_bridge_get(priv_p priv, const u_char *addr)
821 {
822 const int bucket = HASH(addr, priv->hashMask);
823 struct ng_bridge_hent *hent;
824
825 SLIST_FOREACH(hent, &priv->tab[bucket], next) {
826 if (ETHER_EQUAL(hent->host.addr, addr))
827 return (&hent->host);
828 }
829 return (NULL);
830 }
831
832 /*
833 * Add a new host entry to the table. This assumes the host doesn't
834 * already exist in the table. Returns 1 on success, 0 if there
835 * was a memory allocation failure.
836 */
837 static int
838 ng_bridge_put(priv_p priv, const u_char *addr, int linkNum)
839 {
840 const int bucket = HASH(addr, priv->hashMask);
841 struct ng_bridge_hent *hent;
842
843 #ifdef INVARIANTS
844 /* Assert that entry does not already exist in hashtable */
845 SLIST_FOREACH(hent, &priv->tab[bucket], next) {
846 KASSERT(!ETHER_EQUAL(hent->host.addr, addr),
847 ("%s: entry %6D exists in table", __func__, addr, ":"));
848 }
849 #endif
850
851 /* Allocate and initialize new hashtable entry */
852 MALLOC(hent, struct ng_bridge_hent *,
853 sizeof(*hent), M_NETGRAPH_BRIDGE, M_NOWAIT);
854 if (hent == NULL)
855 return (0);
856 bcopy(addr, hent->host.addr, ETHER_ADDR_LEN);
857 hent->host.linkNum = linkNum;
858 hent->host.staleness = 0;
859 hent->host.age = 0;
860
861 /* Add new element to hash bucket */
862 SLIST_INSERT_HEAD(&priv->tab[bucket], hent, next);
863 priv->numHosts++;
864
865 /* Resize table if necessary */
866 ng_bridge_rehash(priv);
867 return (1);
868 }
869
870 /*
871 * Resize the hash table. We try to maintain the number of buckets
872 * such that the load factor is in the range 0.25 to 1.0.
873 *
874 * If we can't get the new memory then we silently fail. This is OK
875 * because things will still work and we'll try again soon anyway.
876 */
877 static void
878 ng_bridge_rehash(priv_p priv)
879 {
880 struct ng_bridge_bucket *newTab;
881 int oldBucket, newBucket;
882 int newNumBuckets;
883 u_int newMask;
884
885 /* Is table too full or too empty? */
886 if (priv->numHosts > priv->numBuckets
887 && (priv->numBuckets << 1) <= MAX_BUCKETS)
888 newNumBuckets = priv->numBuckets << 1;
889 else if (priv->numHosts < (priv->numBuckets >> 2)
890 && (priv->numBuckets >> 2) >= MIN_BUCKETS)
891 newNumBuckets = priv->numBuckets >> 2;
892 else
893 return;
894 newMask = newNumBuckets - 1;
895
896 /* Allocate and initialize new table */
897 MALLOC(newTab, struct ng_bridge_bucket *,
898 newNumBuckets * sizeof(*newTab), M_NETGRAPH_BRIDGE, M_NOWAIT | M_ZERO);
899 if (newTab == NULL)
900 return;
901
902 /* Move all entries from old table to new table */
903 for (oldBucket = 0; oldBucket < priv->numBuckets; oldBucket++) {
904 struct ng_bridge_bucket *const oldList = &priv->tab[oldBucket];
905
906 while (!SLIST_EMPTY(oldList)) {
907 struct ng_bridge_hent *const hent
908 = SLIST_FIRST(oldList);
909
910 SLIST_REMOVE_HEAD(oldList, next);
911 newBucket = HASH(hent->host.addr, newMask);
912 SLIST_INSERT_HEAD(&newTab[newBucket], hent, next);
913 }
914 }
915
916 /* Replace old table with new one */
917 if (priv->conf.debugLevel >= 3) {
918 log(LOG_INFO, "ng_bridge: %s: table size %d -> %d\n",
919 ng_bridge_nodename(priv->node),
920 priv->numBuckets, newNumBuckets);
921 }
922 FREE(priv->tab, M_NETGRAPH_BRIDGE);
923 priv->numBuckets = newNumBuckets;
924 priv->hashMask = newMask;
925 priv->tab = newTab;
926 return;
927 }
928
929 /******************************************************************
930 MISC FUNCTIONS
931 ******************************************************************/
932
933 /*
934 * Remove all hosts associated with a specific link from the hashtable.
935 * If linkNum == -1, then remove all hosts in the table.
936 */
937 static void
938 ng_bridge_remove_hosts(priv_p priv, int linkNum)
939 {
940 int bucket;
941
942 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
943 struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
944
945 while (*hptr != NULL) {
946 struct ng_bridge_hent *const hent = *hptr;
947
948 if (linkNum == -1 || hent->host.linkNum == linkNum) {
949 *hptr = SLIST_NEXT(hent, next);
950 FREE(hent, M_NETGRAPH_BRIDGE);
951 priv->numHosts--;
952 } else
953 hptr = &SLIST_NEXT(hent, next);
954 }
955 }
956 }
957
958 /*
959 * Handle our once-per-second timeout event. We do two things:
960 * we decrement link->loopCount for those links being muted due to
961 * a detected loopback condition, and we remove any hosts from
962 * the hashtable whom we haven't heard from in a long while.
963 */
964 static void
965 ng_bridge_timeout(node_p node, hook_p hook, void *arg1, int arg2)
966 {
967 const priv_p priv = NG_NODE_PRIVATE(node);
968 int bucket;
969 int counter = 0;
970 int linkNum;
971
972 /* Update host time counters and remove stale entries */
973 for (bucket = 0; bucket < priv->numBuckets; bucket++) {
974 struct ng_bridge_hent **hptr = &SLIST_FIRST(&priv->tab[bucket]);
975
976 while (*hptr != NULL) {
977 struct ng_bridge_hent *const hent = *hptr;
978
979 /* Make sure host's link really exists */
980 KASSERT(priv->links[hent->host.linkNum] != NULL,
981 ("%s: host %6D on nonexistent link %d\n",
982 __func__, hent->host.addr, ":",
983 hent->host.linkNum));
984
985 /* Remove hosts we haven't heard from in a while */
986 if (++hent->host.staleness >= priv->conf.maxStaleness) {
987 *hptr = SLIST_NEXT(hent, next);
988 FREE(hent, M_NETGRAPH_BRIDGE);
989 priv->numHosts--;
990 } else {
991 if (hent->host.age < 0xffff)
992 hent->host.age++;
993 hptr = &SLIST_NEXT(hent, next);
994 counter++;
995 }
996 }
997 }
998 KASSERT(priv->numHosts == counter,
999 ("%s: hosts: %d != %d", __func__, priv->numHosts, counter));
1000
1001 /* Decrease table size if necessary */
1002 ng_bridge_rehash(priv);
1003
1004 /* Decrease loop counter on muted looped back links */
1005 for (counter = linkNum = 0; linkNum < NG_BRIDGE_MAX_LINKS; linkNum++) {
1006 struct ng_bridge_link *const link = priv->links[linkNum];
1007
1008 if (link != NULL) {
1009 if (link->loopCount != 0) {
1010 link->loopCount--;
1011 if (link->loopCount == 0
1012 && priv->conf.debugLevel >= 2) {
1013 log(LOG_INFO, "ng_bridge: %s:"
1014 " restoring looped back link%d\n",
1015 ng_bridge_nodename(node), linkNum);
1016 }
1017 }
1018 counter++;
1019 }
1020 }
1021 KASSERT(priv->numLinks == counter,
1022 ("%s: links: %d != %d", __func__, priv->numLinks, counter));
1023
1024 /* Register a new timeout, keeping the existing node reference */
1025 ng_callout(&priv->timer, node, NULL, hz, ng_bridge_timeout, NULL, 0);
1026 }
1027
1028 /*
1029 * Return node's "name", even if it doesn't have one.
1030 */
1031 static const char *
1032 ng_bridge_nodename(node_p node)
1033 {
1034 static char name[NG_NODESIZ];
1035
1036 if (NG_NODE_NAME(node) != NULL)
1037 snprintf(name, sizeof(name), "%s", NG_NODE_NAME(node));
1038 else
1039 snprintf(name, sizeof(name), "[%x]", ng_node2ID(node));
1040 return name;
1041 }
1042
Cache object: fff63ebb97dcd0a2e2ceb56523946c9b
|