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