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