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