]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/netgraph/ng_base.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sys / netgraph / ng_base.c
1 /*
2  * ng_base.c
3  */
4
5 /*-
6  * Copyright (c) 1996-1999 Whistle Communications, Inc.
7  * All rights reserved.
8  *
9  * Subject to the following obligations and disclaimer of warranty, use and
10  * redistribution of this software, in source or object code forms, with or
11  * without modifications are expressly permitted by Whistle Communications;
12  * provided, however, that:
13  * 1. Any and all reproductions of the source or object code must include the
14  *    copyright notice above and the following disclaimer of warranties; and
15  * 2. No rights are granted, in any manner or form, to use Whistle
16  *    Communications, Inc. trademarks, including the mark "WHISTLE
17  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18  *    such appears in the above copyright notice or in the software.
19  *
20  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
36  * OF SUCH DAMAGE.
37  *
38  * Authors: Julian Elischer <julian@freebsd.org>
39  *          Archie Cobbs <archie@freebsd.org>
40  *
41  * $FreeBSD$
42  * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
43  */
44
45 /*
46  * This file implements the base netgraph code.
47  */
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/ctype.h>
52 #include <sys/errno.h>
53 #include <sys/kdb.h>
54 #include <sys/kernel.h>
55 #include <sys/ktr.h>
56 #include <sys/limits.h>
57 #include <sys/malloc.h>
58 #include <sys/mbuf.h>
59 #include <sys/queue.h>
60 #include <sys/sysctl.h>
61 #include <sys/syslog.h>
62 #include <sys/refcount.h>
63 #include <sys/proc.h>
64 #include <sys/unistd.h>
65 #include <sys/kthread.h>
66 #include <sys/smp.h>
67 #include <machine/cpu.h>
68
69 #include <netgraph/ng_message.h>
70 #include <netgraph/netgraph.h>
71 #include <netgraph/ng_parse.h>
72
73 MODULE_VERSION(netgraph, NG_ABI_VERSION);
74
75 /* Mutex to protect topology events. */
76 static struct mtx       ng_topo_mtx;
77
78 #ifdef  NETGRAPH_DEBUG
79 static struct mtx       ng_nodelist_mtx; /* protects global node/hook lists */
80 static struct mtx       ngq_mtx;        /* protects the queue item list */
81
82 static SLIST_HEAD(, ng_node) ng_allnodes;
83 static LIST_HEAD(, ng_node) ng_freenodes; /* in debug, we never free() them */
84 static SLIST_HEAD(, ng_hook) ng_allhooks;
85 static LIST_HEAD(, ng_hook) ng_freehooks; /* in debug, we never free() them */
86
87 static void ng_dumpitems(void);
88 static void ng_dumpnodes(void);
89 static void ng_dumphooks(void);
90
91 #endif  /* NETGRAPH_DEBUG */
92 /*
93  * DEAD versions of the structures.
94  * In order to avoid races, it is sometimes neccesary to point
95  * at SOMETHING even though theoretically, the current entity is
96  * INVALID. Use these to avoid these races.
97  */
98 struct ng_type ng_deadtype = {
99         NG_ABI_VERSION,
100         "dead",
101         NULL,   /* modevent */
102         NULL,   /* constructor */
103         NULL,   /* rcvmsg */
104         NULL,   /* shutdown */
105         NULL,   /* newhook */
106         NULL,   /* findhook */
107         NULL,   /* connect */
108         NULL,   /* rcvdata */
109         NULL,   /* disconnect */
110         NULL,   /* cmdlist */
111 };
112
113 struct ng_node ng_deadnode = {
114         "dead",
115         &ng_deadtype,   
116         NGF_INVALID,
117         1,      /* refs */
118         0,      /* numhooks */
119         NULL,   /* private */
120         0,      /* ID */
121         LIST_HEAD_INITIALIZER(ng_deadnode.hooks),
122         {},     /* all_nodes list entry */
123         {},     /* id hashtable list entry */
124         {},     /* workqueue entry */
125         {       0,
126                 {}, /* should never use! (should hang) */
127                 NULL,
128                 &ng_deadnode.nd_input_queue.queue,
129                 &ng_deadnode
130         },
131 #ifdef  NETGRAPH_DEBUG
132         ND_MAGIC,
133         __FILE__,
134         __LINE__,
135         {NULL}
136 #endif  /* NETGRAPH_DEBUG */
137 };
138
139 struct ng_hook ng_deadhook = {
140         "dead",
141         NULL,           /* private */
142         HK_INVALID | HK_DEAD,
143         1,              /* refs always >= 1 */
144         0,              /* undefined data link type */
145         &ng_deadhook,   /* Peer is self */
146         &ng_deadnode,   /* attached to deadnode */
147         {},             /* hooks list */
148         NULL,           /* override rcvmsg() */
149         NULL,           /* override rcvdata() */
150 #ifdef  NETGRAPH_DEBUG
151         HK_MAGIC,
152         __FILE__,
153         __LINE__,
154         {NULL}
155 #endif  /* NETGRAPH_DEBUG */
156 };
157
158 /*
159  * END DEAD STRUCTURES
160  */
161 /* List nodes with unallocated work */
162 static TAILQ_HEAD(, ng_node) ng_worklist = TAILQ_HEAD_INITIALIZER(ng_worklist);
163 static struct mtx       ng_worklist_mtx;   /* MUST LOCK NODE FIRST */
164
165 /* List of installed types */
166 static LIST_HEAD(, ng_type) ng_typelist;
167 static struct mtx       ng_typelist_mtx;
168
169 /* Hash related definitions */
170 /* XXX Don't need to initialise them because it's a LIST */
171 #define NG_ID_HASH_SIZE 128 /* most systems wont need even this many */
172 static LIST_HEAD(, ng_node) ng_ID_hash[NG_ID_HASH_SIZE];
173 static struct mtx       ng_idhash_mtx;
174 /* Method to find a node.. used twice so do it here */
175 #define NG_IDHASH_FN(ID) ((ID) % (NG_ID_HASH_SIZE))
176 #define NG_IDHASH_FIND(ID, node)                                        \
177         do {                                                            \
178                 mtx_assert(&ng_idhash_mtx, MA_OWNED);                   \
179                 LIST_FOREACH(node, &ng_ID_hash[NG_IDHASH_FN(ID)],       \
180                                                 nd_idnodes) {           \
181                         if (NG_NODE_IS_VALID(node)                      \
182                         && (NG_NODE_ID(node) == ID)) {                  \
183                                 break;                                  \
184                         }                                               \
185                 }                                                       \
186         } while (0)
187
188 #define NG_NAME_HASH_SIZE 128 /* most systems wont need even this many */
189 static LIST_HEAD(, ng_node) ng_name_hash[NG_NAME_HASH_SIZE];
190 static struct mtx       ng_namehash_mtx;
191 #define NG_NAMEHASH(NAME, HASH)                         \
192         do {                                            \
193                 u_char  h = 0;                          \
194                 const u_char    *c;                     \
195                 for (c = (const u_char*)(NAME); *c; c++)\
196                         h += *c;                        \
197                 (HASH) = h % (NG_NAME_HASH_SIZE);       \
198         } while (0)
199
200
201 /* Internal functions */
202 static int      ng_add_hook(node_p node, const char *name, hook_p * hookp);
203 static int      ng_generic_msg(node_p here, item_p item, hook_p lasthook);
204 static ng_ID_t  ng_decodeidname(const char *name);
205 static int      ngb_mod_event(module_t mod, int event, void *data);
206 static void     ng_worklist_add(node_p node);
207 static void     ngthread(void *);
208 static int      ng_apply_item(node_p node, item_p item, int rw);
209 static void     ng_flush_input_queue(struct ng_queue * ngq);
210 static node_p   ng_ID2noderef(ng_ID_t ID);
211 static int      ng_con_nodes(item_p item, node_p node, const char *name,
212                     node_p node2, const char *name2);
213 static int      ng_con_part2(node_p node, item_p item, hook_p hook);
214 static int      ng_con_part3(node_p node, item_p item, hook_p hook);
215 static int      ng_mkpeer(node_p node, const char *name,
216                                                 const char *name2, char *type);
217
218 /* Imported, these used to be externally visible, some may go back. */
219 void    ng_destroy_hook(hook_p hook);
220 node_p  ng_name2noderef(node_p node, const char *name);
221 int     ng_path2noderef(node_p here, const char *path,
222         node_p *dest, hook_p *lasthook);
223 int     ng_make_node(const char *type, node_p *nodepp);
224 int     ng_path_parse(char *addr, char **node, char **path, char **hook);
225 void    ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3);
226 void    ng_unname(node_p node);
227
228
229 /* Our own netgraph malloc type */
230 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
231 MALLOC_DEFINE(M_NETGRAPH_HOOK, "netgraph_hook", "netgraph hook structures");
232 MALLOC_DEFINE(M_NETGRAPH_NODE, "netgraph_node", "netgraph node structures");
233 MALLOC_DEFINE(M_NETGRAPH_ITEM, "netgraph_item", "netgraph item structures");
234 MALLOC_DEFINE(M_NETGRAPH_MSG, "netgraph_msg", "netgraph name storage");
235
236 /* Should not be visible outside this file */
237
238 #define _NG_ALLOC_HOOK(hook) \
239         MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH_HOOK, M_NOWAIT | M_ZERO)
240 #define _NG_ALLOC_NODE(node) \
241         MALLOC(node, node_p, sizeof(*node), M_NETGRAPH_NODE, M_NOWAIT | M_ZERO)
242
243 #define NG_QUEUE_LOCK_INIT(n)                   \
244         mtx_init(&(n)->q_mtx, "ng_node", NULL, MTX_DEF)
245 #define NG_QUEUE_LOCK(n)                        \
246         mtx_lock(&(n)->q_mtx)
247 #define NG_QUEUE_UNLOCK(n)                      \
248         mtx_unlock(&(n)->q_mtx)
249 #define NG_WORKLIST_LOCK_INIT()                 \
250         mtx_init(&ng_worklist_mtx, "ng_worklist", NULL, MTX_DEF)
251 #define NG_WORKLIST_LOCK()                      \
252         mtx_lock(&ng_worklist_mtx)
253 #define NG_WORKLIST_UNLOCK()                    \
254         mtx_unlock(&ng_worklist_mtx)
255 #define NG_WORKLIST_SLEEP()                     \
256         mtx_sleep(&ng_worklist, &ng_worklist_mtx, PI_NET, "sleep", 0)
257 #define NG_WORKLIST_WAKEUP()                    \
258         wakeup_one(&ng_worklist)
259
260 #ifdef NETGRAPH_DEBUG /*----------------------------------------------*/
261 /*
262  * In debug mode:
263  * In an attempt to help track reference count screwups
264  * we do not free objects back to the malloc system, but keep them
265  * in a local cache where we can examine them and keep information safely
266  * after they have been freed.
267  * We use this scheme for nodes and hooks, and to some extent for items.
268  */
269 static __inline hook_p
270 ng_alloc_hook(void)
271 {
272         hook_p hook;
273         SLIST_ENTRY(ng_hook) temp;
274         mtx_lock(&ng_nodelist_mtx);
275         hook = LIST_FIRST(&ng_freehooks);
276         if (hook) {
277                 LIST_REMOVE(hook, hk_hooks);
278                 bcopy(&hook->hk_all, &temp, sizeof(temp));
279                 bzero(hook, sizeof(struct ng_hook));
280                 bcopy(&temp, &hook->hk_all, sizeof(temp));
281                 mtx_unlock(&ng_nodelist_mtx);
282                 hook->hk_magic = HK_MAGIC;
283         } else {
284                 mtx_unlock(&ng_nodelist_mtx);
285                 _NG_ALLOC_HOOK(hook);
286                 if (hook) {
287                         hook->hk_magic = HK_MAGIC;
288                         mtx_lock(&ng_nodelist_mtx);
289                         SLIST_INSERT_HEAD(&ng_allhooks, hook, hk_all);
290                         mtx_unlock(&ng_nodelist_mtx);
291                 }
292         }
293         return (hook);
294 }
295
296 static __inline node_p
297 ng_alloc_node(void)
298 {
299         node_p node;
300         SLIST_ENTRY(ng_node) temp;
301         mtx_lock(&ng_nodelist_mtx);
302         node = LIST_FIRST(&ng_freenodes);
303         if (node) {
304                 LIST_REMOVE(node, nd_nodes);
305                 bcopy(&node->nd_all, &temp, sizeof(temp));
306                 bzero(node, sizeof(struct ng_node));
307                 bcopy(&temp, &node->nd_all, sizeof(temp));
308                 mtx_unlock(&ng_nodelist_mtx);
309                 node->nd_magic = ND_MAGIC;
310         } else {
311                 mtx_unlock(&ng_nodelist_mtx);
312                 _NG_ALLOC_NODE(node);
313                 if (node) {
314                         node->nd_magic = ND_MAGIC;
315                         mtx_lock(&ng_nodelist_mtx);
316                         SLIST_INSERT_HEAD(&ng_allnodes, node, nd_all);
317                         mtx_unlock(&ng_nodelist_mtx);
318                 }
319         }
320         return (node);
321 }
322
323 #define NG_ALLOC_HOOK(hook) do { (hook) = ng_alloc_hook(); } while (0)
324 #define NG_ALLOC_NODE(node) do { (node) = ng_alloc_node(); } while (0)
325
326
327 #define NG_FREE_HOOK(hook)                                              \
328         do {                                                            \
329                 mtx_lock(&ng_nodelist_mtx);                     \
330                 LIST_INSERT_HEAD(&ng_freehooks, hook, hk_hooks);        \
331                 hook->hk_magic = 0;                                     \
332                 mtx_unlock(&ng_nodelist_mtx);                   \
333         } while (0)
334
335 #define NG_FREE_NODE(node)                                              \
336         do {                                                            \
337                 mtx_lock(&ng_nodelist_mtx);                     \
338                 LIST_INSERT_HEAD(&ng_freenodes, node, nd_nodes);        \
339                 node->nd_magic = 0;                                     \
340                 mtx_unlock(&ng_nodelist_mtx);                   \
341         } while (0)
342
343 #else /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
344
345 #define NG_ALLOC_HOOK(hook) _NG_ALLOC_HOOK(hook)
346 #define NG_ALLOC_NODE(node) _NG_ALLOC_NODE(node)
347
348 #define NG_FREE_HOOK(hook) do { FREE((hook), M_NETGRAPH_HOOK); } while (0)
349 #define NG_FREE_NODE(node) do { FREE((node), M_NETGRAPH_NODE); } while (0)
350
351 #endif /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
352
353 /* Set this to kdb_enter("X") to catch all errors as they occur */
354 #ifndef TRAP_ERROR
355 #define TRAP_ERROR()
356 #endif
357
358 static  ng_ID_t nextID = 1;
359
360 #ifdef INVARIANTS
361 #define CHECK_DATA_MBUF(m)      do {                                    \
362                 struct mbuf *n;                                         \
363                 int total;                                              \
364                                                                         \
365                 M_ASSERTPKTHDR(m);                                      \
366                 for (total = 0, n = (m); n != NULL; n = n->m_next) {    \
367                         total += n->m_len;                              \
368                         if (n->m_nextpkt != NULL)                       \
369                                 panic("%s: m_nextpkt", __func__);       \
370                 }                                                       \
371                                                                         \
372                 if ((m)->m_pkthdr.len != total) {                       \
373                         panic("%s: %d != %d",                           \
374                             __func__, (m)->m_pkthdr.len, total);        \
375                 }                                                       \
376         } while (0)
377 #else
378 #define CHECK_DATA_MBUF(m)
379 #endif
380
381 #define ERROUT(x)       do { error = (x); goto done; } while (0)
382
383 /************************************************************************
384         Parse type definitions for generic messages
385 ************************************************************************/
386
387 /* Handy structure parse type defining macro */
388 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args)                          \
389 static const struct ng_parse_struct_field                               \
390         ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args;  \
391 static const struct ng_parse_type ng_generic_ ## lo ## _type = {        \
392         &ng_parse_struct_type,                                          \
393         &ng_ ## lo ## _type_fields                                      \
394 }
395
396 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
397 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
398 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
399 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
400 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
401 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
402 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
403
404 /* Get length of an array when the length is stored as a 32 bit
405    value immediately preceding the array -- as with struct namelist
406    and struct typelist. */
407 static int
408 ng_generic_list_getLength(const struct ng_parse_type *type,
409         const u_char *start, const u_char *buf)
410 {
411         return *((const u_int32_t *)(buf - 4));
412 }
413
414 /* Get length of the array of struct linkinfo inside a struct hooklist */
415 static int
416 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
417         const u_char *start, const u_char *buf)
418 {
419         const struct hooklist *hl = (const struct hooklist *)start;
420
421         return hl->nodeinfo.hooks;
422 }
423
424 /* Array type for a variable length array of struct namelist */
425 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
426         &ng_generic_nodeinfo_type,
427         &ng_generic_list_getLength
428 };
429 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
430         &ng_parse_array_type,
431         &ng_nodeinfoarray_type_info
432 };
433
434 /* Array type for a variable length array of struct typelist */
435 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
436         &ng_generic_typeinfo_type,
437         &ng_generic_list_getLength
438 };
439 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
440         &ng_parse_array_type,
441         &ng_typeinfoarray_type_info
442 };
443
444 /* Array type for array of struct linkinfo in struct hooklist */
445 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
446         &ng_generic_linkinfo_type,
447         &ng_generic_linkinfo_getLength
448 };
449 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
450         &ng_parse_array_type,
451         &ng_generic_linkinfo_array_type_info
452 };
453
454 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
455 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
456         (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
457 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
458         (&ng_generic_nodeinfoarray_type));
459
460 /* List of commands and how to convert arguments to/from ASCII */
461 static const struct ng_cmdlist ng_generic_cmds[] = {
462         {
463           NGM_GENERIC_COOKIE,
464           NGM_SHUTDOWN,
465           "shutdown",
466           NULL,
467           NULL
468         },
469         {
470           NGM_GENERIC_COOKIE,
471           NGM_MKPEER,
472           "mkpeer",
473           &ng_generic_mkpeer_type,
474           NULL
475         },
476         {
477           NGM_GENERIC_COOKIE,
478           NGM_CONNECT,
479           "connect",
480           &ng_generic_connect_type,
481           NULL
482         },
483         {
484           NGM_GENERIC_COOKIE,
485           NGM_NAME,
486           "name",
487           &ng_generic_name_type,
488           NULL
489         },
490         {
491           NGM_GENERIC_COOKIE,
492           NGM_RMHOOK,
493           "rmhook",
494           &ng_generic_rmhook_type,
495           NULL
496         },
497         {
498           NGM_GENERIC_COOKIE,
499           NGM_NODEINFO,
500           "nodeinfo",
501           NULL,
502           &ng_generic_nodeinfo_type
503         },
504         {
505           NGM_GENERIC_COOKIE,
506           NGM_LISTHOOKS,
507           "listhooks",
508           NULL,
509           &ng_generic_hooklist_type
510         },
511         {
512           NGM_GENERIC_COOKIE,
513           NGM_LISTNAMES,
514           "listnames",
515           NULL,
516           &ng_generic_listnodes_type    /* same as NGM_LISTNODES */
517         },
518         {
519           NGM_GENERIC_COOKIE,
520           NGM_LISTNODES,
521           "listnodes",
522           NULL,
523           &ng_generic_listnodes_type
524         },
525         {
526           NGM_GENERIC_COOKIE,
527           NGM_LISTTYPES,
528           "listtypes",
529           NULL,
530           &ng_generic_typeinfo_type
531         },
532         {
533           NGM_GENERIC_COOKIE,
534           NGM_TEXT_CONFIG,
535           "textconfig",
536           NULL,
537           &ng_parse_string_type
538         },
539         {
540           NGM_GENERIC_COOKIE,
541           NGM_TEXT_STATUS,
542           "textstatus",
543           NULL,
544           &ng_parse_string_type
545         },
546         {
547           NGM_GENERIC_COOKIE,
548           NGM_ASCII2BINARY,
549           "ascii2binary",
550           &ng_parse_ng_mesg_type,
551           &ng_parse_ng_mesg_type
552         },
553         {
554           NGM_GENERIC_COOKIE,
555           NGM_BINARY2ASCII,
556           "binary2ascii",
557           &ng_parse_ng_mesg_type,
558           &ng_parse_ng_mesg_type
559         },
560         { 0 }
561 };
562
563 /************************************************************************
564                         Node routines
565 ************************************************************************/
566
567 /*
568  * Instantiate a node of the requested type
569  */
570 int
571 ng_make_node(const char *typename, node_p *nodepp)
572 {
573         struct ng_type *type;
574         int     error;
575
576         /* Check that the type makes sense */
577         if (typename == NULL) {
578                 TRAP_ERROR();
579                 return (EINVAL);
580         }
581
582         /* Locate the node type. If we fail we return. Do not try to load
583          * module.
584          */
585         if ((type = ng_findtype(typename)) == NULL)
586                 return (ENXIO);
587
588         /*
589          * If we have a constructor, then make the node and
590          * call the constructor to do type specific initialisation.
591          */
592         if (type->constructor != NULL) {
593                 if ((error = ng_make_node_common(type, nodepp)) == 0) {
594                         if ((error = ((*type->constructor)(*nodepp)) != 0)) {
595                                 NG_NODE_UNREF(*nodepp);
596                         }
597                 }
598         } else {
599                 /*
600                  * Node has no constructor. We cannot ask for one
601                  * to be made. It must be brought into existence by
602                  * some external agency. The external agency should
603                  * call ng_make_node_common() directly to get the
604                  * netgraph part initialised.
605                  */
606                 TRAP_ERROR();
607                 error = EINVAL;
608         }
609         return (error);
610 }
611
612 /*
613  * Generic node creation. Called by node initialisation for externally
614  * instantiated nodes (e.g. hardware, sockets, etc ).
615  * The returned node has a reference count of 1.
616  */
617 int
618 ng_make_node_common(struct ng_type *type, node_p *nodepp)
619 {
620         node_p node;
621
622         /* Require the node type to have been already installed */
623         if (ng_findtype(type->name) == NULL) {
624                 TRAP_ERROR();
625                 return (EINVAL);
626         }
627
628         /* Make a node and try attach it to the type */
629         NG_ALLOC_NODE(node);
630         if (node == NULL) {
631                 TRAP_ERROR();
632                 return (ENOMEM);
633         }
634         node->nd_type = type;
635         NG_NODE_REF(node);                              /* note reference */
636         type->refs++;
637
638         NG_QUEUE_LOCK_INIT(&node->nd_input_queue);
639         node->nd_input_queue.queue = NULL;
640         node->nd_input_queue.last = &node->nd_input_queue.queue;
641         node->nd_input_queue.q_flags = 0;
642         node->nd_input_queue.q_node = node;
643
644         /* Initialize hook list for new node */
645         LIST_INIT(&node->nd_hooks);
646
647         /* Link us into the name hash. */
648         mtx_lock(&ng_namehash_mtx);
649         LIST_INSERT_HEAD(&ng_name_hash[0], node, nd_nodes);
650         mtx_unlock(&ng_namehash_mtx);
651
652         /* get an ID and put us in the hash chain */
653         mtx_lock(&ng_idhash_mtx);
654         for (;;) { /* wrap protection, even if silly */
655                 node_p node2 = NULL;
656                 node->nd_ID = nextID++; /* 137/second for 1 year before wrap */
657
658                 /* Is there a problem with the new number? */
659                 NG_IDHASH_FIND(node->nd_ID, node2); /* already taken? */
660                 if ((node->nd_ID != 0) && (node2 == NULL)) {
661                         break;
662                 }
663         }
664         LIST_INSERT_HEAD(&ng_ID_hash[NG_IDHASH_FN(node->nd_ID)],
665                                                         node, nd_idnodes);
666         mtx_unlock(&ng_idhash_mtx);
667
668         /* Done */
669         *nodepp = node;
670         return (0);
671 }
672
673 /*
674  * Forceably start the shutdown process on a node. Either call
675  * its shutdown method, or do the default shutdown if there is
676  * no type-specific method.
677  *
678  * We can only be called from a shutdown message, so we know we have
679  * a writer lock, and therefore exclusive access. It also means
680  * that we should not be on the work queue, but we check anyhow.
681  *
682  * Persistent node types must have a type-specific method which
683  * allocates a new node in which case, this one is irretrievably going away,
684  * or cleans up anything it needs, and just makes the node valid again,
685  * in which case we allow the node to survive.
686  *
687  * XXX We need to think of how to tell a persistent node that we
688  * REALLY need to go away because the hardware has gone or we
689  * are rebooting.... etc.
690  */
691 void
692 ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3)
693 {
694         hook_p hook;
695
696         /* Check if it's already shutting down */
697         if ((node->nd_flags & NGF_CLOSING) != 0)
698                 return;
699
700         if (node == &ng_deadnode) {
701                 printf ("shutdown called on deadnode\n");
702                 return;
703         }
704
705         /* Add an extra reference so it doesn't go away during this */
706         NG_NODE_REF(node);
707
708         /*
709          * Mark it invalid so any newcomers know not to try use it
710          * Also add our own mark so we can't recurse
711          * note that NGF_INVALID does not do this as it's also set during
712          * creation
713          */
714         node->nd_flags |= NGF_INVALID|NGF_CLOSING;
715
716         /* If node has its pre-shutdown method, then call it first*/
717         if (node->nd_type && node->nd_type->close)
718                 (*node->nd_type->close)(node);
719
720         /* Notify all remaining connected nodes to disconnect */
721         while ((hook = LIST_FIRST(&node->nd_hooks)) != NULL)
722                 ng_destroy_hook(hook);
723
724         /*
725          * Drain the input queue forceably.
726          * it has no hooks so what's it going to do, bleed on someone?
727          * Theoretically we came here from a queue entry that was added
728          * Just before the queue was closed, so it should be empty anyway.
729          * Also removes us from worklist if needed.
730          */
731         ng_flush_input_queue(&node->nd_input_queue);
732
733         /* Ask the type if it has anything to do in this case */
734         if (node->nd_type && node->nd_type->shutdown) {
735                 (*node->nd_type->shutdown)(node);
736                 if (NG_NODE_IS_VALID(node)) {
737                         /*
738                          * Well, blow me down if the node code hasn't declared
739                          * that it doesn't want to die.
740                          * Presumably it is a persistant node.
741                          * If we REALLY want it to go away,
742                          *  e.g. hardware going away,
743                          * Our caller should set NGF_REALLY_DIE in nd_flags.
744                          */
745                         node->nd_flags &= ~(NGF_INVALID|NGF_CLOSING);
746                         NG_NODE_UNREF(node); /* Assume they still have theirs */
747                         return;
748                 }
749         } else {                                /* do the default thing */
750                 NG_NODE_UNREF(node);
751         }
752
753         ng_unname(node); /* basically a NOP these days */
754
755         /*
756          * Remove extra reference, possibly the last
757          * Possible other holders of references may include
758          * timeout callouts, but theoretically the node's supposed to
759          * have cancelled them. Possibly hardware dependencies may
760          * force a driver to 'linger' with a reference.
761          */
762         NG_NODE_UNREF(node);
763 }
764
765 /*
766  * Remove a reference to the node, possibly the last.
767  * deadnode always acts as it it were the last.
768  */
769 int
770 ng_unref_node(node_p node)
771 {
772         int v;
773
774         if (node == &ng_deadnode) {
775                 return (0);
776         }
777
778         v = atomic_fetchadd_int(&node->nd_refs, -1);
779
780         if (v == 1) { /* we were the last */
781
782                 mtx_lock(&ng_namehash_mtx);
783                 node->nd_type->refs--; /* XXX maybe should get types lock? */
784                 LIST_REMOVE(node, nd_nodes);
785                 mtx_unlock(&ng_namehash_mtx);
786
787                 mtx_lock(&ng_idhash_mtx);
788                 LIST_REMOVE(node, nd_idnodes);
789                 mtx_unlock(&ng_idhash_mtx);
790
791                 mtx_destroy(&node->nd_input_queue.q_mtx);
792                 NG_FREE_NODE(node);
793         }
794         return (v - 1);
795 }
796
797 /************************************************************************
798                         Node ID handling
799 ************************************************************************/
800 static node_p
801 ng_ID2noderef(ng_ID_t ID)
802 {
803         node_p node;
804         mtx_lock(&ng_idhash_mtx);
805         NG_IDHASH_FIND(ID, node);
806         if(node)
807                 NG_NODE_REF(node);
808         mtx_unlock(&ng_idhash_mtx);
809         return(node);
810 }
811
812 ng_ID_t
813 ng_node2ID(node_p node)
814 {
815         return (node ? NG_NODE_ID(node) : 0);
816 }
817
818 /************************************************************************
819                         Node name handling
820 ************************************************************************/
821
822 /*
823  * Assign a node a name. Once assigned, the name cannot be changed.
824  */
825 int
826 ng_name_node(node_p node, const char *name)
827 {
828         int i, hash;
829         node_p node2;
830
831         /* Check the name is valid */
832         for (i = 0; i < NG_NODESIZ; i++) {
833                 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
834                         break;
835         }
836         if (i == 0 || name[i] != '\0') {
837                 TRAP_ERROR();
838                 return (EINVAL);
839         }
840         if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
841                 TRAP_ERROR();
842                 return (EINVAL);
843         }
844
845         /* Check the name isn't already being used */
846         if ((node2 = ng_name2noderef(node, name)) != NULL) {
847                 NG_NODE_UNREF(node2);
848                 TRAP_ERROR();
849                 return (EADDRINUSE);
850         }
851
852         /* copy it */
853         strlcpy(NG_NODE_NAME(node), name, NG_NODESIZ);
854
855         /* Update name hash. */
856         NG_NAMEHASH(name, hash);
857         mtx_lock(&ng_namehash_mtx);
858         LIST_REMOVE(node, nd_nodes);
859         LIST_INSERT_HEAD(&ng_name_hash[hash], node, nd_nodes);
860         mtx_unlock(&ng_namehash_mtx);
861
862         return (0);
863 }
864
865 /*
866  * Find a node by absolute name. The name should NOT end with ':'
867  * The name "." means "this node" and "[xxx]" means "the node
868  * with ID (ie, at address) xxx".
869  *
870  * Returns the node if found, else NULL.
871  * Eventually should add something faster than a sequential search.
872  * Note it acquires a reference on the node so you can be sure it's still
873  * there.
874  */
875 node_p
876 ng_name2noderef(node_p here, const char *name)
877 {
878         node_p node;
879         ng_ID_t temp;
880         int     hash;
881
882         /* "." means "this node" */
883         if (strcmp(name, ".") == 0) {
884                 NG_NODE_REF(here);
885                 return(here);
886         }
887
888         /* Check for name-by-ID */
889         if ((temp = ng_decodeidname(name)) != 0) {
890                 return (ng_ID2noderef(temp));
891         }
892
893         /* Find node by name */
894         NG_NAMEHASH(name, hash);
895         mtx_lock(&ng_namehash_mtx);
896         LIST_FOREACH(node, &ng_name_hash[hash], nd_nodes) {
897                 if (NG_NODE_IS_VALID(node) &&
898                     (strcmp(NG_NODE_NAME(node), name) == 0)) {
899                         break;
900                 }
901         }
902         if (node)
903                 NG_NODE_REF(node);
904         mtx_unlock(&ng_namehash_mtx);
905         return (node);
906 }
907
908 /*
909  * Decode an ID name, eg. "[f03034de]". Returns 0 if the
910  * string is not valid, otherwise returns the value.
911  */
912 static ng_ID_t
913 ng_decodeidname(const char *name)
914 {
915         const int len = strlen(name);
916         char *eptr;
917         u_long val;
918
919         /* Check for proper length, brackets, no leading junk */
920         if ((len < 3)
921         || (name[0] != '[')
922         || (name[len - 1] != ']')
923         || (!isxdigit(name[1]))) {
924                 return ((ng_ID_t)0);
925         }
926
927         /* Decode number */
928         val = strtoul(name + 1, &eptr, 16);
929         if ((eptr - name != len - 1)
930         || (val == ULONG_MAX)
931         || (val == 0)) {
932                 return ((ng_ID_t)0);
933         }
934         return (ng_ID_t)val;
935 }
936
937 /*
938  * Remove a name from a node. This should only be called
939  * when shutting down and removing the node.
940  * IF we allow name changing this may be more resurrected.
941  */
942 void
943 ng_unname(node_p node)
944 {
945 }
946
947 /************************************************************************
948                         Hook routines
949  Names are not optional. Hooks are always connected, except for a
950  brief moment within these routines. On invalidation or during creation
951  they are connected to the 'dead' hook.
952 ************************************************************************/
953
954 /*
955  * Remove a hook reference
956  */
957 void
958 ng_unref_hook(hook_p hook)
959 {
960         int v;
961
962         if (hook == &ng_deadhook) {
963                 return;
964         }
965
966         v = atomic_fetchadd_int(&hook->hk_refs, -1);
967
968         if (v == 1) { /* we were the last */
969                 if (_NG_HOOK_NODE(hook)) /* it'll probably be ng_deadnode */
970                         _NG_NODE_UNREF((_NG_HOOK_NODE(hook)));
971                 NG_FREE_HOOK(hook);
972         }
973 }
974
975 /*
976  * Add an unconnected hook to a node. Only used internally.
977  * Assumes node is locked. (XXX not yet true )
978  */
979 static int
980 ng_add_hook(node_p node, const char *name, hook_p *hookp)
981 {
982         hook_p hook;
983         int error = 0;
984
985         /* Check that the given name is good */
986         if (name == NULL) {
987                 TRAP_ERROR();
988                 return (EINVAL);
989         }
990         if (ng_findhook(node, name) != NULL) {
991                 TRAP_ERROR();
992                 return (EEXIST);
993         }
994
995         /* Allocate the hook and link it up */
996         NG_ALLOC_HOOK(hook);
997         if (hook == NULL) {
998                 TRAP_ERROR();
999                 return (ENOMEM);
1000         }
1001         hook->hk_refs = 1;              /* add a reference for us to return */
1002         hook->hk_flags = HK_INVALID;
1003         hook->hk_peer = &ng_deadhook;   /* start off this way */
1004         hook->hk_node = node;
1005         NG_NODE_REF(node);              /* each hook counts as a reference */
1006
1007         /* Set hook name */
1008         strlcpy(NG_HOOK_NAME(hook), name, NG_HOOKSIZ);
1009
1010         /*
1011          * Check if the node type code has something to say about it
1012          * If it fails, the unref of the hook will also unref the node.
1013          */
1014         if (node->nd_type->newhook != NULL) {
1015                 if ((error = (*node->nd_type->newhook)(node, hook, name))) {
1016                         NG_HOOK_UNREF(hook);    /* this frees the hook */
1017                         return (error);
1018                 }
1019         }
1020         /*
1021          * The 'type' agrees so far, so go ahead and link it in.
1022          * We'll ask again later when we actually connect the hooks.
1023          */
1024         LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
1025         node->nd_numhooks++;
1026         NG_HOOK_REF(hook);      /* one for the node */
1027
1028         if (hookp)
1029                 *hookp = hook;
1030         return (0);
1031 }
1032
1033 /*
1034  * Find a hook
1035  *
1036  * Node types may supply their own optimized routines for finding
1037  * hooks.  If none is supplied, we just do a linear search.
1038  * XXX Possibly we should add a reference to the hook?
1039  */
1040 hook_p
1041 ng_findhook(node_p node, const char *name)
1042 {
1043         hook_p hook;
1044
1045         if (node->nd_type->findhook != NULL)
1046                 return (*node->nd_type->findhook)(node, name);
1047         LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
1048                 if (NG_HOOK_IS_VALID(hook)
1049                 && (strcmp(NG_HOOK_NAME(hook), name) == 0))
1050                         return (hook);
1051         }
1052         return (NULL);
1053 }
1054
1055 /*
1056  * Destroy a hook
1057  *
1058  * As hooks are always attached, this really destroys two hooks.
1059  * The one given, and the one attached to it. Disconnect the hooks
1060  * from each other first. We reconnect the peer hook to the 'dead'
1061  * hook so that it can still exist after we depart. We then
1062  * send the peer its own destroy message. This ensures that we only
1063  * interact with the peer's structures when it is locked processing that
1064  * message. We hold a reference to the peer hook so we are guaranteed that
1065  * the peer hook and node are still going to exist until
1066  * we are finished there as the hook holds a ref on the node.
1067  * We run this same code again on the peer hook, but that time it is already
1068  * attached to the 'dead' hook.
1069  *
1070  * This routine is called at all stages of hook creation
1071  * on error detection and must be able to handle any such stage.
1072  */
1073 void
1074 ng_destroy_hook(hook_p hook)
1075 {
1076         hook_p peer;
1077         node_p node;
1078
1079         if (hook == &ng_deadhook) {     /* better safe than sorry */
1080                 printf("ng_destroy_hook called on deadhook\n");
1081                 return;
1082         }
1083
1084         /*
1085          * Protect divorce process with mutex, to avoid races on
1086          * simultaneous disconnect.
1087          */
1088         mtx_lock(&ng_topo_mtx);
1089
1090         hook->hk_flags |= HK_INVALID;
1091
1092         peer = NG_HOOK_PEER(hook);
1093         node = NG_HOOK_NODE(hook);
1094
1095         if (peer && (peer != &ng_deadhook)) {
1096                 /*
1097                  * Set the peer to point to ng_deadhook
1098                  * from this moment on we are effectively independent it.
1099                  * send it an rmhook message of it's own.
1100                  */
1101                 peer->hk_peer = &ng_deadhook;   /* They no longer know us */
1102                 hook->hk_peer = &ng_deadhook;   /* Nor us, them */
1103                 if (NG_HOOK_NODE(peer) == &ng_deadnode) {
1104                         /*
1105                          * If it's already divorced from a node,
1106                          * just free it.
1107                          */
1108                         mtx_unlock(&ng_topo_mtx);
1109                 } else {
1110                         mtx_unlock(&ng_topo_mtx);
1111                         ng_rmhook_self(peer);   /* Send it a surprise */
1112                 }
1113                 NG_HOOK_UNREF(peer);            /* account for peer link */
1114                 NG_HOOK_UNREF(hook);            /* account for peer link */
1115         } else
1116                 mtx_unlock(&ng_topo_mtx);
1117
1118         mtx_assert(&ng_topo_mtx, MA_NOTOWNED);
1119
1120         /*
1121          * Remove the hook from the node's list to avoid possible recursion
1122          * in case the disconnection results in node shutdown.
1123          */
1124         if (node == &ng_deadnode) { /* happens if called from ng_con_nodes() */
1125                 return;
1126         }
1127         LIST_REMOVE(hook, hk_hooks);
1128         node->nd_numhooks--;
1129         if (node->nd_type->disconnect) {
1130                 /*
1131                  * The type handler may elect to destroy the node so don't
1132                  * trust its existence after this point. (except
1133                  * that we still hold a reference on it. (which we
1134                  * inherrited from the hook we are destroying)
1135                  */
1136                 (*node->nd_type->disconnect) (hook);
1137         }
1138
1139         /*
1140          * Note that because we will point to ng_deadnode, the original node
1141          * is not decremented automatically so we do that manually.
1142          */
1143         _NG_HOOK_NODE(hook) = &ng_deadnode;
1144         NG_NODE_UNREF(node);    /* We no longer point to it so adjust count */
1145         NG_HOOK_UNREF(hook);    /* Account for linkage (in list) to node */
1146 }
1147
1148 /*
1149  * Take two hooks on a node and merge the connection so that the given node
1150  * is effectively bypassed.
1151  */
1152 int
1153 ng_bypass(hook_p hook1, hook_p hook2)
1154 {
1155         if (hook1->hk_node != hook2->hk_node) {
1156                 TRAP_ERROR();
1157                 return (EINVAL);
1158         }
1159         hook1->hk_peer->hk_peer = hook2->hk_peer;
1160         hook2->hk_peer->hk_peer = hook1->hk_peer;
1161
1162         hook1->hk_peer = &ng_deadhook;
1163         hook2->hk_peer = &ng_deadhook;
1164
1165         NG_HOOK_UNREF(hook1);
1166         NG_HOOK_UNREF(hook2);
1167
1168         /* XXX If we ever cache methods on hooks update them as well */
1169         ng_destroy_hook(hook1);
1170         ng_destroy_hook(hook2);
1171         return (0);
1172 }
1173
1174 /*
1175  * Install a new netgraph type
1176  */
1177 int
1178 ng_newtype(struct ng_type *tp)
1179 {
1180         const size_t namelen = strlen(tp->name);
1181
1182         /* Check version and type name fields */
1183         if ((tp->version != NG_ABI_VERSION)
1184         || (namelen == 0)
1185         || (namelen >= NG_TYPESIZ)) {
1186                 TRAP_ERROR();
1187                 if (tp->version != NG_ABI_VERSION) {
1188                         printf("Netgraph: Node type rejected. ABI mismatch. Suggest recompile\n");
1189                 }
1190                 return (EINVAL);
1191         }
1192
1193         /* Check for name collision */
1194         if (ng_findtype(tp->name) != NULL) {
1195                 TRAP_ERROR();
1196                 return (EEXIST);
1197         }
1198
1199
1200         /* Link in new type */
1201         mtx_lock(&ng_typelist_mtx);
1202         LIST_INSERT_HEAD(&ng_typelist, tp, types);
1203         tp->refs = 1;   /* first ref is linked list */
1204         mtx_unlock(&ng_typelist_mtx);
1205         return (0);
1206 }
1207
1208 /*
1209  * unlink a netgraph type
1210  * If no examples exist
1211  */
1212 int
1213 ng_rmtype(struct ng_type *tp)
1214 {
1215         /* Check for name collision */
1216         if (tp->refs != 1) {
1217                 TRAP_ERROR();
1218                 return (EBUSY);
1219         }
1220
1221         /* Unlink type */
1222         mtx_lock(&ng_typelist_mtx);
1223         LIST_REMOVE(tp, types);
1224         mtx_unlock(&ng_typelist_mtx);
1225         return (0);
1226 }
1227
1228 /*
1229  * Look for a type of the name given
1230  */
1231 struct ng_type *
1232 ng_findtype(const char *typename)
1233 {
1234         struct ng_type *type;
1235
1236         mtx_lock(&ng_typelist_mtx);
1237         LIST_FOREACH(type, &ng_typelist, types) {
1238                 if (strcmp(type->name, typename) == 0)
1239                         break;
1240         }
1241         mtx_unlock(&ng_typelist_mtx);
1242         return (type);
1243 }
1244
1245 /************************************************************************
1246                         Composite routines
1247 ************************************************************************/
1248 /*
1249  * Connect two nodes using the specified hooks, using queued functions.
1250  */
1251 static int
1252 ng_con_part3(node_p node, item_p item, hook_p hook)
1253 {
1254         int     error = 0;
1255
1256         /*
1257          * When we run, we know that the node 'node' is locked for us.
1258          * Our caller has a reference on the hook.
1259          * Our caller has a reference on the node.
1260          * (In this case our caller is ng_apply_item() ).
1261          * The peer hook has a reference on the hook.
1262          * We are all set up except for the final call to the node, and
1263          * the clearing of the INVALID flag.
1264          */
1265         if (NG_HOOK_NODE(hook) == &ng_deadnode) {
1266                 /*
1267                  * The node must have been freed again since we last visited
1268                  * here. ng_destry_hook() has this effect but nothing else does.
1269                  * We should just release our references and
1270                  * free anything we can think of.
1271                  * Since we know it's been destroyed, and it's our caller
1272                  * that holds the references, just return.
1273                  */
1274                 ERROUT(ENOENT);
1275         }
1276         if (hook->hk_node->nd_type->connect) {
1277                 if ((error = (*hook->hk_node->nd_type->connect) (hook))) {
1278                         ng_destroy_hook(hook);  /* also zaps peer */
1279                         printf("failed in ng_con_part3()\n");
1280                         ERROUT(error);
1281                 }
1282         }
1283         /*
1284          *  XXX this is wrong for SMP. Possibly we need
1285          * to separate out 'create' and 'invalid' flags.
1286          * should only set flags on hooks we have locked under our node.
1287          */
1288         hook->hk_flags &= ~HK_INVALID;
1289 done:
1290         NG_FREE_ITEM(item);
1291         return (error);
1292 }
1293
1294 static int
1295 ng_con_part2(node_p node, item_p item, hook_p hook)
1296 {
1297         hook_p  peer;
1298         int     error = 0;
1299
1300         /*
1301          * When we run, we know that the node 'node' is locked for us.
1302          * Our caller has a reference on the hook.
1303          * Our caller has a reference on the node.
1304          * (In this case our caller is ng_apply_item() ).
1305          * The peer hook has a reference on the hook.
1306          * our node pointer points to the 'dead' node.
1307          * First check the hook name is unique.
1308          * Should not happen because we checked before queueing this.
1309          */
1310         if (ng_findhook(node, NG_HOOK_NAME(hook)) != NULL) {
1311                 TRAP_ERROR();
1312                 ng_destroy_hook(hook); /* should destroy peer too */
1313                 printf("failed in ng_con_part2()\n");
1314                 ERROUT(EEXIST);
1315         }
1316         /*
1317          * Check if the node type code has something to say about it
1318          * If it fails, the unref of the hook will also unref the attached node,
1319          * however since that node is 'ng_deadnode' this will do nothing.
1320          * The peer hook will also be destroyed.
1321          */
1322         if (node->nd_type->newhook != NULL) {
1323                 if ((error = (*node->nd_type->newhook)(node, hook,
1324                     hook->hk_name))) {
1325                         ng_destroy_hook(hook); /* should destroy peer too */
1326                         printf("failed in ng_con_part2()\n");
1327                         ERROUT(error);
1328                 }
1329         }
1330
1331         /*
1332          * The 'type' agrees so far, so go ahead and link it in.
1333          * We'll ask again later when we actually connect the hooks.
1334          */
1335         hook->hk_node = node;           /* just overwrite ng_deadnode */
1336         NG_NODE_REF(node);              /* each hook counts as a reference */
1337         LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
1338         node->nd_numhooks++;
1339         NG_HOOK_REF(hook);      /* one for the node */
1340         
1341         /*
1342          * We now have a symmetrical situation, where both hooks have been
1343          * linked to their nodes, the newhook methods have been called
1344          * And the references are all correct. The hooks are still marked
1345          * as invalid, as we have not called the 'connect' methods
1346          * yet.
1347          * We can call the local one immediately as we have the
1348          * node locked, but we need to queue the remote one.
1349          */
1350         if (hook->hk_node->nd_type->connect) {
1351                 if ((error = (*hook->hk_node->nd_type->connect) (hook))) {
1352                         ng_destroy_hook(hook);  /* also zaps peer */
1353                         printf("failed in ng_con_part2(A)\n");
1354                         ERROUT(error);
1355                 }
1356         }
1357
1358         /*
1359          * Acquire topo mutex to avoid race with ng_destroy_hook().
1360          */
1361         mtx_lock(&ng_topo_mtx);
1362         peer = hook->hk_peer;
1363         if (peer == &ng_deadhook) {
1364                 mtx_unlock(&ng_topo_mtx);
1365                 printf("failed in ng_con_part2(B)\n");
1366                 ng_destroy_hook(hook);
1367                 ERROUT(ENOENT);
1368         }
1369         mtx_unlock(&ng_topo_mtx);
1370
1371         if ((error = ng_send_fn2(peer->hk_node, peer, item, &ng_con_part3,
1372             NULL, 0, NG_REUSE_ITEM))) {
1373                 printf("failed in ng_con_part2(C)\n");
1374                 ng_destroy_hook(hook);  /* also zaps peer */
1375                 return (error);         /* item was consumed. */
1376         }
1377         hook->hk_flags &= ~HK_INVALID; /* need both to be able to work */
1378         return (0);                     /* item was consumed. */
1379 done:
1380         NG_FREE_ITEM(item);
1381         return (error);
1382 }
1383
1384 /*
1385  * Connect this node with another node. We assume that this node is
1386  * currently locked, as we are only called from an NGM_CONNECT message.
1387  */
1388 static int
1389 ng_con_nodes(item_p item, node_p node, const char *name,
1390     node_p node2, const char *name2)
1391 {
1392         int     error;
1393         hook_p  hook;
1394         hook_p  hook2;
1395
1396         if (ng_findhook(node2, name2) != NULL) {
1397                 return(EEXIST);
1398         }
1399         if ((error = ng_add_hook(node, name, &hook)))  /* gives us a ref */
1400                 return (error);
1401         /* Allocate the other hook and link it up */
1402         NG_ALLOC_HOOK(hook2);
1403         if (hook2 == NULL) {
1404                 TRAP_ERROR();
1405                 ng_destroy_hook(hook);  /* XXX check ref counts so far */
1406                 NG_HOOK_UNREF(hook);    /* including our ref */
1407                 return (ENOMEM);
1408         }
1409         hook2->hk_refs = 1;             /* start with a reference for us. */
1410         hook2->hk_flags = HK_INVALID;
1411         hook2->hk_peer = hook;          /* Link the two together */
1412         hook->hk_peer = hook2;  
1413         NG_HOOK_REF(hook);              /* Add a ref for the peer to each*/
1414         NG_HOOK_REF(hook2);
1415         hook2->hk_node = &ng_deadnode;
1416         strlcpy(NG_HOOK_NAME(hook2), name2, NG_HOOKSIZ);
1417
1418         /*
1419          * Queue the function above.
1420          * Procesing continues in that function in the lock context of
1421          * the other node.
1422          */
1423         if ((error = ng_send_fn2(node2, hook2, item, &ng_con_part2, NULL, 0,
1424             NG_NOFLAGS))) {
1425                 printf("failed in ng_con_nodes(): %d\n", error);
1426                 ng_destroy_hook(hook);  /* also zaps peer */
1427         }
1428
1429         NG_HOOK_UNREF(hook);            /* Let each hook go if it wants to */
1430         NG_HOOK_UNREF(hook2);
1431         return (error);
1432 }
1433
1434 /*
1435  * Make a peer and connect.
1436  * We assume that the local node is locked.
1437  * The new node probably doesn't need a lock until
1438  * it has a hook, because it cannot really have any work until then,
1439  * but we should think about it a bit more.
1440  *
1441  * The problem may come if the other node also fires up
1442  * some hardware or a timer or some other source of activation,
1443  * also it may already get a command msg via it's ID.
1444  *
1445  * We could use the same method as ng_con_nodes() but we'd have
1446  * to add ability to remove the node when failing. (Not hard, just
1447  * make arg1 point to the node to remove).
1448  * Unless of course we just ignore failure to connect and leave
1449  * an unconnected node?
1450  */
1451 static int
1452 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
1453 {
1454         node_p  node2;
1455         hook_p  hook1, hook2;
1456         int     error;
1457
1458         if ((error = ng_make_node(type, &node2))) {
1459                 return (error);
1460         }
1461
1462         if ((error = ng_add_hook(node, name, &hook1))) { /* gives us a ref */
1463                 ng_rmnode(node2, NULL, NULL, 0);
1464                 return (error);
1465         }
1466
1467         if ((error = ng_add_hook(node2, name2, &hook2))) {
1468                 ng_rmnode(node2, NULL, NULL, 0);
1469                 ng_destroy_hook(hook1);
1470                 NG_HOOK_UNREF(hook1);
1471                 return (error);
1472         }
1473
1474         /*
1475          * Actually link the two hooks together.
1476          */
1477         hook1->hk_peer = hook2;
1478         hook2->hk_peer = hook1;
1479
1480         /* Each hook is referenced by the other */
1481         NG_HOOK_REF(hook1);
1482         NG_HOOK_REF(hook2);
1483
1484         /* Give each node the opportunity to veto the pending connection */
1485         if (hook1->hk_node->nd_type->connect) {
1486                 error = (*hook1->hk_node->nd_type->connect) (hook1);
1487         }
1488
1489         if ((error == 0) && hook2->hk_node->nd_type->connect) {
1490                 error = (*hook2->hk_node->nd_type->connect) (hook2);
1491
1492         }
1493
1494         /*
1495          * drop the references we were holding on the two hooks.
1496          */
1497         if (error) {
1498                 ng_destroy_hook(hook2); /* also zaps hook1 */
1499                 ng_rmnode(node2, NULL, NULL, 0);
1500         } else {
1501                 /* As a last act, allow the hooks to be used */
1502                 hook1->hk_flags &= ~HK_INVALID;
1503                 hook2->hk_flags &= ~HK_INVALID;
1504         }
1505         NG_HOOK_UNREF(hook1);
1506         NG_HOOK_UNREF(hook2);
1507         return (error);
1508 }
1509
1510 /************************************************************************
1511                 Utility routines to send self messages
1512 ************************************************************************/
1513         
1514 /* Shut this node down as soon as everyone is clear of it */
1515 /* Should add arg "immediately" to jump the queue */
1516 int
1517 ng_rmnode_self(node_p node)
1518 {
1519         int             error;
1520
1521         if (node == &ng_deadnode)
1522                 return (0);
1523         node->nd_flags |= NGF_INVALID;
1524         if (node->nd_flags & NGF_CLOSING)
1525                 return (0);
1526
1527         error = ng_send_fn(node, NULL, &ng_rmnode, NULL, 0);
1528         return (error);
1529 }
1530
1531 static void
1532 ng_rmhook_part2(node_p node, hook_p hook, void *arg1, int arg2)
1533 {
1534         ng_destroy_hook(hook);
1535         return ;
1536 }
1537
1538 int
1539 ng_rmhook_self(hook_p hook)
1540 {
1541         int             error;
1542         node_p node = NG_HOOK_NODE(hook);
1543
1544         if (node == &ng_deadnode)
1545                 return (0);
1546
1547         error = ng_send_fn(node, hook, &ng_rmhook_part2, NULL, 0);
1548         return (error);
1549 }
1550
1551 /***********************************************************************
1552  * Parse and verify a string of the form:  <NODE:><PATH>
1553  *
1554  * Such a string can refer to a specific node or a specific hook
1555  * on a specific node, depending on how you look at it. In the
1556  * latter case, the PATH component must not end in a dot.
1557  *
1558  * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1559  * of hook names separated by dots. This breaks out the original
1560  * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1561  * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1562  * the final hook component of <PATH>, if any, otherwise NULL.
1563  *
1564  * This returns -1 if the path is malformed. The char ** are optional.
1565  ***********************************************************************/
1566 int
1567 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1568 {
1569         char    *node, *path, *hook;
1570         int     k;
1571
1572         /*
1573          * Extract absolute NODE, if any
1574          */
1575         for (path = addr; *path && *path != ':'; path++);
1576         if (*path) {
1577                 node = addr;    /* Here's the NODE */
1578                 *path++ = '\0'; /* Here's the PATH */
1579
1580                 /* Node name must not be empty */
1581                 if (!*node)
1582                         return -1;
1583
1584                 /* A name of "." is OK; otherwise '.' not allowed */
1585                 if (strcmp(node, ".") != 0) {
1586                         for (k = 0; node[k]; k++)
1587                                 if (node[k] == '.')
1588                                         return -1;
1589                 }
1590         } else {
1591                 node = NULL;    /* No absolute NODE */
1592                 path = addr;    /* Here's the PATH */
1593         }
1594
1595         /* Snoop for illegal characters in PATH */
1596         for (k = 0; path[k]; k++)
1597                 if (path[k] == ':')
1598                         return -1;
1599
1600         /* Check for no repeated dots in PATH */
1601         for (k = 0; path[k]; k++)
1602                 if (path[k] == '.' && path[k + 1] == '.')
1603                         return -1;
1604
1605         /* Remove extra (degenerate) dots from beginning or end of PATH */
1606         if (path[0] == '.')
1607                 path++;
1608         if (*path && path[strlen(path) - 1] == '.')
1609                 path[strlen(path) - 1] = 0;
1610
1611         /* If PATH has a dot, then we're not talking about a hook */
1612         if (*path) {
1613                 for (hook = path, k = 0; path[k]; k++)
1614                         if (path[k] == '.') {
1615                                 hook = NULL;
1616                                 break;
1617                         }
1618         } else
1619                 path = hook = NULL;
1620
1621         /* Done */
1622         if (nodep)
1623                 *nodep = node;
1624         if (pathp)
1625                 *pathp = path;
1626         if (hookp)
1627                 *hookp = hook;
1628         return (0);
1629 }
1630
1631 /*
1632  * Given a path, which may be absolute or relative, and a starting node,
1633  * return the destination node.
1634  */
1635 int
1636 ng_path2noderef(node_p here, const char *address,
1637                                 node_p *destp, hook_p *lasthook)
1638 {
1639         char    fullpath[NG_PATHSIZ];
1640         char   *nodename, *path, pbuf[2];
1641         node_p  node, oldnode;
1642         char   *cp;
1643         hook_p hook = NULL;
1644
1645         /* Initialize */
1646         if (destp == NULL) {
1647                 TRAP_ERROR();
1648                 return EINVAL;
1649         }
1650         *destp = NULL;
1651
1652         /* Make a writable copy of address for ng_path_parse() */
1653         strncpy(fullpath, address, sizeof(fullpath) - 1);
1654         fullpath[sizeof(fullpath) - 1] = '\0';
1655
1656         /* Parse out node and sequence of hooks */
1657         if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1658                 TRAP_ERROR();
1659                 return EINVAL;
1660         }
1661         if (path == NULL) {
1662                 pbuf[0] = '.';  /* Needs to be writable */
1663                 pbuf[1] = '\0';
1664                 path = pbuf;
1665         }
1666
1667         /*
1668          * For an absolute address, jump to the starting node.
1669          * Note that this holds a reference on the node for us.
1670          * Don't forget to drop the reference if we don't need it.
1671          */
1672         if (nodename) {
1673                 node = ng_name2noderef(here, nodename);
1674                 if (node == NULL) {
1675                         TRAP_ERROR();
1676                         return (ENOENT);
1677                 }
1678         } else {
1679                 if (here == NULL) {
1680                         TRAP_ERROR();
1681                         return (EINVAL);
1682                 }
1683                 node = here;
1684                 NG_NODE_REF(node);
1685         }
1686
1687         /*
1688          * Now follow the sequence of hooks
1689          * XXX
1690          * We actually cannot guarantee that the sequence
1691          * is not being demolished as we crawl along it
1692          * without extra-ordinary locking etc.
1693          * So this is a bit dodgy to say the least.
1694          * We can probably hold up some things by holding
1695          * the nodelist mutex for the time of this
1696          * crawl if we wanted.. At least that way we wouldn't have to
1697          * worry about the nodes disappearing, but the hooks would still
1698          * be a problem.
1699          */
1700         for (cp = path; node != NULL && *cp != '\0'; ) {
1701                 char *segment;
1702
1703                 /*
1704                  * Break out the next path segment. Replace the dot we just
1705                  * found with a NUL; "cp" points to the next segment (or the
1706                  * NUL at the end).
1707                  */
1708                 for (segment = cp; *cp != '\0'; cp++) {
1709                         if (*cp == '.') {
1710                                 *cp++ = '\0';
1711                                 break;
1712                         }
1713                 }
1714
1715                 /* Empty segment */
1716                 if (*segment == '\0')
1717                         continue;
1718
1719                 /* We have a segment, so look for a hook by that name */
1720                 hook = ng_findhook(node, segment);
1721
1722                 /* Can't get there from here... */
1723                 if (hook == NULL
1724                     || NG_HOOK_PEER(hook) == NULL
1725                     || NG_HOOK_NOT_VALID(hook)
1726                     || NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))) {
1727                         TRAP_ERROR();
1728                         NG_NODE_UNREF(node);
1729 #if 0
1730                         printf("hooknotvalid %s %s %d %d %d %d ",
1731                                         path,
1732                                         segment,
1733                                         hook == NULL,
1734                                         NG_HOOK_PEER(hook) == NULL,
1735                                         NG_HOOK_NOT_VALID(hook),
1736                                         NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook)));
1737 #endif
1738                         return (ENOENT);
1739                 }
1740
1741                 /*
1742                  * Hop on over to the next node
1743                  * XXX
1744                  * Big race conditions here as hooks and nodes go away
1745                  * *** Idea.. store an ng_ID_t in each hook and use that
1746                  * instead of the direct hook in this crawl?
1747                  */
1748                 oldnode = node;
1749                 if ((node = NG_PEER_NODE(hook)))
1750                         NG_NODE_REF(node);      /* XXX RACE */
1751                 NG_NODE_UNREF(oldnode); /* XXX another race */
1752                 if (NG_NODE_NOT_VALID(node)) {
1753                         NG_NODE_UNREF(node);    /* XXX more races */
1754                         node = NULL;
1755                 }
1756         }
1757
1758         /* If node somehow missing, fail here (probably this is not needed) */
1759         if (node == NULL) {
1760                 TRAP_ERROR();
1761                 return (ENXIO);
1762         }
1763
1764         /* Done */
1765         *destp = node;
1766         if (lasthook != NULL)
1767                 *lasthook = (hook ? NG_HOOK_PEER(hook) : NULL);
1768         return (0);
1769 }
1770
1771 /***************************************************************\
1772 * Input queue handling.
1773 * All activities are submitted to the node via the input queue
1774 * which implements a multiple-reader/single-writer gate.
1775 * Items which cannot be handled immediately are queued.
1776 *
1777 * read-write queue locking inline functions                     *
1778 \***************************************************************/
1779
1780 static __inline item_p ng_dequeue(struct ng_queue * ngq, int *rw);
1781 static __inline item_p ng_acquire_read(struct ng_queue * ngq,
1782                                         item_p  item);
1783 static __inline item_p ng_acquire_write(struct ng_queue * ngq,
1784                                         item_p  item);
1785 static __inline void    ng_leave_read(struct ng_queue * ngq);
1786 static __inline void    ng_leave_write(struct ng_queue * ngq);
1787 static __inline void    ng_queue_rw(struct ng_queue * ngq,
1788                                         item_p  item, int rw);
1789
1790 /*
1791  * Definition of the bits fields in the ng_queue flag word.
1792  * Defined here rather than in netgraph.h because no-one should fiddle
1793  * with them.
1794  *
1795  * The ordering here may be important! don't shuffle these.
1796  */
1797 /*-
1798  Safety Barrier--------+ (adjustable to suit taste) (not used yet)
1799                        |
1800                        V
1801 +-------+-------+-------+-------+-------+-------+-------+-------+
1802   | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
1803   | |A|c|t|i|v|e| |R|e|a|d|e|r| |C|o|u|n|t| | | | | | | | | |P|A|
1804   | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |O|W|
1805 +-------+-------+-------+-------+-------+-------+-------+-------+
1806   \___________________________ ____________________________/ | |
1807                             V                                | |
1808                   [active reader count]                      | |
1809                                                              | |
1810             Operation Pending -------------------------------+ |
1811                                                                |
1812           Active Writer ---------------------------------------+
1813
1814 Node queue has such semantics:
1815 - All flags modifications are atomic.
1816 - Reader count can be incremented only if there is no writer or pending flags.
1817   As soon as this can't be done with single operation, it is implemented with
1818   spin loop and atomic_cmpset().
1819 - Writer flag can be set only if there is no any bits set.
1820   It is implemented with atomic_cmpset().
1821 - Pending flag can be set any time, but to avoid collision on queue processing
1822   all queue fields are protected by the mutex.
1823 - Queue processing thread reads queue holding the mutex, but releases it while
1824   processing. When queue is empty pending flag is removed.
1825 */
1826
1827 #define WRITER_ACTIVE   0x00000001
1828 #define OP_PENDING      0x00000002
1829 #define READER_INCREMENT 0x00000004
1830 #define READER_MASK     0xfffffffc      /* Not valid if WRITER_ACTIVE is set */
1831 #define SAFETY_BARRIER  0x00100000      /* 128K items queued should be enough */
1832
1833 /* Defines of more elaborate states on the queue */
1834 /* Mask of bits a new read cares about */
1835 #define NGQ_RMASK       (WRITER_ACTIVE|OP_PENDING)
1836
1837 /* Mask of bits a new write cares about */
1838 #define NGQ_WMASK       (NGQ_RMASK|READER_MASK)
1839
1840 /* Test to decide if there is something on the queue. */
1841 #define QUEUE_ACTIVE(QP) ((QP)->q_flags & OP_PENDING)
1842
1843 /* How to decide what the next queued item is. */
1844 #define HEAD_IS_READER(QP)  NGI_QUEUED_READER((QP)->queue)
1845 #define HEAD_IS_WRITER(QP)  NGI_QUEUED_WRITER((QP)->queue) /* notused */
1846
1847 /* Read the status to decide if the next item on the queue can now run. */
1848 #define QUEUED_READER_CAN_PROCEED(QP)                   \
1849                 (((QP)->q_flags & (NGQ_RMASK & ~OP_PENDING)) == 0)
1850 #define QUEUED_WRITER_CAN_PROCEED(QP)                   \
1851                 (((QP)->q_flags & (NGQ_WMASK & ~OP_PENDING)) == 0)
1852
1853 /* Is there a chance of getting ANY work off the queue? */
1854 #define NEXT_QUEUED_ITEM_CAN_PROCEED(QP)                                \
1855         ((HEAD_IS_READER(QP)) ? QUEUED_READER_CAN_PROCEED(QP) :         \
1856                                 QUEUED_WRITER_CAN_PROCEED(QP))
1857
1858
1859 #define NGQRW_R 0
1860 #define NGQRW_W 1
1861
1862 /*
1863  * Taking into account the current state of the queue and node, possibly take
1864  * the next entry off the queue and return it. Return NULL if there was
1865  * nothing we could return, either because there really was nothing there, or
1866  * because the node was in a state where it cannot yet process the next item
1867  * on the queue.
1868  */
1869 static __inline item_p
1870 ng_dequeue(struct ng_queue *ngq, int *rw)
1871 {
1872         item_p item;
1873
1874         /* This MUST be called with the mutex held. */
1875         mtx_assert(&ngq->q_mtx, MA_OWNED);
1876
1877         /* If there is nothing queued, then just return. */
1878         if (!QUEUE_ACTIVE(ngq)) {
1879                 CTR4(KTR_NET, "%20s: node [%x] (%p) queue empty; "
1880                     "queue flags 0x%lx", __func__,
1881                     ngq->q_node->nd_ID, ngq->q_node, ngq->q_flags);
1882                 return (NULL);
1883         }
1884
1885         /*
1886          * From here, we can assume there is a head item.
1887          * We need to find out what it is and if it can be dequeued, given
1888          * the current state of the node.
1889          */
1890         if (HEAD_IS_READER(ngq)) {
1891                 while (1) {
1892                         long t = ngq->q_flags;
1893                         if (t & WRITER_ACTIVE) {
1894                                 /* There is writer, reader can't proceed. */
1895                                 CTR4(KTR_NET, "%20s: node [%x] (%p) queued reader "
1896                                     "can't proceed; queue flags 0x%lx", __func__,
1897                                     ngq->q_node->nd_ID, ngq->q_node, t);
1898                                 return (NULL);
1899                         }
1900                         if (atomic_cmpset_acq_long(&ngq->q_flags, t,
1901                             t + READER_INCREMENT))
1902                                 break;
1903                         cpu_spinwait();
1904                 }
1905                 /* We have got reader lock for the node. */
1906                 *rw = NGQRW_R;
1907         } else if (atomic_cmpset_acq_long(&ngq->q_flags, OP_PENDING,
1908             OP_PENDING + WRITER_ACTIVE)) {
1909                 /* We have got writer lock for the node. */
1910                 *rw = NGQRW_W;
1911         } else {
1912                 /* There is somebody other, writer can't proceed. */
1913                 CTR4(KTR_NET, "%20s: node [%x] (%p) queued writer "
1914                     "can't proceed; queue flags 0x%lx", __func__,
1915                     ngq->q_node->nd_ID, ngq->q_node, ngq->q_flags);
1916                 return (NULL);
1917         }
1918
1919         /*
1920          * Now we dequeue the request (whatever it may be) and correct the
1921          * pending flags and the next and last pointers.
1922          */
1923         item = ngq->queue;
1924         ngq->queue = item->el_next;
1925         if (ngq->last == &(item->el_next)) {
1926                 ngq->last = &(ngq->queue);
1927                 atomic_clear_long(&ngq->q_flags, OP_PENDING);
1928         }
1929         CTR6(KTR_NET, "%20s: node [%x] (%p) returning item %p as %s; "
1930             "queue flags 0x%lx", __func__,
1931             ngq->q_node->nd_ID, ngq->q_node, item, *rw ? "WRITER" : "READER" ,
1932             ngq->q_flags);
1933         return (item);
1934 }
1935
1936 /*
1937  * Queue a packet to be picked up later by someone else.
1938  * If the queue could be run now, add node to the queue handler's worklist.
1939  */
1940 static __inline void
1941 ng_queue_rw(struct ng_queue * ngq, item_p  item, int rw)
1942 {
1943         if (rw == NGQRW_W)
1944                 NGI_SET_WRITER(item);
1945         else
1946                 NGI_SET_READER(item);
1947         item->el_next = NULL;   /* maybe not needed */
1948
1949         NG_QUEUE_LOCK(ngq);
1950         /* Set OP_PENDING flag and enqueue the item. */
1951         atomic_set_long(&ngq->q_flags, OP_PENDING);
1952         *ngq->last = item;
1953         ngq->last = &(item->el_next);
1954
1955         CTR5(KTR_NET, "%20s: node [%x] (%p) queued item %p as %s", __func__,
1956             ngq->q_node->nd_ID, ngq->q_node, item, rw ? "WRITER" : "READER" );
1957             
1958         /*
1959          * We can take the worklist lock with the node locked
1960          * BUT NOT THE REVERSE!
1961          */
1962         if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
1963                 ng_worklist_add(ngq->q_node);
1964         NG_QUEUE_UNLOCK(ngq);
1965 }
1966
1967 /* Acquire reader lock on node. If node is busy, queue the packet. */
1968 static __inline item_p
1969 ng_acquire_read(struct ng_queue *ngq, item_p item)
1970 {
1971         KASSERT(ngq != &ng_deadnode.nd_input_queue,
1972             ("%s: working on deadnode", __func__));
1973
1974         /* Reader needs node without writer and pending items. */
1975         while (1) {
1976                 long t = ngq->q_flags;
1977                 if (t & NGQ_RMASK)
1978                         break; /* Node is not ready for reader. */
1979                 if (atomic_cmpset_acq_long(&ngq->q_flags, t, t + READER_INCREMENT)) {
1980                         /* Successfully grabbed node */
1981                         CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
1982                             __func__, ngq->q_node->nd_ID, ngq->q_node, item);
1983                         return (item);
1984                 }
1985                 cpu_spinwait();
1986         };
1987
1988         /* Queue the request for later. */
1989         ng_queue_rw(ngq, item, NGQRW_R);
1990
1991         return (NULL);
1992 }
1993
1994 /* Acquire writer lock on node. If node is busy, queue the packet. */
1995 static __inline item_p
1996 ng_acquire_write(struct ng_queue *ngq, item_p item)
1997 {
1998         KASSERT(ngq != &ng_deadnode.nd_input_queue,
1999             ("%s: working on deadnode", __func__));
2000
2001         /* Writer needs completely idle node. */
2002         if (atomic_cmpset_acq_long(&ngq->q_flags, 0, WRITER_ACTIVE)) {
2003                 /* Successfully grabbed node */
2004                 CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
2005                     __func__, ngq->q_node->nd_ID, ngq->q_node, item);
2006                 return (item);
2007         }
2008
2009         /* Queue the request for later. */
2010         ng_queue_rw(ngq, item, NGQRW_W);
2011
2012         return (NULL);
2013 }
2014
2015 #if 0
2016 static __inline item_p
2017 ng_upgrade_write(struct ng_queue *ngq, item_p item)
2018 {
2019         KASSERT(ngq != &ng_deadnode.nd_input_queue,
2020             ("%s: working on deadnode", __func__));
2021
2022         NGI_SET_WRITER(item);
2023
2024         mtx_lock_spin(&(ngq->q_mtx));
2025
2026         /*
2027          * There will never be no readers as we are there ourselves.
2028          * Set the WRITER_ACTIVE flags ASAP to block out fast track readers.
2029          * The caller we are running from will call ng_leave_read()
2030          * soon, so we must account for that. We must leave again with the
2031          * READER lock. If we find other readers, then
2032          * queue the request for later. However "later" may be rignt now
2033          * if there are no readers. We don't really care if there are queued
2034          * items as we will bypass them anyhow.
2035          */
2036         atomic_add_long(&ngq->q_flags, WRITER_ACTIVE - READER_INCREMENT);
2037         if (ngq->q_flags & (NGQ_WMASK & ~OP_PENDING) == WRITER_ACTIVE) {
2038                 mtx_unlock_spin(&(ngq->q_mtx));
2039                 
2040                 /* It's just us, act on the item. */
2041                 /* will NOT drop writer lock when done */
2042                 ng_apply_item(node, item, 0);
2043
2044                 /*
2045                  * Having acted on the item, atomically 
2046                  * down grade back to READER and finish up
2047                  */
2048                 atomic_add_long(&ngq->q_flags,
2049                     READER_INCREMENT - WRITER_ACTIVE);
2050
2051                 /* Our caller will call ng_leave_read() */
2052                 return;
2053         }
2054         /*
2055          * It's not just us active, so queue us AT THE HEAD.
2056          * "Why?" I hear you ask.
2057          * Put us at the head of the queue as we've already been
2058          * through it once. If there is nothing else waiting,
2059          * set the correct flags.
2060          */
2061         if ((item->el_next = ngq->queue) == NULL) {
2062                 /*
2063                  * Set up the "last" pointer.
2064                  * We are the only (and thus last) item
2065                  */
2066                 ngq->last = &(item->el_next);
2067
2068                 /* We've gone from, 0 to 1 item in the queue */
2069                 atomic_set_long(&ngq->q_flags, OP_PENDING);
2070
2071                 CTR3(KTR_NET, "%20s: node [%x] (%p) set OP_PENDING", __func__,
2072                     ngq->q_node->nd_ID, ngq->q_node);
2073         };
2074         ngq->queue = item;
2075         CTR5(KTR_NET, "%20s: node [%x] (%p) requeued item %p as WRITER",
2076             __func__, ngq->q_node->nd_ID, ngq->q_node, item );
2077
2078         /* Reverse what we did above. That downgrades us back to reader */
2079         atomic_add_long(&ngq->q_flags, READER_INCREMENT - WRITER_ACTIVE);
2080         if (QUEUE_ACTIVE(ngq) && NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2081                 ng_worklist_add(ngq->q_node);
2082         mtx_unlock_spin(&(ngq->q_mtx));
2083
2084         return;
2085 }
2086
2087 #endif
2088
2089 /* Release reader lock. */
2090 static __inline void
2091 ng_leave_read(struct ng_queue *ngq)
2092 {
2093         atomic_subtract_rel_long(&ngq->q_flags, READER_INCREMENT);
2094 }
2095
2096 /* Release writer lock. */
2097 static __inline void
2098 ng_leave_write(struct ng_queue *ngq)
2099 {
2100         atomic_clear_rel_long(&ngq->q_flags, WRITER_ACTIVE);
2101 }
2102
2103 /* Purge node queue. Called on node shutdown. */
2104 static void
2105 ng_flush_input_queue(struct ng_queue * ngq)
2106 {
2107         item_p item;
2108
2109         NG_QUEUE_LOCK(ngq);
2110         while (ngq->queue) {
2111                 item = ngq->queue;
2112                 ngq->queue = item->el_next;
2113                 if (ngq->last == &(item->el_next)) {
2114                         ngq->last = &(ngq->queue);
2115                         atomic_clear_long(&ngq->q_flags, OP_PENDING);
2116                 }
2117                 NG_QUEUE_UNLOCK(ngq);
2118
2119                 /* If the item is supplying a callback, call it with an error */
2120                 if (item->apply != NULL) {
2121                         if (item->depth == 1)
2122                                 item->apply->error = ENOENT;
2123                         if (refcount_release(&item->apply->refs)) {
2124                                 (*item->apply->apply)(item->apply->context,
2125                                     item->apply->error);
2126                         }
2127                 }
2128                 NG_FREE_ITEM(item);
2129                 NG_QUEUE_LOCK(ngq);
2130         }
2131         NG_QUEUE_UNLOCK(ngq);
2132 }
2133
2134 /***********************************************************************
2135 * Externally visible method for sending or queueing messages or data.
2136 ***********************************************************************/
2137
2138 /*
2139  * The module code should have filled out the item correctly by this stage:
2140  * Common:
2141  *    reference to destination node.
2142  *    Reference to destination rcv hook if relevant.
2143  *    apply pointer must be or NULL or reference valid struct ng_apply_info.
2144  * Data:
2145  *    pointer to mbuf
2146  * Control_Message:
2147  *    pointer to msg.
2148  *    ID of original sender node. (return address)
2149  * Function:
2150  *    Function pointer
2151  *    void * argument
2152  *    integer argument
2153  *
2154  * The nodes have several routines and macros to help with this task:
2155  */
2156
2157 int
2158 ng_snd_item(item_p item, int flags)
2159 {
2160         hook_p hook;
2161         node_p node;
2162         int queue, rw;
2163         struct ng_queue *ngq;
2164         int error = 0;
2165
2166         /* We are sending item, so it must be present! */
2167         KASSERT(item != NULL, ("ng_snd_item: item is NULL"));
2168
2169 #ifdef  NETGRAPH_DEBUG
2170         _ngi_check(item, __FILE__, __LINE__);
2171 #endif
2172
2173         /* Item was sent once more, postpone apply() call. */
2174         if (item->apply)
2175                 refcount_acquire(&item->apply->refs);
2176
2177         node = NGI_NODE(item);
2178         /* Node is never optional. */
2179         KASSERT(node != NULL, ("ng_snd_item: node is NULL"));
2180
2181         hook = NGI_HOOK(item);
2182         /* Valid hook and mbuf are mandatory for data. */
2183         if ((item->el_flags & NGQF_TYPE) == NGQF_DATA) {
2184                 KASSERT(hook != NULL, ("ng_snd_item: hook for data is NULL"));
2185                 if (NGI_M(item) == NULL)
2186                         ERROUT(EINVAL);
2187                 CHECK_DATA_MBUF(NGI_M(item));
2188         }
2189
2190         /*
2191          * If the item or the node specifies single threading, force
2192          * writer semantics. Similarly, the node may say one hook always
2193          * produces writers. These are overrides.
2194          */
2195         if (((item->el_flags & NGQF_RW) == NGQF_WRITER) ||
2196             (node->nd_flags & NGF_FORCE_WRITER) ||
2197             (hook && (hook->hk_flags & HK_FORCE_WRITER))) {
2198                 rw = NGQRW_W;
2199         } else {
2200                 rw = NGQRW_R;
2201         }
2202
2203         /*
2204          * If sender or receiver requests queued delivery or stack usage
2205          * level is dangerous - enqueue message.
2206          */
2207         if ((flags & NG_QUEUE) || (hook && (hook->hk_flags & HK_QUEUE))) {
2208                 queue = 1;
2209         } else {
2210                 queue = 0;
2211 #ifdef GET_STACK_USAGE
2212                 /*
2213                  * Most of netgraph nodes have small stack consumption and
2214                  * for them 25% of free stack space is more than enough.
2215                  * Nodes/hooks with higher stack usage should be marked as
2216                  * HI_STACK. For them 50% of stack will be guaranteed then.
2217                  * XXX: Values 25% and 50% are completely empirical.
2218                  */
2219                 size_t  st, su, sl;
2220                 GET_STACK_USAGE(st, su);
2221                 sl = st - su;
2222                 if ((sl * 4 < st) ||
2223                     ((sl * 2 < st) && ((node->nd_flags & NGF_HI_STACK) ||
2224                       (hook && (hook->hk_flags & HK_HI_STACK))))) {
2225                         queue = 1;
2226                 }
2227 #endif
2228         }
2229
2230         ngq = &node->nd_input_queue;
2231         if (queue) {
2232                 item->depth = 1;
2233                 /* Put it on the queue for that node*/
2234                 ng_queue_rw(ngq, item, rw);
2235                 return ((flags & NG_PROGRESS) ? EINPROGRESS : 0);
2236         }
2237
2238         /*
2239          * We already decided how we will be queueud or treated.
2240          * Try get the appropriate operating permission.
2241          */
2242         if (rw == NGQRW_R)
2243                 item = ng_acquire_read(ngq, item);
2244         else
2245                 item = ng_acquire_write(ngq, item);
2246
2247         /* Item was queued while trying to get permission. */
2248         if (item == NULL)
2249                 return ((flags & NG_PROGRESS) ? EINPROGRESS : 0);
2250
2251         NGI_GET_NODE(item, node); /* zaps stored node */
2252
2253         item->depth++;
2254         error = ng_apply_item(node, item, rw); /* drops r/w lock when done */
2255
2256         /* If something is waiting on queue and ready, schedule it. */
2257         if (QUEUE_ACTIVE(ngq)) {
2258                 NG_QUEUE_LOCK(ngq);
2259                 if (QUEUE_ACTIVE(ngq) && NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2260                         ng_worklist_add(ngq->q_node);
2261                 NG_QUEUE_UNLOCK(ngq);
2262         }
2263
2264         /*
2265          * Node may go away as soon as we remove the reference.
2266          * Whatever we do, DO NOT access the node again!
2267          */
2268         NG_NODE_UNREF(node);
2269
2270         return (error);
2271
2272 done:
2273         /* If was not sent, apply callback here. */
2274         if (item->apply != NULL) {
2275                 if (item->depth == 0 && error != 0)
2276                         item->apply->error = error;
2277                 if (refcount_release(&item->apply->refs)) {
2278                         (*item->apply->apply)(item->apply->context,
2279                             item->apply->error);
2280                 }
2281         }
2282
2283         NG_FREE_ITEM(item);
2284         return (error);
2285 }
2286
2287 /*
2288  * We have an item that was possibly queued somewhere.
2289  * It should contain all the information needed
2290  * to run it on the appropriate node/hook.
2291  * If there is apply pointer and we own the last reference, call apply().
2292  */
2293 static int
2294 ng_apply_item(node_p node, item_p item, int rw)
2295 {
2296         hook_p  hook;
2297         ng_rcvdata_t *rcvdata;
2298         ng_rcvmsg_t *rcvmsg;
2299         struct ng_apply_info *apply;
2300         int     error = 0, depth;
2301
2302         /* Node and item are never optional. */
2303         KASSERT(node != NULL, ("ng_apply_item: node is NULL"));
2304         KASSERT(item != NULL, ("ng_apply_item: item is NULL"));
2305
2306         NGI_GET_HOOK(item, hook); /* clears stored hook */
2307 #ifdef  NETGRAPH_DEBUG
2308         _ngi_check(item, __FILE__, __LINE__);
2309 #endif
2310
2311         apply = item->apply;
2312         depth = item->depth;
2313
2314         switch (item->el_flags & NGQF_TYPE) {
2315         case NGQF_DATA:
2316                 /*
2317                  * Check things are still ok as when we were queued.
2318                  */
2319                 KASSERT(hook != NULL, ("ng_apply_item: hook for data is NULL"));
2320                 if (NG_HOOK_NOT_VALID(hook) ||
2321                     NG_NODE_NOT_VALID(node)) {
2322                         error = EIO;
2323                         NG_FREE_ITEM(item);
2324                         break;
2325                 }
2326                 /*
2327                  * If no receive method, just silently drop it.
2328                  * Give preference to the hook over-ride method
2329                  */
2330                 if ((!(rcvdata = hook->hk_rcvdata))
2331                 && (!(rcvdata = NG_HOOK_NODE(hook)->nd_type->rcvdata))) {
2332                         error = 0;
2333                         NG_FREE_ITEM(item);
2334                         break;
2335                 }
2336                 error = (*rcvdata)(hook, item);
2337                 break;
2338         case NGQF_MESG:
2339                 if (hook && NG_HOOK_NOT_VALID(hook)) {
2340                         /*
2341                          * The hook has been zapped then we can't use it.
2342                          * Immediately drop its reference.
2343                          * The message may not need it.
2344                          */
2345                         NG_HOOK_UNREF(hook);
2346                         hook = NULL;
2347                 }
2348                 /*
2349                  * Similarly, if the node is a zombie there is
2350                  * nothing we can do with it, drop everything.
2351                  */
2352                 if (NG_NODE_NOT_VALID(node)) {
2353                         TRAP_ERROR();
2354                         error = EINVAL;
2355                         NG_FREE_ITEM(item);
2356                         break;
2357                 }
2358                 /*
2359                  * Call the appropriate message handler for the object.
2360                  * It is up to the message handler to free the message.
2361                  * If it's a generic message, handle it generically,
2362                  * otherwise call the type's message handler (if it exists).
2363                  * XXX (race). Remember that a queued message may
2364                  * reference a node or hook that has just been
2365                  * invalidated. It will exist as the queue code
2366                  * is holding a reference, but..
2367                  */
2368                 if ((NGI_MSG(item)->header.typecookie == NGM_GENERIC_COOKIE) &&
2369                     ((NGI_MSG(item)->header.flags & NGF_RESP) == 0)) {
2370                         error = ng_generic_msg(node, item, hook);
2371                         break;
2372                 }
2373                 if (((!hook) || (!(rcvmsg = hook->hk_rcvmsg))) &&
2374                     (!(rcvmsg = node->nd_type->rcvmsg))) {
2375                         TRAP_ERROR();
2376                         error = 0;
2377                         NG_FREE_ITEM(item);
2378                         break;
2379                 }
2380                 error = (*rcvmsg)(node, item, hook);
2381                 break;
2382         case NGQF_FN:
2383         case NGQF_FN2:
2384                 /*
2385                  * In the case of the shutdown message we allow it to hit
2386                  * even if the node is invalid.
2387                  */
2388                 if (NG_NODE_NOT_VALID(node) &&
2389                     NGI_FN(item) != &ng_rmnode) {
2390                         TRAP_ERROR();
2391                         error = EINVAL;
2392                         NG_FREE_ITEM(item);
2393                         break;
2394                 }
2395                 /* Same is about some internal functions and invalid hook. */
2396                 if (hook && NG_HOOK_NOT_VALID(hook) &&
2397                     NGI_FN2(item) != &ng_con_part2 &&
2398                     NGI_FN2(item) != &ng_con_part3 &&
2399                     NGI_FN(item) != &ng_rmhook_part2) {
2400                         TRAP_ERROR();
2401                         error = EINVAL;
2402                         NG_FREE_ITEM(item);
2403                         break;
2404                 }
2405                 
2406                 if ((item->el_flags & NGQF_TYPE) == NGQF_FN) {
2407                         (*NGI_FN(item))(node, hook, NGI_ARG1(item),
2408                             NGI_ARG2(item));
2409                         NG_FREE_ITEM(item);
2410                 } else  /* it is NGQF_FN2 */
2411                         error = (*NGI_FN2(item))(node, item, hook);
2412                 break;
2413         }
2414         /*
2415          * We held references on some of the resources
2416          * that we took from the item. Now that we have
2417          * finished doing everything, drop those references.
2418          */
2419         if (hook)
2420                 NG_HOOK_UNREF(hook);
2421
2422         if (rw == NGQRW_R)
2423                 ng_leave_read(&node->nd_input_queue);
2424         else
2425                 ng_leave_write(&node->nd_input_queue);
2426
2427         /* Apply callback. */
2428         if (apply != NULL) {
2429                 if (depth == 1 && error != 0)
2430                         apply->error = error;
2431                 if (refcount_release(&apply->refs))
2432                         (*apply->apply)(apply->context, apply->error);
2433         }
2434
2435         return (error);
2436 }
2437
2438 /***********************************************************************
2439  * Implement the 'generic' control messages
2440  ***********************************************************************/
2441 static int
2442 ng_generic_msg(node_p here, item_p item, hook_p lasthook)
2443 {
2444         int error = 0;
2445         struct ng_mesg *msg;
2446         struct ng_mesg *resp = NULL;
2447
2448         NGI_GET_MSG(item, msg);
2449         if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
2450                 TRAP_ERROR();
2451                 error = EINVAL;
2452                 goto out;
2453         }
2454         switch (msg->header.cmd) {
2455         case NGM_SHUTDOWN:
2456                 ng_rmnode(here, NULL, NULL, 0);
2457                 break;
2458         case NGM_MKPEER:
2459             {
2460                 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
2461
2462                 if (msg->header.arglen != sizeof(*mkp)) {
2463                         TRAP_ERROR();
2464                         error = EINVAL;
2465                         break;
2466                 }
2467                 mkp->type[sizeof(mkp->type) - 1] = '\0';
2468                 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
2469                 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
2470                 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
2471                 break;
2472             }
2473         case NGM_CONNECT:
2474             {
2475                 struct ngm_connect *const con =
2476                         (struct ngm_connect *) msg->data;
2477                 node_p node2;
2478
2479                 if (msg->header.arglen != sizeof(*con)) {
2480                         TRAP_ERROR();
2481                         error = EINVAL;
2482                         break;
2483                 }
2484                 con->path[sizeof(con->path) - 1] = '\0';
2485                 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
2486                 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
2487                 /* Don't forget we get a reference.. */
2488                 error = ng_path2noderef(here, con->path, &node2, NULL);
2489                 if (error)
2490                         break;
2491                 error = ng_con_nodes(item, here, con->ourhook,
2492                     node2, con->peerhook);
2493                 NG_NODE_UNREF(node2);
2494                 break;
2495             }
2496         case NGM_NAME:
2497             {
2498                 struct ngm_name *const nam = (struct ngm_name *) msg->data;
2499
2500                 if (msg->header.arglen != sizeof(*nam)) {
2501                         TRAP_ERROR();
2502                         error = EINVAL;
2503                         break;
2504                 }
2505                 nam->name[sizeof(nam->name) - 1] = '\0';
2506                 error = ng_name_node(here, nam->name);
2507                 break;
2508             }
2509         case NGM_RMHOOK:
2510             {
2511                 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
2512                 hook_p hook;
2513
2514                 if (msg->header.arglen != sizeof(*rmh)) {
2515                         TRAP_ERROR();
2516                         error = EINVAL;
2517                         break;
2518                 }
2519                 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
2520                 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
2521                         ng_destroy_hook(hook);
2522                 break;
2523             }
2524         case NGM_NODEINFO:
2525             {
2526                 struct nodeinfo *ni;
2527
2528                 NG_MKRESPONSE(resp, msg, sizeof(*ni), M_NOWAIT);
2529                 if (resp == NULL) {
2530                         error = ENOMEM;
2531                         break;
2532                 }
2533
2534                 /* Fill in node info */
2535                 ni = (struct nodeinfo *) resp->data;
2536                 if (NG_NODE_HAS_NAME(here))
2537                         strcpy(ni->name, NG_NODE_NAME(here));
2538                 strcpy(ni->type, here->nd_type->name);
2539                 ni->id = ng_node2ID(here);
2540                 ni->hooks = here->nd_numhooks;
2541                 break;
2542             }
2543         case NGM_LISTHOOKS:
2544             {
2545                 const int nhooks = here->nd_numhooks;
2546                 struct hooklist *hl;
2547                 struct nodeinfo *ni;
2548                 hook_p hook;
2549
2550                 /* Get response struct */
2551                 NG_MKRESPONSE(resp, msg, sizeof(*hl)
2552                     + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
2553                 if (resp == NULL) {
2554                         error = ENOMEM;
2555                         break;
2556                 }
2557                 hl = (struct hooklist *) resp->data;
2558                 ni = &hl->nodeinfo;
2559
2560                 /* Fill in node info */
2561                 if (NG_NODE_HAS_NAME(here))
2562                         strcpy(ni->name, NG_NODE_NAME(here));
2563                 strcpy(ni->type, here->nd_type->name);
2564                 ni->id = ng_node2ID(here);
2565
2566                 /* Cycle through the linked list of hooks */
2567                 ni->hooks = 0;
2568                 LIST_FOREACH(hook, &here->nd_hooks, hk_hooks) {
2569                         struct linkinfo *const link = &hl->link[ni->hooks];
2570
2571                         if (ni->hooks >= nhooks) {
2572                                 log(LOG_ERR, "%s: number of %s changed\n",
2573                                     __func__, "hooks");
2574                                 break;
2575                         }
2576                         if (NG_HOOK_NOT_VALID(hook))
2577                                 continue;
2578                         strcpy(link->ourhook, NG_HOOK_NAME(hook));
2579                         strcpy(link->peerhook, NG_PEER_HOOK_NAME(hook));
2580                         if (NG_PEER_NODE_NAME(hook)[0] != '\0')
2581                                 strcpy(link->nodeinfo.name,
2582                                     NG_PEER_NODE_NAME(hook));
2583                         strcpy(link->nodeinfo.type,
2584                            NG_PEER_NODE(hook)->nd_type->name);
2585                         link->nodeinfo.id = ng_node2ID(NG_PEER_NODE(hook));
2586                         link->nodeinfo.hooks = NG_PEER_NODE(hook)->nd_numhooks;
2587                         ni->hooks++;
2588                 }
2589                 break;
2590             }
2591
2592         case NGM_LISTNAMES:
2593         case NGM_LISTNODES:
2594             {
2595                 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
2596                 struct namelist *nl;
2597                 node_p node;
2598                 int num = 0, i;
2599
2600                 mtx_lock(&ng_namehash_mtx);
2601                 /* Count number of nodes */
2602                 for (i = 0; i < NG_NAME_HASH_SIZE; i++) {
2603                         LIST_FOREACH(node, &ng_name_hash[i], nd_nodes) {
2604                                 if (NG_NODE_IS_VALID(node) &&
2605                                     (unnamed || NG_NODE_HAS_NAME(node))) {
2606                                         num++;
2607                                 }
2608                         }
2609                 }
2610                 mtx_unlock(&ng_namehash_mtx);
2611
2612                 /* Get response struct */
2613                 NG_MKRESPONSE(resp, msg, sizeof(*nl)
2614                     + (num * sizeof(struct nodeinfo)), M_NOWAIT);
2615                 if (resp == NULL) {
2616                         error = ENOMEM;
2617                         break;
2618                 }
2619                 nl = (struct namelist *) resp->data;
2620
2621                 /* Cycle through the linked list of nodes */
2622                 nl->numnames = 0;
2623                 mtx_lock(&ng_namehash_mtx);
2624                 for (i = 0; i < NG_NAME_HASH_SIZE; i++) {
2625                         LIST_FOREACH(node, &ng_name_hash[i], nd_nodes) {
2626                                 struct nodeinfo *const np =
2627                                     &nl->nodeinfo[nl->numnames];
2628
2629                                 if (NG_NODE_NOT_VALID(node))
2630                                         continue;
2631                                 if (!unnamed && (! NG_NODE_HAS_NAME(node)))
2632                                         continue;
2633                                 if (nl->numnames >= num) {
2634                                         log(LOG_ERR, "%s: number of nodes changed\n",
2635                                             __func__);
2636                                         break;
2637                                 }
2638                                 if (NG_NODE_HAS_NAME(node))
2639                                         strcpy(np->name, NG_NODE_NAME(node));
2640                                 strcpy(np->type, node->nd_type->name);
2641                                 np->id = ng_node2ID(node);
2642                                 np->hooks = node->nd_numhooks;
2643                                 nl->numnames++;
2644                         }
2645                 }
2646                 mtx_unlock(&ng_namehash_mtx);
2647                 break;
2648             }
2649
2650         case NGM_LISTTYPES:
2651             {
2652                 struct typelist *tl;
2653                 struct ng_type *type;
2654                 int num = 0;
2655
2656                 mtx_lock(&ng_typelist_mtx);
2657                 /* Count number of types */
2658                 LIST_FOREACH(type, &ng_typelist, types) {
2659                         num++;
2660                 }
2661                 mtx_unlock(&ng_typelist_mtx);
2662
2663                 /* Get response struct */
2664                 NG_MKRESPONSE(resp, msg, sizeof(*tl)
2665                     + (num * sizeof(struct typeinfo)), M_NOWAIT);
2666                 if (resp == NULL) {
2667                         error = ENOMEM;
2668                         break;
2669                 }
2670                 tl = (struct typelist *) resp->data;
2671
2672                 /* Cycle through the linked list of types */
2673                 tl->numtypes = 0;
2674                 mtx_lock(&ng_typelist_mtx);
2675                 LIST_FOREACH(type, &ng_typelist, types) {
2676                         struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
2677
2678                         if (tl->numtypes >= num) {
2679                                 log(LOG_ERR, "%s: number of %s changed\n",
2680                                     __func__, "types");
2681                                 break;
2682                         }
2683                         strcpy(tp->type_name, type->name);
2684                         tp->numnodes = type->refs - 1; /* don't count list */
2685                         tl->numtypes++;
2686                 }
2687                 mtx_unlock(&ng_typelist_mtx);
2688                 break;
2689             }
2690
2691         case NGM_BINARY2ASCII:
2692             {
2693                 int bufSize = 20 * 1024;        /* XXX hard coded constant */
2694                 const struct ng_parse_type *argstype;
2695                 const struct ng_cmdlist *c;
2696                 struct ng_mesg *binary, *ascii;
2697
2698                 /* Data area must contain a valid netgraph message */
2699                 binary = (struct ng_mesg *)msg->data;
2700                 if (msg->header.arglen < sizeof(struct ng_mesg) ||
2701                     (msg->header.arglen - sizeof(struct ng_mesg) <
2702                     binary->header.arglen)) {
2703                         TRAP_ERROR();
2704                         error = EINVAL;
2705                         break;
2706                 }
2707
2708                 /* Get a response message with lots of room */
2709                 NG_MKRESPONSE(resp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
2710                 if (resp == NULL) {
2711                         error = ENOMEM;
2712                         break;
2713                 }
2714                 ascii = (struct ng_mesg *)resp->data;
2715
2716                 /* Copy binary message header to response message payload */
2717                 bcopy(binary, ascii, sizeof(*binary));
2718
2719                 /* Find command by matching typecookie and command number */
2720                 for (c = here->nd_type->cmdlist;
2721                     c != NULL && c->name != NULL; c++) {
2722                         if (binary->header.typecookie == c->cookie
2723                             && binary->header.cmd == c->cmd)
2724                                 break;
2725                 }
2726                 if (c == NULL || c->name == NULL) {
2727                         for (c = ng_generic_cmds; c->name != NULL; c++) {
2728                                 if (binary->header.typecookie == c->cookie
2729                                     && binary->header.cmd == c->cmd)
2730                                         break;
2731                         }
2732                         if (c->name == NULL) {
2733                                 NG_FREE_MSG(resp);
2734                                 error = ENOSYS;
2735                                 break;
2736                         }
2737                 }
2738
2739                 /* Convert command name to ASCII */
2740                 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
2741                     "%s", c->name);
2742
2743                 /* Convert command arguments to ASCII */
2744                 argstype = (binary->header.flags & NGF_RESP) ?
2745                     c->respType : c->mesgType;
2746                 if (argstype == NULL) {
2747                         *ascii->data = '\0';
2748                 } else {
2749                         if ((error = ng_unparse(argstype,
2750                             (u_char *)binary->data,
2751                             ascii->data, bufSize)) != 0) {
2752                                 NG_FREE_MSG(resp);
2753                                 break;
2754                         }
2755                 }
2756
2757                 /* Return the result as struct ng_mesg plus ASCII string */
2758                 bufSize = strlen(ascii->data) + 1;
2759                 ascii->header.arglen = bufSize;
2760                 resp->header.arglen = sizeof(*ascii) + bufSize;
2761                 break;
2762             }
2763
2764         case NGM_ASCII2BINARY:
2765             {
2766                 int bufSize = 2000;     /* XXX hard coded constant */
2767                 const struct ng_cmdlist *c;
2768                 const struct ng_parse_type *argstype;
2769                 struct ng_mesg *ascii, *binary;
2770                 int off = 0;
2771
2772                 /* Data area must contain at least a struct ng_mesg + '\0' */
2773                 ascii = (struct ng_mesg *)msg->data;
2774                 if ((msg->header.arglen < sizeof(*ascii) + 1) ||
2775                     (ascii->header.arglen < 1) ||
2776                     (msg->header.arglen < sizeof(*ascii) +
2777                     ascii->header.arglen)) {
2778                         TRAP_ERROR();
2779                         error = EINVAL;
2780                         break;
2781                 }
2782                 ascii->data[ascii->header.arglen - 1] = '\0';
2783
2784                 /* Get a response message with lots of room */
2785                 NG_MKRESPONSE(resp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
2786                 if (resp == NULL) {
2787                         error = ENOMEM;
2788                         break;
2789                 }
2790                 binary = (struct ng_mesg *)resp->data;
2791
2792                 /* Copy ASCII message header to response message payload */
2793                 bcopy(ascii, binary, sizeof(*ascii));
2794
2795                 /* Find command by matching ASCII command string */
2796                 for (c = here->nd_type->cmdlist;
2797                     c != NULL && c->name != NULL; c++) {
2798                         if (strcmp(ascii->header.cmdstr, c->name) == 0)
2799                                 break;
2800                 }
2801                 if (c == NULL || c->name == NULL) {
2802                         for (c = ng_generic_cmds; c->name != NULL; c++) {
2803                                 if (strcmp(ascii->header.cmdstr, c->name) == 0)
2804                                         break;
2805                         }
2806                         if (c->name == NULL) {
2807                                 NG_FREE_MSG(resp);
2808                                 error = ENOSYS;
2809                                 break;
2810                         }
2811                 }
2812
2813                 /* Convert command name to binary */
2814                 binary->header.cmd = c->cmd;
2815                 binary->header.typecookie = c->cookie;
2816
2817                 /* Convert command arguments to binary */
2818                 argstype = (binary->header.flags & NGF_RESP) ?
2819                     c->respType : c->mesgType;
2820                 if (argstype == NULL) {
2821                         bufSize = 0;
2822                 } else {
2823                         if ((error = ng_parse(argstype, ascii->data,
2824                             &off, (u_char *)binary->data, &bufSize)) != 0) {
2825                                 NG_FREE_MSG(resp);
2826                                 break;
2827                         }
2828                 }
2829
2830                 /* Return the result */
2831                 binary->header.arglen = bufSize;
2832                 resp->header.arglen = sizeof(*binary) + bufSize;
2833                 break;
2834             }
2835
2836         case NGM_TEXT_CONFIG:
2837         case NGM_TEXT_STATUS:
2838                 /*
2839                  * This one is tricky as it passes the command down to the
2840                  * actual node, even though it is a generic type command.
2841                  * This means we must assume that the item/msg is already freed
2842                  * when control passes back to us.
2843                  */
2844                 if (here->nd_type->rcvmsg != NULL) {
2845                         NGI_MSG(item) = msg; /* put it back as we found it */
2846                         return((*here->nd_type->rcvmsg)(here, item, lasthook));
2847                 }
2848                 /* Fall through if rcvmsg not supported */
2849         default:
2850                 TRAP_ERROR();
2851                 error = EINVAL;
2852         }
2853         /*
2854          * Sometimes a generic message may be statically allocated
2855          * to avoid problems with allocating when in tight memeory situations.
2856          * Don't free it if it is so.
2857          * I break them appart here, because erros may cause a free if the item
2858          * in which case we'd be doing it twice.
2859          * they are kept together above, to simplify freeing.
2860          */
2861 out:
2862         NG_RESPOND_MSG(error, here, item, resp);
2863         NG_FREE_MSG(msg);
2864         return (error);
2865 }
2866
2867 /************************************************************************
2868                         Queue element get/free routines
2869 ************************************************************************/
2870
2871 uma_zone_t                      ng_qzone;
2872 uma_zone_t                      ng_qdzone;
2873 static int                      numthreads = 0; /* number of queue threads */
2874 static int                      maxalloc = 4096;/* limit the damage of a leak */
2875 static int                      maxdata = 512;  /* limit the damage of a DoS */
2876
2877 TUNABLE_INT("net.graph.threads", &numthreads);
2878 SYSCTL_INT(_net_graph, OID_AUTO, threads, CTLFLAG_RDTUN, &numthreads,
2879     0, "Number of queue processing threads to create");
2880 TUNABLE_INT("net.graph.maxalloc", &maxalloc);
2881 SYSCTL_INT(_net_graph, OID_AUTO, maxalloc, CTLFLAG_RDTUN, &maxalloc,
2882     0, "Maximum number of non-data queue items to allocate");
2883 TUNABLE_INT("net.graph.maxdata", &maxdata);
2884 SYSCTL_INT(_net_graph, OID_AUTO, maxdata, CTLFLAG_RDTUN, &maxdata,
2885     0, "Maximum number of data queue items to allocate");
2886
2887 #ifdef  NETGRAPH_DEBUG
2888 static TAILQ_HEAD(, ng_item) ng_itemlist = TAILQ_HEAD_INITIALIZER(ng_itemlist);
2889 static int                      allocated;      /* number of items malloc'd */
2890 #endif
2891
2892 /*
2893  * Get a queue entry.
2894  * This is usually called when a packet first enters netgraph.
2895  * By definition, this is usually from an interrupt, or from a user.
2896  * Users are not so important, but try be quick for the times that it's
2897  * an interrupt.
2898  */
2899 static __inline item_p
2900 ng_alloc_item(int type, int flags)
2901 {
2902         item_p item;
2903
2904         KASSERT(((type & ~NGQF_TYPE) == 0),
2905             ("%s: incorrect item type: %d", __func__, type));
2906
2907         item = uma_zalloc((type == NGQF_DATA)?ng_qdzone:ng_qzone,
2908             ((flags & NG_WAITOK) ? M_WAITOK : M_NOWAIT) | M_ZERO);
2909
2910         if (item) {
2911                 item->el_flags = type;
2912 #ifdef  NETGRAPH_DEBUG
2913                 mtx_lock(&ngq_mtx);
2914                 TAILQ_INSERT_TAIL(&ng_itemlist, item, all);
2915                 allocated++;
2916                 mtx_unlock(&ngq_mtx);
2917 #endif
2918         }
2919
2920         return (item);
2921 }
2922
2923 /*
2924  * Release a queue entry
2925  */
2926 void
2927 ng_free_item(item_p item)
2928 {
2929         /*
2930          * The item may hold resources on it's own. We need to free
2931          * these before we can free the item. What they are depends upon
2932          * what kind of item it is. it is important that nodes zero
2933          * out pointers to resources that they remove from the item
2934          * or we release them again here.
2935          */
2936         switch (item->el_flags & NGQF_TYPE) {
2937         case NGQF_DATA:
2938                 /* If we have an mbuf still attached.. */
2939                 NG_FREE_M(_NGI_M(item));
2940                 break;
2941         case NGQF_MESG:
2942                 _NGI_RETADDR(item) = 0;
2943                 NG_FREE_MSG(_NGI_MSG(item));
2944                 break;
2945         case NGQF_FN:
2946         case NGQF_FN2:
2947                 /* nothing to free really, */
2948                 _NGI_FN(item) = NULL;
2949                 _NGI_ARG1(item) = NULL;
2950                 _NGI_ARG2(item) = 0;
2951                 break;
2952         }
2953         /* If we still have a node or hook referenced... */
2954         _NGI_CLR_NODE(item);
2955         _NGI_CLR_HOOK(item);
2956
2957 #ifdef  NETGRAPH_DEBUG
2958         mtx_lock(&ngq_mtx);
2959         TAILQ_REMOVE(&ng_itemlist, item, all);
2960         allocated--;
2961         mtx_unlock(&ngq_mtx);
2962 #endif
2963         uma_zfree(((item->el_flags & NGQF_TYPE) == NGQF_DATA)?
2964             ng_qdzone:ng_qzone, item);
2965 }
2966
2967 /*
2968  * Change type of the queue entry.
2969  * Possibly reallocates it from another UMA zone.
2970  */
2971 static __inline item_p
2972 ng_realloc_item(item_p pitem, int type, int flags)
2973 {
2974         item_p item;
2975         int from, to;
2976
2977         KASSERT((pitem != NULL), ("%s: can't reallocate NULL", __func__));
2978         KASSERT(((type & ~NGQF_TYPE) == 0),
2979             ("%s: incorrect item type: %d", __func__, type));
2980
2981         from = ((pitem->el_flags & NGQF_TYPE) == NGQF_DATA);
2982         to = (type == NGQF_DATA);
2983         if (from != to) {
2984                 /* If reallocation is required do it and copy item. */
2985                 if ((item = ng_alloc_item(type, flags)) == NULL) {
2986                         ng_free_item(pitem);
2987                         return (NULL);
2988                 }
2989                 *item = *pitem;
2990                 ng_free_item(pitem);
2991         } else
2992                 item = pitem;
2993         item->el_flags = (item->el_flags & ~NGQF_TYPE) | type;
2994
2995         return (item);
2996 }
2997
2998 /************************************************************************
2999                         Module routines
3000 ************************************************************************/
3001
3002 /*
3003  * Handle the loading/unloading of a netgraph node type module
3004  */
3005 int
3006 ng_mod_event(module_t mod, int event, void *data)
3007 {
3008         struct ng_type *const type = data;
3009         int s, error = 0;
3010
3011         switch (event) {
3012         case MOD_LOAD:
3013
3014                 /* Register new netgraph node type */
3015                 s = splnet();
3016                 if ((error = ng_newtype(type)) != 0) {
3017                         splx(s);
3018                         break;
3019                 }
3020
3021                 /* Call type specific code */
3022                 if (type->mod_event != NULL)
3023                         if ((error = (*type->mod_event)(mod, event, data))) {
3024                                 mtx_lock(&ng_typelist_mtx);
3025                                 type->refs--;   /* undo it */
3026                                 LIST_REMOVE(type, types);
3027                                 mtx_unlock(&ng_typelist_mtx);
3028                         }
3029                 splx(s);
3030                 break;
3031
3032         case MOD_UNLOAD:
3033                 s = splnet();
3034                 if (type->refs > 1) {           /* make sure no nodes exist! */
3035                         error = EBUSY;
3036                 } else {
3037                         if (type->refs == 0) {
3038                                 /* failed load, nothing to undo */
3039                                 splx(s);
3040                                 break;
3041                         }
3042                         if (type->mod_event != NULL) {  /* check with type */
3043                                 error = (*type->mod_event)(mod, event, data);
3044                                 if (error != 0) {       /* type refuses.. */
3045                                         splx(s);
3046                                         break;
3047                                 }
3048                         }
3049                         mtx_lock(&ng_typelist_mtx);
3050                         LIST_REMOVE(type, types);
3051                         mtx_unlock(&ng_typelist_mtx);
3052                 }
3053                 splx(s);
3054                 break;
3055
3056         default:
3057                 if (type->mod_event != NULL)
3058                         error = (*type->mod_event)(mod, event, data);
3059                 else
3060                         error = EOPNOTSUPP;             /* XXX ? */
3061                 break;
3062         }
3063         return (error);
3064 }
3065
3066 /*
3067  * Handle loading and unloading for this code.
3068  * The only thing we need to link into is the NETISR strucure.
3069  */
3070 static int
3071 ngb_mod_event(module_t mod, int event, void *data)
3072 {
3073         int i, error = 0;
3074
3075         switch (event) {
3076         case MOD_LOAD:
3077                 /* Initialize everything. */
3078                 NG_WORKLIST_LOCK_INIT();
3079                 mtx_init(&ng_typelist_mtx, "netgraph types mutex", NULL,
3080                     MTX_DEF);
3081                 mtx_init(&ng_idhash_mtx, "netgraph idhash mutex", NULL,
3082                     MTX_DEF);
3083                 mtx_init(&ng_namehash_mtx, "netgraph namehash mutex", NULL,
3084                     MTX_DEF);
3085                 mtx_init(&ng_topo_mtx, "netgraph topology mutex", NULL,
3086                     MTX_DEF);
3087 #ifdef  NETGRAPH_DEBUG
3088                 mtx_init(&ng_nodelist_mtx, "netgraph nodelist mutex", NULL,
3089                     MTX_DEF);
3090                 mtx_init(&ngq_mtx, "netgraph item list mutex", NULL,
3091                     MTX_DEF);
3092 #endif
3093                 ng_qzone = uma_zcreate("NetGraph items", sizeof(struct ng_item),
3094                     NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
3095                 uma_zone_set_max(ng_qzone, maxalloc);
3096                 ng_qdzone = uma_zcreate("NetGraph data items", sizeof(struct ng_item),
3097                     NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
3098                 uma_zone_set_max(ng_qdzone, maxdata);
3099                 /* Autoconfigure number of threads. */
3100                 if (numthreads <= 0)
3101                         numthreads = mp_ncpus;
3102                 /* Create threads. */
3103                 for (i = 0; i < numthreads; i++) {
3104                         if (kthread_create(ngthread, NULL, NULL,
3105                             0, 0, "ng_queue%d", i)) {
3106                                 numthreads = i - 1;
3107                                 break;
3108                         }
3109                 }
3110                 break;
3111         case MOD_UNLOAD:
3112                 /* You can't unload it because an interface may be using it. */
3113                 error = EBUSY;
3114                 break;
3115         default:
3116                 error = EOPNOTSUPP;
3117                 break;
3118         }
3119         return (error);
3120 }
3121
3122 static moduledata_t netgraph_mod = {
3123         "netgraph",
3124         ngb_mod_event,
3125         (NULL)
3126 };
3127 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_NETGRAPH, SI_ORDER_MIDDLE);
3128 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
3129 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
3130 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
3131
3132 #ifdef  NETGRAPH_DEBUG
3133 void
3134 dumphook (hook_p hook, char *file, int line)
3135 {
3136         printf("hook: name %s, %d refs, Last touched:\n",
3137                 _NG_HOOK_NAME(hook), hook->hk_refs);
3138         printf("        Last active @ %s, line %d\n",
3139                 hook->lastfile, hook->lastline);
3140         if (line) {
3141                 printf(" problem discovered at file %s, line %d\n", file, line);
3142         }
3143 }
3144
3145 void
3146 dumpnode(node_p node, char *file, int line)
3147 {
3148         printf("node: ID [%x]: type '%s', %d hooks, flags 0x%x, %d refs, %s:\n",
3149                 _NG_NODE_ID(node), node->nd_type->name,
3150                 node->nd_numhooks, node->nd_flags,
3151                 node->nd_refs, node->nd_name);
3152         printf("        Last active @ %s, line %d\n",
3153                 node->lastfile, node->lastline);
3154         if (line) {
3155                 printf(" problem discovered at file %s, line %d\n", file, line);
3156         }
3157 }
3158
3159 void
3160 dumpitem(item_p item, char *file, int line)
3161 {
3162         printf(" ACTIVE item, last used at %s, line %d",
3163                 item->lastfile, item->lastline);
3164         switch(item->el_flags & NGQF_TYPE) {
3165         case NGQF_DATA:
3166                 printf(" - [data]\n");
3167                 break;
3168         case NGQF_MESG:
3169                 printf(" - retaddr[%d]:\n", _NGI_RETADDR(item));
3170                 break;
3171         case NGQF_FN:
3172                 printf(" - fn@%p (%p, %p, %p, %d (%x))\n",
3173                         _NGI_FN(item),
3174                         _NGI_NODE(item),
3175                         _NGI_HOOK(item),
3176                         item->body.fn.fn_arg1,
3177                         item->body.fn.fn_arg2,
3178                         item->body.fn.fn_arg2);
3179                 break;
3180         case NGQF_FN2:
3181                 printf(" - fn2@%p (%p, %p, %p, %d (%x))\n",
3182                         _NGI_FN2(item),
3183                         _NGI_NODE(item),
3184                         _NGI_HOOK(item),
3185                         item->body.fn.fn_arg1,
3186                         item->body.fn.fn_arg2,
3187                         item->body.fn.fn_arg2);
3188                 break;
3189         }
3190         if (line) {
3191                 printf(" problem discovered at file %s, line %d\n", file, line);
3192                 if (_NGI_NODE(item)) {
3193                         printf("node %p ([%x])\n",
3194                                 _NGI_NODE(item), ng_node2ID(_NGI_NODE(item)));
3195                 }
3196         }
3197 }
3198
3199 static void
3200 ng_dumpitems(void)
3201 {
3202         item_p item;
3203         int i = 1;
3204         TAILQ_FOREACH(item, &ng_itemlist, all) {
3205                 printf("[%d] ", i++);
3206                 dumpitem(item, NULL, 0);
3207         }
3208 }
3209
3210 static void
3211 ng_dumpnodes(void)
3212 {
3213         node_p node;
3214         int i = 1;
3215         mtx_lock(&ng_nodelist_mtx);
3216         SLIST_FOREACH(node, &ng_allnodes, nd_all) {
3217                 printf("[%d] ", i++);
3218                 dumpnode(node, NULL, 0);
3219         }
3220         mtx_unlock(&ng_nodelist_mtx);
3221 }
3222
3223 static void
3224 ng_dumphooks(void)
3225 {
3226         hook_p hook;
3227         int i = 1;
3228         mtx_lock(&ng_nodelist_mtx);
3229         SLIST_FOREACH(hook, &ng_allhooks, hk_all) {
3230                 printf("[%d] ", i++);
3231                 dumphook(hook, NULL, 0);
3232         }
3233         mtx_unlock(&ng_nodelist_mtx);
3234 }
3235
3236 static int
3237 sysctl_debug_ng_dump_items(SYSCTL_HANDLER_ARGS)
3238 {
3239         int error;
3240         int val;
3241         int i;
3242
3243         val = allocated;
3244         i = 1;
3245         error = sysctl_handle_int(oidp, &val, 0, req);
3246         if (error != 0 || req->newptr == NULL)
3247                 return (error);
3248         if (val == 42) {
3249                 ng_dumpitems();
3250                 ng_dumpnodes();
3251                 ng_dumphooks();
3252         }
3253         return (0);
3254 }
3255
3256 SYSCTL_PROC(_debug, OID_AUTO, ng_dump_items, CTLTYPE_INT | CTLFLAG_RW,
3257     0, sizeof(int), sysctl_debug_ng_dump_items, "I", "Number of allocated items");
3258 #endif  /* NETGRAPH_DEBUG */
3259
3260
3261 /***********************************************************************
3262 * Worklist routines
3263 **********************************************************************/
3264 /*
3265  * Pick a node off the list of nodes with work,
3266  * try get an item to process off it. Remove the node from the list.
3267  */
3268 static void
3269 ngthread(void *arg)
3270 {
3271         for (;;) {
3272                 node_p  node;
3273
3274                 /* Get node from the worklist. */
3275                 NG_WORKLIST_LOCK();
3276                 while ((node = TAILQ_FIRST(&ng_worklist)) == NULL)
3277                         NG_WORKLIST_SLEEP();
3278                 TAILQ_REMOVE(&ng_worklist, node, nd_work);
3279                 NG_WORKLIST_UNLOCK();
3280                 CTR3(KTR_NET, "%20s: node [%x] (%p) taken off worklist",
3281                     __func__, node->nd_ID, node);
3282                 /*
3283                  * We have the node. We also take over the reference
3284                  * that the list had on it.
3285                  * Now process as much as you can, until it won't
3286                  * let you have another item off the queue.
3287                  * All this time, keep the reference
3288                  * that lets us be sure that the node still exists.
3289                  * Let the reference go at the last minute.
3290                  */
3291                 for (;;) {
3292                         item_p item;
3293                         int rw;
3294
3295                         NG_QUEUE_LOCK(&node->nd_input_queue);
3296                         item = ng_dequeue(&node->nd_input_queue, &rw);
3297                         if (item == NULL) {
3298                                 atomic_clear_int(&node->nd_flags, NGF_WORKQ);
3299                                 NG_QUEUE_UNLOCK(&node->nd_input_queue);
3300                                 break; /* go look for another node */
3301                         } else {
3302                                 NG_QUEUE_UNLOCK(&node->nd_input_queue);
3303                                 NGI_GET_NODE(item, node); /* zaps stored node */
3304                                 ng_apply_item(node, item, rw);
3305                                 NG_NODE_UNREF(node);
3306                         }
3307                 }
3308                 NG_NODE_UNREF(node);
3309         }
3310 }
3311
3312 /*
3313  * XXX
3314  * It's posible that a debugging NG_NODE_REF may need
3315  * to be outside the mutex zone
3316  */
3317 static void
3318 ng_worklist_add(node_p node)
3319 {
3320
3321         mtx_assert(&node->nd_input_queue.q_mtx, MA_OWNED);
3322
3323         if ((node->nd_flags & NGF_WORKQ) == 0) {
3324                 /*
3325                  * If we are not already on the work queue,
3326                  * then put us on.
3327                  */
3328                 atomic_set_int(&node->nd_flags, NGF_WORKQ);
3329                 NG_NODE_REF(node); /* XXX fafe in mutex? */
3330                 NG_WORKLIST_LOCK();
3331                 TAILQ_INSERT_TAIL(&ng_worklist, node, nd_work);
3332                 NG_WORKLIST_UNLOCK();
3333                 CTR3(KTR_NET, "%20s: node [%x] (%p) put on worklist", __func__,
3334                     node->nd_ID, node);
3335                 NG_WORKLIST_WAKEUP();
3336         } else {
3337                 CTR3(KTR_NET, "%20s: node [%x] (%p) already on worklist",
3338                     __func__, node->nd_ID, node);
3339         }
3340 }
3341
3342
3343 /***********************************************************************
3344 * Externally useable functions to set up a queue item ready for sending
3345 ***********************************************************************/
3346
3347 #ifdef  NETGRAPH_DEBUG
3348 #define ITEM_DEBUG_CHECKS                                               \
3349         do {                                                            \
3350                 if (NGI_NODE(item) ) {                                  \
3351                         printf("item already has node");                \
3352                         kdb_enter_why(KDB_WHY_NETGRAPH, "has node");    \
3353                         NGI_CLR_NODE(item);                             \
3354                 }                                                       \
3355                 if (NGI_HOOK(item) ) {                                  \
3356                         printf("item already has hook");                \
3357                         kdb_enter_why(KDB_WHY_NETGRAPH, "has hook");    \
3358                         NGI_CLR_HOOK(item);                             \
3359                 }                                                       \
3360         } while (0)
3361 #else
3362 #define ITEM_DEBUG_CHECKS
3363 #endif
3364
3365 /*
3366  * Put mbuf into the item.
3367  * Hook and node references will be removed when the item is dequeued.
3368  * (or equivalent)
3369  * (XXX) Unsafe because no reference held by peer on remote node.
3370  * remote node might go away in this timescale.
3371  * We know the hooks can't go away because that would require getting
3372  * a writer item on both nodes and we must have at least a  reader
3373  * here to be able to do this.
3374  * Note that the hook loaded is the REMOTE hook.
3375  *
3376  * This is possibly in the critical path for new data.
3377  */
3378 item_p
3379 ng_package_data(struct mbuf *m, int flags)
3380 {
3381         item_p item;
3382
3383         if ((item = ng_alloc_item(NGQF_DATA, flags)) == NULL) {
3384                 NG_FREE_M(m);
3385                 return (NULL);
3386         }
3387         ITEM_DEBUG_CHECKS;
3388         item->el_flags |= NGQF_READER;
3389         NGI_M(item) = m;
3390         return (item);
3391 }
3392
3393 /*
3394  * Allocate a queue item and put items into it..
3395  * Evaluate the address as this will be needed to queue it and
3396  * to work out what some of the fields should be.
3397  * Hook and node references will be removed when the item is dequeued.
3398  * (or equivalent)
3399  */
3400 item_p
3401 ng_package_msg(struct ng_mesg *msg, int flags)
3402 {
3403         item_p item;
3404
3405         if ((item = ng_alloc_item(NGQF_MESG, flags)) == NULL) {
3406                 NG_FREE_MSG(msg);
3407                 return (NULL);
3408         }
3409         ITEM_DEBUG_CHECKS;
3410         /* Messages items count as writers unless explicitly exempted. */
3411         if (msg->header.cmd & NGM_READONLY)
3412                 item->el_flags |= NGQF_READER;
3413         else
3414                 item->el_flags |= NGQF_WRITER;
3415         /*
3416          * Set the current lasthook into the queue item
3417          */
3418         NGI_MSG(item) = msg;
3419         NGI_RETADDR(item) = 0;
3420         return (item);
3421 }
3422
3423
3424
3425 #define SET_RETADDR(item, here, retaddr)                                \
3426         do {    /* Data or fn items don't have retaddrs */              \
3427                 if ((item->el_flags & NGQF_TYPE) == NGQF_MESG) {        \
3428                         if (retaddr) {                                  \
3429                                 NGI_RETADDR(item) = retaddr;            \
3430                         } else {                                        \
3431                                 /*                                      \
3432                                  * The old return address should be ok. \
3433                                  * If there isn't one, use the address  \
3434                                  * here.                                \
3435                                  */                                     \
3436                                 if (NGI_RETADDR(item) == 0) {           \
3437                                         NGI_RETADDR(item)               \
3438                                                 = ng_node2ID(here);     \
3439                                 }                                       \
3440                         }                                               \
3441                 }                                                       \
3442         } while (0)
3443
3444 int
3445 ng_address_hook(node_p here, item_p item, hook_p hook, ng_ID_t retaddr)
3446 {
3447         hook_p peer;
3448         node_p peernode;
3449         ITEM_DEBUG_CHECKS;
3450         /*
3451          * Quick sanity check..
3452          * Since a hook holds a reference on it's node, once we know
3453          * that the peer is still connected (even if invalid,) we know
3454          * that the peer node is present, though maybe invalid.
3455          */
3456         if ((hook == NULL) ||
3457             NG_HOOK_NOT_VALID(hook) ||
3458             NG_HOOK_NOT_VALID(peer = NG_HOOK_PEER(hook)) ||
3459             NG_NODE_NOT_VALID(peernode = NG_PEER_NODE(hook))) {
3460                 NG_FREE_ITEM(item);
3461                 TRAP_ERROR();
3462                 return (ENETDOWN);
3463         }
3464
3465         /*
3466          * Transfer our interest to the other (peer) end.
3467          */
3468         NG_HOOK_REF(peer);
3469         NG_NODE_REF(peernode);
3470         NGI_SET_HOOK(item, peer);
3471         NGI_SET_NODE(item, peernode);
3472         SET_RETADDR(item, here, retaddr);
3473         return (0);
3474 }
3475
3476 int
3477 ng_address_path(node_p here, item_p item, char *address, ng_ID_t retaddr)
3478 {
3479         node_p  dest = NULL;
3480         hook_p  hook = NULL;
3481         int     error;
3482
3483         ITEM_DEBUG_CHECKS;
3484         /*
3485          * Note that ng_path2noderef increments the reference count
3486          * on the node for us if it finds one. So we don't have to.
3487          */
3488         error = ng_path2noderef(here, address, &dest, &hook);
3489         if (error) {
3490                 NG_FREE_ITEM(item);
3491                 return (error);
3492         }
3493         NGI_SET_NODE(item, dest);
3494         if ( hook) {
3495                 NG_HOOK_REF(hook);      /* don't let it go while on the queue */
3496                 NGI_SET_HOOK(item, hook);
3497         }
3498         SET_RETADDR(item, here, retaddr);
3499         return (0);
3500 }
3501
3502 int
3503 ng_address_ID(node_p here, item_p item, ng_ID_t ID, ng_ID_t retaddr)
3504 {
3505         node_p dest;
3506
3507         ITEM_DEBUG_CHECKS;
3508         /*
3509          * Find the target node.
3510          */
3511         dest = ng_ID2noderef(ID); /* GETS REFERENCE! */
3512         if (dest == NULL) {
3513                 NG_FREE_ITEM(item);
3514                 TRAP_ERROR();
3515                 return(EINVAL);
3516         }
3517         /* Fill out the contents */
3518         NGI_SET_NODE(item, dest);
3519         NGI_CLR_HOOK(item);
3520         SET_RETADDR(item, here, retaddr);
3521         return (0);
3522 }
3523
3524 /*
3525  * special case to send a message to self (e.g. destroy node)
3526  * Possibly indicate an arrival hook too.
3527  * Useful for removing that hook :-)
3528  */
3529 item_p
3530 ng_package_msg_self(node_p here, hook_p hook, struct ng_mesg *msg)
3531 {
3532         item_p item;
3533
3534         /*
3535          * Find the target node.
3536          * If there is a HOOK argument, then use that in preference
3537          * to the address.
3538          */
3539         if ((item = ng_alloc_item(NGQF_MESG, NG_NOFLAGS)) == NULL) {
3540                 NG_FREE_MSG(msg);
3541                 return (NULL);
3542         }
3543
3544         /* Fill out the contents */
3545         item->el_flags |= NGQF_WRITER;
3546         NG_NODE_REF(here);
3547         NGI_SET_NODE(item, here);
3548         if (hook) {
3549                 NG_HOOK_REF(hook);
3550                 NGI_SET_HOOK(item, hook);
3551         }
3552         NGI_MSG(item) = msg;
3553         NGI_RETADDR(item) = ng_node2ID(here);
3554         return (item);
3555 }
3556
3557 /*
3558  * Send ng_item_fn function call to the specified node.
3559  */
3560
3561 int
3562 ng_send_fn(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2)
3563 {
3564
3565         return ng_send_fn1(node, hook, fn, arg1, arg2, NG_NOFLAGS);
3566 }
3567
3568 int
3569 ng_send_fn1(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2,
3570         int flags)
3571 {
3572         item_p item;
3573
3574         if ((item = ng_alloc_item(NGQF_FN, flags)) == NULL) {
3575                 return (ENOMEM);
3576         }
3577         item->el_flags |= NGQF_WRITER;
3578         NG_NODE_REF(node); /* and one for the item */
3579         NGI_SET_NODE(item, node);
3580         if (hook) {
3581                 NG_HOOK_REF(hook);
3582                 NGI_SET_HOOK(item, hook);
3583         }
3584         NGI_FN(item) = fn;
3585         NGI_ARG1(item) = arg1;
3586         NGI_ARG2(item) = arg2;
3587         return(ng_snd_item(item, flags));
3588 }
3589
3590 /*
3591  * Send ng_item_fn2 function call to the specified node.
3592  *
3593  * If an optional pitem parameter is supplied, its apply
3594  * callback will be copied to the new item. If also NG_REUSE_ITEM
3595  * flag is set, no new item will be allocated, but pitem will
3596  * be used.
3597  */
3598 int
3599 ng_send_fn2(node_p node, hook_p hook, item_p pitem, ng_item_fn2 *fn, void *arg1,
3600         int arg2, int flags)
3601 {
3602         item_p item;
3603
3604         KASSERT((pitem != NULL || (flags & NG_REUSE_ITEM) == 0),
3605             ("%s: NG_REUSE_ITEM but no pitem", __func__));
3606
3607         /*
3608          * Allocate a new item if no supplied or
3609          * if we can't use supplied one.
3610          */
3611         if (pitem == NULL || (flags & NG_REUSE_ITEM) == 0) {
3612                 if ((item = ng_alloc_item(NGQF_FN2, flags)) == NULL)
3613                         return (ENOMEM);
3614                 if (pitem != NULL)
3615                         item->apply = pitem->apply;
3616         } else {
3617                 if ((item = ng_realloc_item(pitem, NGQF_FN2, flags)) == NULL)
3618                         return (ENOMEM);
3619         }
3620
3621         item->el_flags = (item->el_flags & ~NGQF_RW) | NGQF_WRITER;
3622         NG_NODE_REF(node); /* and one for the item */
3623         NGI_SET_NODE(item, node);
3624         if (hook) {
3625                 NG_HOOK_REF(hook);
3626                 NGI_SET_HOOK(item, hook);
3627         }
3628         NGI_FN2(item) = fn;
3629         NGI_ARG1(item) = arg1;
3630         NGI_ARG2(item) = arg2;
3631         return(ng_snd_item(item, flags));
3632 }
3633
3634 /*
3635  * Official timeout routines for Netgraph nodes.
3636  */
3637 static void
3638 ng_callout_trampoline(void *arg)
3639 {
3640         item_p item = arg;
3641
3642         ng_snd_item(item, 0);
3643 }
3644
3645
3646 int
3647 ng_callout(struct callout *c, node_p node, hook_p hook, int ticks,
3648     ng_item_fn *fn, void * arg1, int arg2)
3649 {
3650         item_p item, oitem;
3651
3652         if ((item = ng_alloc_item(NGQF_FN, NG_NOFLAGS)) == NULL)
3653                 return (ENOMEM);
3654
3655         item->el_flags |= NGQF_WRITER;
3656         NG_NODE_REF(node);              /* and one for the item */
3657         NGI_SET_NODE(item, node);
3658         if (hook) {
3659                 NG_HOOK_REF(hook);
3660                 NGI_SET_HOOK(item, hook);
3661         }
3662         NGI_FN(item) = fn;
3663         NGI_ARG1(item) = arg1;
3664         NGI_ARG2(item) = arg2;
3665         oitem = c->c_arg;
3666         if (callout_reset(c, ticks, &ng_callout_trampoline, item) == 1 &&
3667             oitem != NULL)
3668                 NG_FREE_ITEM(oitem);
3669         return (0);
3670 }
3671
3672 /* A special modified version of untimeout() */
3673 int
3674 ng_uncallout(struct callout *c, node_p node)
3675 {
3676         item_p item;
3677         int rval;
3678
3679         KASSERT(c != NULL, ("ng_uncallout: NULL callout"));
3680         KASSERT(node != NULL, ("ng_uncallout: NULL node"));
3681
3682         rval = callout_stop(c);
3683         item = c->c_arg;
3684         /* Do an extra check */
3685         if ((rval > 0) && (c->c_func == &ng_callout_trampoline) &&
3686             (NGI_NODE(item) == node)) {
3687                 /*
3688                  * We successfully removed it from the queue before it ran
3689                  * So now we need to unreference everything that was
3690                  * given extra references. (NG_FREE_ITEM does this).
3691                  */
3692                 NG_FREE_ITEM(item);
3693         }
3694         c->c_arg = NULL;
3695
3696         return (rval);
3697 }
3698
3699 /*
3700  * Set the address, if none given, give the node here.
3701  */
3702 void
3703 ng_replace_retaddr(node_p here, item_p item, ng_ID_t retaddr)
3704 {
3705         if (retaddr) {
3706                 NGI_RETADDR(item) = retaddr;
3707         } else {
3708                 /*
3709                  * The old return address should be ok.
3710                  * If there isn't one, use the address here.
3711                  */
3712                 NGI_RETADDR(item) = ng_node2ID(here);
3713         }
3714 }
3715
3716 #define TESTING
3717 #ifdef TESTING
3718 /* just test all the macros */
3719 void
3720 ng_macro_test(item_p item);
3721 void
3722 ng_macro_test(item_p item)
3723 {
3724         node_p node = NULL;
3725         hook_p hook = NULL;
3726         struct mbuf *m;
3727         struct ng_mesg *msg;
3728         ng_ID_t retaddr;
3729         int     error;
3730
3731         NGI_GET_M(item, m);
3732         NGI_GET_MSG(item, msg);
3733         retaddr = NGI_RETADDR(item);
3734         NG_SEND_DATA(error, hook, m, NULL);
3735         NG_SEND_DATA_ONLY(error, hook, m);
3736         NG_FWD_NEW_DATA(error, item, hook, m);
3737         NG_FWD_ITEM_HOOK(error, item, hook);
3738         NG_SEND_MSG_HOOK(error, node, msg, hook, retaddr);
3739         NG_SEND_MSG_ID(error, node, msg, retaddr, retaddr);
3740         NG_SEND_MSG_PATH(error, node, msg, ".:", retaddr);
3741         NG_FWD_MSG_HOOK(error, node, item, hook, retaddr);
3742 }
3743 #endif /* TESTING */
3744