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