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