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