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