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