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