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