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