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