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