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