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