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