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