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