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