ng_base.c revision 71885
152419Sjulian/*
252419Sjulian * ng_base.c
352419Sjulian *
452419Sjulian * Copyright (c) 1996-1999 Whistle Communications, Inc.
552419Sjulian * All rights reserved.
670700Sjulian *
752419Sjulian * Subject to the following obligations and disclaimer of warranty, use and
852419Sjulian * redistribution of this software, in source or object code forms, with or
952419Sjulian * without modifications are expressly permitted by Whistle Communications;
1052419Sjulian * provided, however, that:
1152419Sjulian * 1. Any and all reproductions of the source or object code must include the
1252419Sjulian *    copyright notice above and the following disclaimer of warranties; and
1352419Sjulian * 2. No rights are granted, in any manner or form, to use Whistle
1452419Sjulian *    Communications, Inc. trademarks, including the mark "WHISTLE
1552419Sjulian *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
1652419Sjulian *    such appears in the above copyright notice or in the software.
1770700Sjulian *
1852419Sjulian * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
1952419Sjulian * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
2052419Sjulian * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
2152419Sjulian * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
2252419Sjulian * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
2352419Sjulian * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
2452419Sjulian * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
2552419Sjulian * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
2652419Sjulian * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
2752419Sjulian * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
2852419Sjulian * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
2952419Sjulian * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
3052419Sjulian * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
3152419Sjulian * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3252419Sjulian * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3352419Sjulian * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
3452419Sjulian * OF SUCH DAMAGE.
3552419Sjulian *
3667506Sjulian * Authors: Julian Elischer <julian@freebsd.org>
3767506Sjulian *          Archie Cobbs <archie@freebsd.org>
3852419Sjulian *
3952419Sjulian * $FreeBSD: head/sys/netgraph/ng_base.c 71885 2001-01-31 20:46:00Z julian $
4052419Sjulian * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
4152419Sjulian */
4252419Sjulian
4352419Sjulian/*
4452419Sjulian * This file implements the base netgraph code.
4552419Sjulian */
4652419Sjulian
4752419Sjulian#include <sys/param.h>
4852419Sjulian#include <sys/systm.h>
4952419Sjulian#include <sys/errno.h>
5052419Sjulian#include <sys/kernel.h>
5152419Sjulian#include <sys/malloc.h>
5252419Sjulian#include <sys/syslog.h>
5370700Sjulian#include <sys/sysctl.h>
5452419Sjulian#include <sys/linker.h>
5552419Sjulian#include <sys/queue.h>
5652419Sjulian#include <sys/mbuf.h>
5752843Sphk#include <sys/ctype.h>
5852816Sarchie#include <machine/limits.h>
5952419Sjulian
6052419Sjulian#include <net/netisr.h>
6152419Sjulian
6252419Sjulian#include <netgraph/ng_message.h>
6352419Sjulian#include <netgraph/netgraph.h>
6453913Sarchie#include <netgraph/ng_parse.h>
6552419Sjulian
6659756SpeterMODULE_VERSION(netgraph, 1);
6759756Speter
6870784Sjulian/* List of all active nodes */
6970700Sjulianstatic LIST_HEAD(, ng_node) ng_nodelist;
7070700Sjulianstatic struct mtx	ng_nodelist_mtx;
7152419Sjulian
7270784Sjulian#ifdef	NETGRAPH_DEBUG
7370784Sjulian
7470784Sjulianstatic SLIST_HEAD(, ng_node) ng_allnodes;
7570784Sjulianstatic LIST_HEAD(, ng_node) ng_freenodes; /* in debug, we never free() them */
7670784Sjulianstatic SLIST_HEAD(, ng_hook) ng_allhooks;
7770784Sjulianstatic LIST_HEAD(, ng_hook) ng_freehooks; /* in debug, we never free() them */
7870784Sjulian
7970784Sjulianstatic void ng_dumpitems(void);
8070784Sjulianstatic void ng_dumpnodes(void);
8170784Sjulianstatic void ng_dumphooks(void);
8270784Sjulian
8370784Sjulian#endif	/* NETGRAPH_DEBUG */
8470935Sjulian/*
8570935Sjulian * DEAD versions of the structures.
8670935Sjulian * In order to avoid races, it is sometimes neccesary to point
8770935Sjulian * at SOMETHING even though theoretically, the current entity is
8870935Sjulian * INVALID. Use these to avoid these races.
8970935Sjulian */
9070935Sjulianstruct ng_type ng_deadtype = {
9170935Sjulian	NG_ABI_VERSION,
9270935Sjulian	"dead",
9370935Sjulian	NULL,	/* modevent */
9470935Sjulian	NULL,	/* constructor */
9570935Sjulian	NULL,	/* rcvmsg */
9670935Sjulian	NULL,	/* shutdown */
9770935Sjulian	NULL,	/* newhook */
9870935Sjulian	NULL,	/* findhook */
9970935Sjulian	NULL,	/* connect */
10070935Sjulian	NULL,	/* rcvdata */
10170935Sjulian	NULL,	/* disconnect */
10270935Sjulian	NULL, 	/* cmdlist */
10370935Sjulian};
10470784Sjulian
10570935Sjulianstruct ng_node ng_deadnode = {
10670935Sjulian	"dead",
10770935Sjulian	&ng_deadtype,
10870935Sjulian	NG_INVALID,
10970935Sjulian	1,	/* refs */
11070935Sjulian	0,	/* numhooks */
11170935Sjulian	NULL,	/* private */
11270935Sjulian	0,	/* ID */
11370935Sjulian	LIST_HEAD_INITIALIZER(ng_deadnode.hooks),
11470935Sjulian	{},	/* all_nodes list entry */
11570935Sjulian	{},	/* id hashtable list entry */
11670935Sjulian	{},	/* workqueue entry */
11770935Sjulian	{	0,
11870935Sjulian		{}, /* should never use! (should hang) */
11970935Sjulian		NULL,
12070935Sjulian		&ng_deadnode.nd_input_queue.queue,
12170935Sjulian		&ng_deadnode
12270935Sjulian	},
12370935Sjulian#ifdef	NETGRAPH_DEBUG
12470935Sjulian	ND_MAGIC,
12570935Sjulian	__FILE__,
12670935Sjulian	__LINE__,
12770935Sjulian	{NULL}
12870935Sjulian#endif	/* NETGRAPH_DEBUG */
12970935Sjulian};
13070935Sjulian
13170935Sjulianstruct ng_hook ng_deadhook = {
13270935Sjulian	"dead",
13370935Sjulian	NULL,		/* private */
13470935Sjulian	HK_INVALID | HK_DEAD,
13570935Sjulian	1,		/* refs always >= 1 */
13670935Sjulian	&ng_deadhook,	/* Peer is self */
13770935Sjulian	&ng_deadnode,	/* attached to deadnode */
13870935Sjulian	{},		/* hooks list */
13971885Sjulian	NULL,		/* override rcvmsg() */
14071885Sjulian	NULL,		/* override rcvdata() */
14170935Sjulian#ifdef	NETGRAPH_DEBUG
14270935Sjulian	HK_MAGIC,
14370935Sjulian	__FILE__,
14470935Sjulian	__LINE__,
14570935Sjulian	{NULL}
14670935Sjulian#endif	/* NETGRAPH_DEBUG */
14770935Sjulian};
14870935Sjulian
14970935Sjulian/*
15070935Sjulian * END DEAD STRUCTURES
15170935Sjulian */
15270700Sjulian/* List nodes with unallocated work */
15370700Sjulianstatic TAILQ_HEAD(, ng_node) ng_worklist = TAILQ_HEAD_INITIALIZER(ng_worklist);
15470700Sjulianstatic struct mtx	ng_worklist_mtx;
15570700Sjulian
15652419Sjulian/* List of installed types */
15770700Sjulianstatic LIST_HEAD(, ng_type) ng_typelist;
15870700Sjulianstatic struct mtx	ng_typelist_mtx;
15952419Sjulian
16070700Sjulian/* Hash related definitions */
16171354Sjulian/* XXX Don't need to initialise them because it's a LIST */
16271354Sjulian#define NG_ID_HASH_SIZE 32 /* most systems wont need even this many */
16371354Sjulianstatic LIST_HEAD(, ng_node) ng_ID_hash[NG_ID_HASH_SIZE];
16470700Sjulianstatic struct mtx	ng_idhash_mtx;
16571354Sjulian/* Method to find a node.. used twice so do it here */
16671354Sjulian#define NG_IDHASH_FN(ID) ((ID) % (NG_ID_HASH_SIZE))
16771354Sjulian#define NG_IDHASH_FIND(ID, node)					\
16871354Sjulian	do { 								\
16971354Sjulian		LIST_FOREACH(node, &ng_ID_hash[NG_IDHASH_FN(ID)],	\
17071354Sjulian						nd_idnodes) {		\
17171354Sjulian			if (NG_NODE_IS_VALID(node)			\
17271354Sjulian			&& (NG_NODE_ID(node) == ID)) {			\
17371354Sjulian				break;					\
17471354Sjulian			}						\
17571354Sjulian		}							\
17671354Sjulian	} while (0)
17752722Sjulian
17870700Sjulian/* Mutex that protects the free queue item list */
17970700Sjulianstatic volatile item_p		ngqfree;	/* free ones */
18070700Sjulianstatic struct mtx	ngq_mtx;
18170700Sjulian
18252419Sjulian/* Internal functions */
18352419Sjulianstatic int	ng_add_hook(node_p node, const char *name, hook_p * hookp);
18470700Sjulianstatic int	ng_generic_msg(node_p here, item_p item, hook_p lasthook);
18552722Sjulianstatic ng_ID_t	ng_decodeidname(const char *name);
18652419Sjulianstatic int	ngb_mod_event(module_t mod, int event, void *data);
18770700Sjulianstatic void	ng_worklist_remove(node_p node);
18852419Sjulianstatic void	ngintr(void);
18971849Sjulianstatic int	ng_apply_item(item_p item);
19070700Sjulianstatic void	ng_flush_input_queue(struct ng_queue * ngq);
19170700Sjulianstatic void	ng_setisr(node_p node);
19270700Sjulianstatic node_p	ng_ID2noderef(ng_ID_t ID);
19371047Sjulianstatic int	ng_con_nodes(node_p node, const char *name, node_p node2,
19471047Sjulian							const char *name2);
19571849Sjulianstatic void	ng_con_part2(node_p node, hook_p hook, void *arg1, int arg2);
19671849Sjulianstatic void	ng_con_part3(node_p node, hook_p hook, void *arg1, int arg2);
19771047Sjulianstatic int	ng_mkpeer(node_p node, const char *name,
19871047Sjulian						const char *name2, char *type);
19952419Sjulian
20070784Sjulian/* imported , these used to be externally visible, some may go back */
20170700Sjulianint	ng_bypass(hook_p hook1, hook_p hook2);
20270700Sjulianvoid	ng_destroy_hook(hook_p hook);
20370700Sjuliannode_p	ng_name2noderef(node_p node, const char *name);
20470700Sjulianint	ng_path2noderef(node_p here, const char *path,
20570700Sjulian	node_p *dest, hook_p *lasthook);
20670700Sjulianstruct	ng_type *ng_findtype(const char *type);
20770700Sjulianint	ng_make_node(const char *type, node_p *nodepp);
20870700Sjulianint	ng_path_parse(char *addr, char **node, char **path, char **hook);
20971849Sjulianvoid	ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3);
21070784Sjulianvoid	ng_unname(node_p node);
21170700Sjulian
21270700Sjulian
21352419Sjulian/* Our own netgraph malloc type */
21452419SjulianMALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
21570700SjulianMALLOC_DEFINE(M_NETGRAPH_HOOK, "netgraph_hook", "netgraph hook structures");
21670700SjulianMALLOC_DEFINE(M_NETGRAPH_NODE, "netgraph_node", "netgraph node structures");
21770700SjulianMALLOC_DEFINE(M_NETGRAPH_ITEM, "netgraph_item", "netgraph item structures");
21870700SjulianMALLOC_DEFINE(M_NETGRAPH_META, "netgraph_meta", "netgraph name storage");
21970700SjulianMALLOC_DEFINE(M_NETGRAPH_MSG, "netgraph_msg", "netgraph name storage");
22052419Sjulian
22170700Sjulian/* Should not be visible outside this file */
22270784Sjulian
22370784Sjulian#define _NG_ALLOC_HOOK(hook) \
22470784Sjulian	MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH_HOOK, M_NOWAIT | M_ZERO)
22570784Sjulian#define _NG_ALLOC_NODE(node) \
22670784Sjulian	MALLOC(node, node_p, sizeof(*node), M_NETGRAPH_NODE, M_NOWAIT | M_ZERO)
22770784Sjulian
22870784Sjulian#ifdef NETGRAPH_DEBUG /*----------------------------------------------*/
22970784Sjulian/*
23070784Sjulian * In debug mode:
23170784Sjulian * In an attempt to help track reference count screwups
23270784Sjulian * we do not free objects back to the malloc system, but keep them
23370784Sjulian * in a local cache where we can examine them and keep information safely
23470784Sjulian * after they have been freed.
23570784Sjulian * We use this scheme for nodes and hooks, and to some extent for items.
23670784Sjulian */
23770784Sjulianstatic __inline hook_p
23870784Sjulianng_alloc_hook(void)
23970784Sjulian{
24070784Sjulian	hook_p hook;
24170784Sjulian	SLIST_ENTRY(ng_hook) temp;
24270784Sjulian	mtx_enter(&ng_nodelist_mtx, MTX_DEF);
24370784Sjulian	hook = LIST_FIRST(&ng_freehooks);
24470784Sjulian	if (hook) {
24570784Sjulian		LIST_REMOVE(hook, hk_hooks);
24670784Sjulian		bcopy(&hook->hk_all, &temp, sizeof(temp));
24770784Sjulian		bzero(hook, sizeof(struct ng_hook));
24870784Sjulian		bcopy(&temp, &hook->hk_all, sizeof(temp));
24970784Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);
25070784Sjulian		hook->hk_magic = HK_MAGIC;
25170784Sjulian	} else {
25270784Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);
25370784Sjulian		_NG_ALLOC_HOOK(hook);
25470784Sjulian		if (hook) {
25570784Sjulian			hook->hk_magic = HK_MAGIC;
25670784Sjulian			mtx_enter(&ng_nodelist_mtx, MTX_DEF);
25770784Sjulian			SLIST_INSERT_HEAD(&ng_allhooks, hook, hk_all);
25870784Sjulian			mtx_exit(&ng_nodelist_mtx, MTX_DEF);
25970784Sjulian		}
26070784Sjulian	}
26170784Sjulian	return (hook);
26270784Sjulian}
26370784Sjulian
26470784Sjulianstatic __inline node_p
26570784Sjulianng_alloc_node(void)
26670784Sjulian{
26770784Sjulian	node_p node;
26870784Sjulian	SLIST_ENTRY(ng_node) temp;
26970784Sjulian	mtx_enter(&ng_nodelist_mtx, MTX_DEF);
27070784Sjulian	node = LIST_FIRST(&ng_freenodes);
27170784Sjulian	if (node) {
27270784Sjulian		LIST_REMOVE(node, nd_nodes);
27370784Sjulian		bcopy(&node->nd_all, &temp, sizeof(temp));
27470784Sjulian		bzero(node, sizeof(struct ng_node));
27570784Sjulian		bcopy(&temp, &node->nd_all, sizeof(temp));
27670784Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);
27770784Sjulian		node->nd_magic = ND_MAGIC;
27870784Sjulian	} else {
27970784Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);
28070784Sjulian		_NG_ALLOC_NODE(node);
28170784Sjulian		if (node) {
28270784Sjulian			node->nd_magic = ND_MAGIC;
28370784Sjulian			mtx_enter(&ng_nodelist_mtx, MTX_DEF);
28470784Sjulian			SLIST_INSERT_HEAD(&ng_allnodes, node, nd_all);
28570784Sjulian			mtx_exit(&ng_nodelist_mtx, MTX_DEF);
28670784Sjulian		}
28770784Sjulian	}
28870784Sjulian	return (node);
28970784Sjulian}
29070784Sjulian
29170784Sjulian#define NG_ALLOC_HOOK(hook) do { (hook) = ng_alloc_hook(); } while (0)
29270784Sjulian#define NG_ALLOC_NODE(node) do { (node) = ng_alloc_node(); } while (0)
29370784Sjulian
29470784Sjulian
29570784Sjulian#define NG_FREE_HOOK(hook)						\
29670784Sjulian	do {								\
29770784Sjulian		mtx_enter(&ng_nodelist_mtx, MTX_DEF);			\
29870784Sjulian		LIST_INSERT_HEAD(&ng_freehooks, hook, hk_hooks);	\
29970784Sjulian		hook->hk_magic = 0;					\
30070784Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);			\
30170784Sjulian	} while (0)
30270784Sjulian
30370784Sjulian#define NG_FREE_NODE(node)						\
30470784Sjulian	do {								\
30570784Sjulian		mtx_enter(&ng_nodelist_mtx, MTX_DEF);			\
30670784Sjulian		LIST_INSERT_HEAD(&ng_freenodes, node, nd_nodes);	\
30770784Sjulian		node->nd_magic = 0;					\
30870784Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);			\
30970784Sjulian	} while (0)
31070784Sjulian
31170784Sjulian#else /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
31270784Sjulian
31370784Sjulian#define NG_ALLOC_HOOK(hook) _NG_ALLOC_HOOK(hook)
31470784Sjulian#define NG_ALLOC_NODE(node) _NG_ALLOC_NODE(node)
31570784Sjulian
31670700Sjulian#define NG_FREE_HOOK(hook) do { FREE((hook), M_NETGRAPH_HOOK); } while (0)
31770700Sjulian#define NG_FREE_NODE(node) do { FREE((node), M_NETGRAPH_NODE); } while (0)
31870784Sjulian
31970784Sjulian#endif /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
32070784Sjulian
32170700Sjulian/* Warning: Generally use NG_FREE_ITEM() instead */
32270700Sjulian#define NG_FREE_ITEM_REAL(item) do { FREE((item), M_NETGRAPH_ITEM); } while (0)
32370700Sjulian
32470700Sjulian
32552419Sjulian/* Set this to Debugger("X") to catch all errors as they occur */
32652419Sjulian#ifndef TRAP_ERROR
32771047Sjulian#define TRAP_ERROR()
32852419Sjulian#endif
32952419Sjulian
33052722Sjulianstatic	ng_ID_t nextID = 1;
33152722Sjulian
33253403Sarchie#ifdef INVARIANTS
33353403Sarchie#define CHECK_DATA_MBUF(m)	do {					\
33453403Sarchie		struct mbuf *n;						\
33553403Sarchie		int total;						\
33653403Sarchie									\
33753403Sarchie		if (((m)->m_flags & M_PKTHDR) == 0)			\
33853403Sarchie			panic("%s: !PKTHDR", __FUNCTION__);		\
33953403Sarchie		for (total = 0, n = (m); n != NULL; n = n->m_next)	\
34053403Sarchie			total += n->m_len;				\
34153403Sarchie		if ((m)->m_pkthdr.len != total) {			\
34253403Sarchie			panic("%s: %d != %d",				\
34353403Sarchie			    __FUNCTION__, (m)->m_pkthdr.len, total);	\
34453403Sarchie		}							\
34553403Sarchie	} while (0)
34653403Sarchie#else
34753403Sarchie#define CHECK_DATA_MBUF(m)
34853403Sarchie#endif
34952722Sjulian
35053403Sarchie
35152419Sjulian/************************************************************************
35253913Sarchie	Parse type definitions for generic messages
35353913Sarchie************************************************************************/
35453913Sarchie
35553913Sarchie/* Handy structure parse type defining macro */
35653913Sarchie#define DEFINE_PARSE_STRUCT_TYPE(lo, up, args)				\
35753913Sarchiestatic const struct ng_parse_struct_info				\
35853913Sarchie	ng_ ## lo ## _type_info = NG_GENERIC_ ## up ## _INFO args;	\
35953913Sarchiestatic const struct ng_parse_type ng_generic_ ## lo ## _type = {	\
36053913Sarchie	&ng_parse_struct_type,						\
36153913Sarchie	&ng_ ## lo ## _type_info					\
36253913Sarchie}
36353913Sarchie
36453913SarchieDEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
36553913SarchieDEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
36653913SarchieDEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
36753913SarchieDEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
36853913SarchieDEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
36953913SarchieDEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
37053913SarchieDEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
37153913Sarchie
37253913Sarchie/* Get length of an array when the length is stored as a 32 bit
37353913Sarchie   value immediately preceeding the array -- as with struct namelist
37453913Sarchie   and struct typelist. */
37553913Sarchiestatic int
37653913Sarchieng_generic_list_getLength(const struct ng_parse_type *type,
37753913Sarchie	const u_char *start, const u_char *buf)
37853913Sarchie{
37953913Sarchie	return *((const u_int32_t *)(buf - 4));
38053913Sarchie}
38153913Sarchie
38253913Sarchie/* Get length of the array of struct linkinfo inside a struct hooklist */
38353913Sarchiestatic int
38453913Sarchieng_generic_linkinfo_getLength(const struct ng_parse_type *type,
38553913Sarchie	const u_char *start, const u_char *buf)
38653913Sarchie{
38753913Sarchie	const struct hooklist *hl = (const struct hooklist *)start;
38853913Sarchie
38953913Sarchie	return hl->nodeinfo.hooks;
39053913Sarchie}
39153913Sarchie
39253913Sarchie/* Array type for a variable length array of struct namelist */
39353913Sarchiestatic const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
39453913Sarchie	&ng_generic_nodeinfo_type,
39553913Sarchie	&ng_generic_list_getLength
39653913Sarchie};
39753913Sarchiestatic const struct ng_parse_type ng_generic_nodeinfoarray_type = {
39853913Sarchie	&ng_parse_array_type,
39953913Sarchie	&ng_nodeinfoarray_type_info
40053913Sarchie};
40153913Sarchie
40253913Sarchie/* Array type for a variable length array of struct typelist */
40353913Sarchiestatic const struct ng_parse_array_info ng_typeinfoarray_type_info = {
40453913Sarchie	&ng_generic_typeinfo_type,
40553913Sarchie	&ng_generic_list_getLength
40653913Sarchie};
40753913Sarchiestatic const struct ng_parse_type ng_generic_typeinfoarray_type = {
40853913Sarchie	&ng_parse_array_type,
40953913Sarchie	&ng_typeinfoarray_type_info
41053913Sarchie};
41153913Sarchie
41253913Sarchie/* Array type for array of struct linkinfo in struct hooklist */
41353913Sarchiestatic const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
41453913Sarchie	&ng_generic_linkinfo_type,
41553913Sarchie	&ng_generic_linkinfo_getLength
41653913Sarchie};
41753913Sarchiestatic const struct ng_parse_type ng_generic_linkinfo_array_type = {
41853913Sarchie	&ng_parse_array_type,
41953913Sarchie	&ng_generic_linkinfo_array_type_info
42053913Sarchie};
42153913Sarchie
42253913SarchieDEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
42353913SarchieDEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
42453913Sarchie	(&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
42553913SarchieDEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
42653913Sarchie	(&ng_generic_nodeinfoarray_type));
42753913Sarchie
42853913Sarchie/* List of commands and how to convert arguments to/from ASCII */
42953913Sarchiestatic const struct ng_cmdlist ng_generic_cmds[] = {
43053913Sarchie	{
43153913Sarchie	  NGM_GENERIC_COOKIE,
43253913Sarchie	  NGM_SHUTDOWN,
43353913Sarchie	  "shutdown",
43453913Sarchie	  NULL,
43553913Sarchie	  NULL
43653913Sarchie	},
43753913Sarchie	{
43853913Sarchie	  NGM_GENERIC_COOKIE,
43953913Sarchie	  NGM_MKPEER,
44053913Sarchie	  "mkpeer",
44153913Sarchie	  &ng_generic_mkpeer_type,
44253913Sarchie	  NULL
44353913Sarchie	},
44453913Sarchie	{
44553913Sarchie	  NGM_GENERIC_COOKIE,
44653913Sarchie	  NGM_CONNECT,
44753913Sarchie	  "connect",
44853913Sarchie	  &ng_generic_connect_type,
44953913Sarchie	  NULL
45053913Sarchie	},
45153913Sarchie	{
45253913Sarchie	  NGM_GENERIC_COOKIE,
45353913Sarchie	  NGM_NAME,
45453913Sarchie	  "name",
45553913Sarchie	  &ng_generic_name_type,
45653913Sarchie	  NULL
45753913Sarchie	},
45853913Sarchie	{
45953913Sarchie	  NGM_GENERIC_COOKIE,
46053913Sarchie	  NGM_RMHOOK,
46153913Sarchie	  "rmhook",
46253913Sarchie	  &ng_generic_rmhook_type,
46353913Sarchie	  NULL
46453913Sarchie	},
46553913Sarchie	{
46653913Sarchie	  NGM_GENERIC_COOKIE,
46753913Sarchie	  NGM_NODEINFO,
46853913Sarchie	  "nodeinfo",
46953913Sarchie	  NULL,
47053913Sarchie	  &ng_generic_nodeinfo_type
47153913Sarchie	},
47253913Sarchie	{
47353913Sarchie	  NGM_GENERIC_COOKIE,
47453913Sarchie	  NGM_LISTHOOKS,
47553913Sarchie	  "listhooks",
47653913Sarchie	  NULL,
47753913Sarchie	  &ng_generic_hooklist_type
47853913Sarchie	},
47953913Sarchie	{
48053913Sarchie	  NGM_GENERIC_COOKIE,
48153913Sarchie	  NGM_LISTNAMES,
48253913Sarchie	  "listnames",
48353913Sarchie	  NULL,
48453913Sarchie	  &ng_generic_listnodes_type	/* same as NGM_LISTNODES */
48553913Sarchie	},
48653913Sarchie	{
48753913Sarchie	  NGM_GENERIC_COOKIE,
48853913Sarchie	  NGM_LISTNODES,
48953913Sarchie	  "listnodes",
49053913Sarchie	  NULL,
49153913Sarchie	  &ng_generic_listnodes_type
49253913Sarchie	},
49353913Sarchie	{
49453913Sarchie	  NGM_GENERIC_COOKIE,
49553913Sarchie	  NGM_LISTTYPES,
49653913Sarchie	  "listtypes",
49753913Sarchie	  NULL,
49853913Sarchie	  &ng_generic_typeinfo_type
49953913Sarchie	},
50053913Sarchie	{
50153913Sarchie	  NGM_GENERIC_COOKIE,
50262471Sphk	  NGM_TEXT_CONFIG,
50362471Sphk	  "textconfig",
50462471Sphk	  NULL,
50562471Sphk	  &ng_parse_string_type
50662471Sphk	},
50762471Sphk	{
50862471Sphk	  NGM_GENERIC_COOKIE,
50953913Sarchie	  NGM_TEXT_STATUS,
51053913Sarchie	  "textstatus",
51153913Sarchie	  NULL,
51253913Sarchie	  &ng_parse_string_type
51353913Sarchie	},
51453913Sarchie	{
51553913Sarchie	  NGM_GENERIC_COOKIE,
51653913Sarchie	  NGM_ASCII2BINARY,
51753913Sarchie	  "ascii2binary",
51853913Sarchie	  &ng_parse_ng_mesg_type,
51953913Sarchie	  &ng_parse_ng_mesg_type
52053913Sarchie	},
52153913Sarchie	{
52253913Sarchie	  NGM_GENERIC_COOKIE,
52353913Sarchie	  NGM_BINARY2ASCII,
52453913Sarchie	  "binary2ascii",
52553913Sarchie	  &ng_parse_ng_mesg_type,
52653913Sarchie	  &ng_parse_ng_mesg_type
52753913Sarchie	},
52853913Sarchie	{ 0 }
52953913Sarchie};
53053913Sarchie
53153913Sarchie/************************************************************************
53252419Sjulian			Node routines
53352419Sjulian************************************************************************/
53452419Sjulian
53552419Sjulian/*
53652419Sjulian * Instantiate a node of the requested type
53752419Sjulian */
53852419Sjulianint
53952419Sjulianng_make_node(const char *typename, node_p *nodepp)
54052419Sjulian{
54152419Sjulian	struct ng_type *type;
54270700Sjulian	int	error;
54352419Sjulian
54452419Sjulian	/* Check that the type makes sense */
54552419Sjulian	if (typename == NULL) {
54671047Sjulian		TRAP_ERROR();
54752419Sjulian		return (EINVAL);
54852419Sjulian	}
54952419Sjulian
55052419Sjulian	/* Locate the node type */
55152419Sjulian	if ((type = ng_findtype(typename)) == NULL) {
55259875Speter		char filename[NG_TYPELEN + 4];
55352419Sjulian		linker_file_t lf;
55452419Sjulian		int error;
55552419Sjulian
55652419Sjulian		/* Not found, try to load it as a loadable module */
55769923Sjulian		snprintf(filename, sizeof(filename), "ng_%s", typename);
55859875Speter		error = linker_load_file(filename, &lf);
55952419Sjulian		if (error != 0)
56052419Sjulian			return (error);
56152419Sjulian		lf->userrefs++;		/* pretend loaded by the syscall */
56252419Sjulian
56352419Sjulian		/* Try again, as now the type should have linked itself in */
56452419Sjulian		if ((type = ng_findtype(typename)) == NULL)
56552419Sjulian			return (ENXIO);
56652419Sjulian	}
56752419Sjulian
56870700Sjulian	/*
56970700Sjulian	 * If we have a constructor, then make the node and
57070700Sjulian	 * call the constructor to do type specific initialisation.
57170700Sjulian	 */
57270700Sjulian	if (type->constructor != NULL) {
57370700Sjulian		if ((error = ng_make_node_common(type, nodepp)) == 0) {
57470700Sjulian			if ((error = ((*type->constructor)(*nodepp)) != 0)) {
57570784Sjulian				NG_NODE_UNREF(*nodepp);
57670700Sjulian			}
57770700Sjulian		}
57870700Sjulian	} else {
57970700Sjulian		/*
58070700Sjulian		 * Node has no constructor. We cannot ask for one
58170700Sjulian		 * to be made. It must be brought into existance by
58270935Sjulian		 * some external agency. The external agency should
58370700Sjulian		 * call ng_make_node_common() directly to get the
58470700Sjulian		 * netgraph part initialised.
58570700Sjulian		 */
58671047Sjulian		TRAP_ERROR();
58770700Sjulian		error = EINVAL;
58870700Sjulian	}
58970700Sjulian	return (error);
59052419Sjulian}
59152419Sjulian
59252419Sjulian/*
59370700Sjulian * Generic node creation. Called by node initialisation for externally
59470700Sjulian * instantiated nodes (e.g. hardware, sockets, etc ).
59552419Sjulian * The returned node has a reference count of 1.
59652419Sjulian */
59752419Sjulianint
59852419Sjulianng_make_node_common(struct ng_type *type, node_p *nodepp)
59952419Sjulian{
60052419Sjulian	node_p node;
60152419Sjulian
60252419Sjulian	/* Require the node type to have been already installed */
60352419Sjulian	if (ng_findtype(type->name) == NULL) {
60471047Sjulian		TRAP_ERROR();
60552419Sjulian		return (EINVAL);
60652419Sjulian	}
60752419Sjulian
60852419Sjulian	/* Make a node and try attach it to the type */
60970784Sjulian	NG_ALLOC_NODE(node);
61052419Sjulian	if (node == NULL) {
61171047Sjulian		TRAP_ERROR();
61252419Sjulian		return (ENOMEM);
61352419Sjulian	}
61470784Sjulian	node->nd_type = type;
61570784Sjulian	NG_NODE_REF(node);				/* note reference */
61652419Sjulian	type->refs++;
61752419Sjulian
61871380Sjulian	mtx_init(&node->nd_input_queue.q_mtx, "netgraph node mutex", MTX_SPIN);
61970784Sjulian	node->nd_input_queue.queue = NULL;
62070784Sjulian	node->nd_input_queue.last = &node->nd_input_queue.queue;
62170784Sjulian	node->nd_input_queue.q_flags = 0;
62270784Sjulian	node->nd_input_queue.q_node = node;
62352419Sjulian
62452419Sjulian	/* Initialize hook list for new node */
62570784Sjulian	LIST_INIT(&node->nd_hooks);
62652419Sjulian
62770700Sjulian	/* Link us into the node linked list */
62870700Sjulian	mtx_enter(&ng_nodelist_mtx, MTX_DEF);
62970784Sjulian	LIST_INSERT_HEAD(&ng_nodelist, node, nd_nodes);
63070700Sjulian	mtx_exit(&ng_nodelist_mtx, MTX_DEF);
63170700Sjulian
63270700Sjulian
63352722Sjulian	/* get an ID and put us in the hash chain */
63470700Sjulian	mtx_enter(&ng_idhash_mtx, MTX_DEF);
63570784Sjulian	for (;;) { /* wrap protection, even if silly */
63670700Sjulian		node_p node2 = NULL;
63770784Sjulian		node->nd_ID = nextID++; /* 137/second for 1 year before wrap */
63871354Sjulian
63970784Sjulian		/* Is there a problem with the new number? */
64071354Sjulian		NG_IDHASH_FIND(node->nd_ID, node2); /* already taken? */
64171354Sjulian		if ((node->nd_ID != 0) && (node2 == NULL)) {
64270784Sjulian			break;
64370700Sjulian		}
64470784Sjulian	}
64571354Sjulian	LIST_INSERT_HEAD(&ng_ID_hash[NG_IDHASH_FN(node->nd_ID)],
64670784Sjulian							node, nd_idnodes);
64770700Sjulian	mtx_exit(&ng_idhash_mtx, MTX_DEF);
64852722Sjulian
64952419Sjulian	/* Done */
65052419Sjulian	*nodepp = node;
65152419Sjulian	return (0);
65252419Sjulian}
65352419Sjulian
65452419Sjulian/*
65552419Sjulian * Forceably start the shutdown process on a node. Either call
65652419Sjulian * it's shutdown method, or do the default shutdown if there is
65752419Sjulian * no type-specific method.
65852419Sjulian *
65970700Sjulian * We can only be called form a shutdown message, so we know we have
66070939Sjulian * a writer lock, and therefore exclusive access. It also means
66170939Sjulian * that we should not be on the work queue, but we check anyhow.
66270700Sjulian *
66370700Sjulian * Persistent node types must have a type-specific method which
66470939Sjulian * Allocates a new node in which case, this one is irretrievably going away,
66570939Sjulian * or cleans up anything it needs, and just makes the node valid again,
66670939Sjulian * in which case we allow the node to survive.
66770939Sjulian *
66870939Sjulian * XXX We need to think of how to tell a persistant node that we
66970939Sjulian * REALLY need to go away because the hardware has gone or we
67070939Sjulian * are rebooting.... etc.
67152419Sjulian */
67252419Sjulianvoid
67371849Sjulianng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3)
67452419Sjulian{
67570939Sjulian	hook_p hook;
67670939Sjulian
67752419Sjulian	/* Check if it's already shutting down */
67870784Sjulian	if ((node->nd_flags & NG_CLOSING) != 0)
67952419Sjulian		return;
68052419Sjulian
68171849Sjulian	if (node == &ng_deadnode) {
68271849Sjulian		printf ("shutdown called on deadnode\n");
68371849Sjulian		return;
68471849Sjulian	}
68571849Sjulian
68652419Sjulian	/* Add an extra reference so it doesn't go away during this */
68770784Sjulian	NG_NODE_REF(node);
68852419Sjulian
68970784Sjulian	/*
69070784Sjulian	 * Mark it invalid so any newcomers know not to try use it
69170784Sjulian	 * Also add our own mark so we can't recurse
69270784Sjulian	 * note that NG_INVALID does not do this as it's also set during
69370784Sjulian	 * creation
69470784Sjulian	 */
69570784Sjulian	node->nd_flags |= NG_INVALID|NG_CLOSING;
69652419Sjulian
69770939Sjulian	/* Notify all remaining connected nodes to disconnect */
69870939Sjulian	while ((hook = LIST_FIRST(&node->nd_hooks)) != NULL)
69970939Sjulian		ng_destroy_hook(hook);
70070784Sjulian
70170700Sjulian	/*
70270700Sjulian	 * Drain the input queue forceably.
70370784Sjulian	 * it has no hooks so what's it going to do, bleed on someone?
70470784Sjulian	 * Theoretically we came here from a queue entry that was added
70570784Sjulian	 * Just before the queue was closed, so it should be empty anyway.
70670700Sjulian	 */
70770784Sjulian	ng_flush_input_queue(&node->nd_input_queue);
70870700Sjulian
70970700Sjulian	/*
71070700Sjulian	 * Take us off the work queue if we are there.
71170784Sjulian	 * We definatly have no work to be done.
71270700Sjulian	 */
71370700Sjulian	ng_worklist_remove(node);
71470700Sjulian
71552419Sjulian	/* Ask the type if it has anything to do in this case */
71670784Sjulian	if (node->nd_type && node->nd_type->shutdown) {
71770784Sjulian		(*node->nd_type->shutdown)(node);
71871849Sjulian		if (NG_NODE_IS_VALID(node)) {
71971849Sjulian			/*
72071849Sjulian			 * Well, blow me down if the node code hasn't declared
72171849Sjulian			 * that it doesn't want to die.
72271849Sjulian			 * Presumably it is a persistant node.
72371849Sjulian			 * If we REALLY want it to go away,
72471849Sjulian			 *  e.g. hardware going away,
72571849Sjulian			 * Our caller should set NG_REALLY_DIE in nd_flags.
72671849Sjulian			 */
72771849Sjulian			node->nd_flags &= ~(NG_INVALID|NG_CLOSING);
72871849Sjulian			NG_NODE_UNREF(node); /* Assume they still have theirs */
72971849Sjulian			return;
73071849Sjulian		}
73170700Sjulian	} else {				/* do the default thing */
73270784Sjulian		NG_NODE_UNREF(node);
73352419Sjulian	}
73452419Sjulian
73570784Sjulian	ng_unname(node); /* basically a NOP these days */
73670784Sjulian
73770784Sjulian	/*
73870784Sjulian	 * Remove extra reference, possibly the last
73970784Sjulian	 * Possible other holders of references may include
74070784Sjulian	 * timeout callouts, but theoretically the node's supposed to
74170784Sjulian	 * have cancelled them. Possibly hardware dependencies may
74270784Sjulian	 * force a driver to 'linger' with a reference.
74370784Sjulian	 */
74470784Sjulian	NG_NODE_UNREF(node);
74552419Sjulian}
74652419Sjulian
74752419Sjulian/*
74852419Sjulian * Remove a reference to the node, possibly the last
74952419Sjulian */
75052419Sjulianvoid
75170784Sjulianng_unref_node(node_p node)
75252419Sjulian{
75370784Sjulian	int     v;
75471047Sjulian
75571047Sjulian	if (node == &ng_deadnode) {
75671047Sjulian		return;
75771047Sjulian	}
75871047Sjulian
75970784Sjulian	do {
76070784Sjulian		v = node->nd_refs;
76170784Sjulian	} while (! atomic_cmpset_int(&node->nd_refs, v, v - 1));
76269519Sjulian
76370784Sjulian	if (v == 1) { /* we were the last */
76470700Sjulian
76570700Sjulian		mtx_enter(&ng_nodelist_mtx, MTX_DEF);
76670784Sjulian		node->nd_type->refs--; /* XXX maybe should get types lock? */
76770784Sjulian		LIST_REMOVE(node, nd_nodes);
76870700Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);
76970700Sjulian
77070700Sjulian		mtx_enter(&ng_idhash_mtx, MTX_DEF);
77170784Sjulian		LIST_REMOVE(node, nd_idnodes);
77270700Sjulian		mtx_exit(&ng_idhash_mtx, MTX_DEF);
77352419Sjulian
77470791Sjulian		mtx_destroy(&node->nd_input_queue.q_mtx);
77570700Sjulian		NG_FREE_NODE(node);
77652419Sjulian	}
77752419Sjulian}
77852419Sjulian
77952419Sjulian/************************************************************************
78052722Sjulian			Node ID handling
78152722Sjulian************************************************************************/
78252722Sjulianstatic node_p
78370700Sjulianng_ID2noderef(ng_ID_t ID)
78452722Sjulian{
78570784Sjulian	node_p node;
78670700Sjulian	mtx_enter(&ng_idhash_mtx, MTX_DEF);
78771354Sjulian	NG_IDHASH_FIND(ID, node);
78870784Sjulian	if(node)
78970784Sjulian		NG_NODE_REF(node);
79070700Sjulian	mtx_exit(&ng_idhash_mtx, MTX_DEF);
79170784Sjulian	return(node);
79252722Sjulian}
79352722Sjulian
79452722Sjulianng_ID_t
79552722Sjulianng_node2ID(node_p node)
79652722Sjulian{
79770912Sjulian	return (node ? NG_NODE_ID(node) : 0);
79852722Sjulian}
79952722Sjulian
80052722Sjulian/************************************************************************
80152419Sjulian			Node name handling
80252419Sjulian************************************************************************/
80352419Sjulian
80452419Sjulian/*
80552419Sjulian * Assign a node a name. Once assigned, the name cannot be changed.
80652419Sjulian */
80752419Sjulianint
80852419Sjulianng_name_node(node_p node, const char *name)
80952419Sjulian{
81052419Sjulian	int i;
81170700Sjulian	node_p node2;
81252419Sjulian
81352419Sjulian	/* Check the name is valid */
81452419Sjulian	for (i = 0; i < NG_NODELEN + 1; i++) {
81552419Sjulian		if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
81652419Sjulian			break;
81752419Sjulian	}
81852419Sjulian	if (i == 0 || name[i] != '\0') {
81971047Sjulian		TRAP_ERROR();
82052419Sjulian		return (EINVAL);
82152419Sjulian	}
82252722Sjulian	if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
82371047Sjulian		TRAP_ERROR();
82452419Sjulian		return (EINVAL);
82552419Sjulian	}
82652419Sjulian
82752419Sjulian	/* Check the name isn't already being used */
82870700Sjulian	if ((node2 = ng_name2noderef(node, name)) != NULL) {
82970784Sjulian		NG_NODE_UNREF(node2);
83071047Sjulian		TRAP_ERROR();
83152419Sjulian		return (EADDRINUSE);
83252419Sjulian	}
83352419Sjulian
83470700Sjulian	/* copy it */
83570784Sjulian	strncpy(NG_NODE_NAME(node), name, NG_NODELEN);
83652419Sjulian
83752419Sjulian	return (0);
83852419Sjulian}
83952419Sjulian
84052419Sjulian/*
84152419Sjulian * Find a node by absolute name. The name should NOT end with ':'
84252419Sjulian * The name "." means "this node" and "[xxx]" means "the node
84352419Sjulian * with ID (ie, at address) xxx".
84452419Sjulian *
84552419Sjulian * Returns the node if found, else NULL.
84670700Sjulian * Eventually should add something faster than a sequential search.
84770784Sjulian * Note it aquires a reference on the node so you can be sure it's still there.
84852419Sjulian */
84952419Sjuliannode_p
85070700Sjulianng_name2noderef(node_p here, const char *name)
85152419Sjulian{
85252722Sjulian	node_p node;
85352722Sjulian	ng_ID_t temp;
85452419Sjulian
85552419Sjulian	/* "." means "this node" */
85670700Sjulian	if (strcmp(name, ".") == 0) {
85770784Sjulian		NG_NODE_REF(here);
85870700Sjulian		return(here);
85970700Sjulian	}
86052419Sjulian
86152419Sjulian	/* Check for name-by-ID */
86252722Sjulian	if ((temp = ng_decodeidname(name)) != 0) {
86370700Sjulian		return (ng_ID2noderef(temp));
86452419Sjulian	}
86552419Sjulian
86652419Sjulian	/* Find node by name */
86770700Sjulian	mtx_enter(&ng_nodelist_mtx, MTX_DEF);
86870784Sjulian	LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
86970912Sjulian		if (NG_NODE_IS_VALID(node)
87070912Sjulian		&& NG_NODE_HAS_NAME(node)
87170912Sjulian		&& (strcmp(NG_NODE_NAME(node), name) == 0)) {
87252419Sjulian			break;
87370912Sjulian		}
87452419Sjulian	}
87570700Sjulian	if (node)
87670784Sjulian		NG_NODE_REF(node);
87770700Sjulian	mtx_exit(&ng_nodelist_mtx, MTX_DEF);
87852419Sjulian	return (node);
87952419Sjulian}
88052419Sjulian
88152419Sjulian/*
88252722Sjulian * Decode a ID name, eg. "[f03034de]". Returns 0 if the
88352722Sjulian * string is not valid, otherwise returns the value.
88452419Sjulian */
88552722Sjulianstatic ng_ID_t
88652419Sjulianng_decodeidname(const char *name)
88752419Sjulian{
88852816Sarchie	const int len = strlen(name);
88953648Sarchie	char *eptr;
89052816Sarchie	u_long val;
89152419Sjulian
89252816Sarchie	/* Check for proper length, brackets, no leading junk */
89370912Sjulian	if ((len < 3)
89470912Sjulian	|| (name[0] != '[')
89570912Sjulian	|| (name[len - 1] != ']')
89670912Sjulian	|| (!isxdigit(name[1]))) {
89770912Sjulian		return ((ng_ID_t)0);
89870912Sjulian	}
89952419Sjulian
90052816Sarchie	/* Decode number */
90152816Sarchie	val = strtoul(name + 1, &eptr, 16);
90270912Sjulian	if ((eptr - name != len - 1)
90370912Sjulian	|| (val == ULONG_MAX)
90470912Sjulian	|| (val == 0)) {
90553042Sjulian		return ((ng_ID_t)0);
90670912Sjulian	}
90752816Sarchie	return (ng_ID_t)val;
90852419Sjulian}
90952419Sjulian
91052419Sjulian/*
91152419Sjulian * Remove a name from a node. This should only be called
91252419Sjulian * when shutting down and removing the node.
91371849Sjulian * IF we allow name changing this may be more resurected.
91452419Sjulian */
91552419Sjulianvoid
91652419Sjulianng_unname(node_p node)
91752419Sjulian{
91852419Sjulian}
91952419Sjulian
92052419Sjulian/************************************************************************
92152419Sjulian			Hook routines
92252419Sjulian Names are not optional. Hooks are always connected, except for a
92370939Sjulian brief moment within these routines. On invalidation or during creation
92470939Sjulian they are connected to the 'dead' hook.
92552419Sjulian************************************************************************/
92652419Sjulian
92752419Sjulian/*
92852419Sjulian * Remove a hook reference
92952419Sjulian */
93070784Sjulianvoid
93152419Sjulianng_unref_hook(hook_p hook)
93252419Sjulian{
93370784Sjulian	int     v;
93471047Sjulian
93571047Sjulian	if (hook == &ng_deadhook) {
93671047Sjulian		return;
93771047Sjulian	}
93870784Sjulian	do {
93970784Sjulian		v = hook->hk_refs;
94070784Sjulian	} while (! atomic_cmpset_int(&hook->hk_refs, v, v - 1));
94169519Sjulian
94270784Sjulian	if (v == 1) { /* we were the last */
94371047Sjulian		if (_NG_HOOK_NODE(hook)) { /* it'll probably be ng_deadnode */
94471047Sjulian			_NG_NODE_UNREF((_NG_HOOK_NODE(hook)));
94570784Sjulian			hook->hk_node = NULL;
94670700Sjulian		}
94770700Sjulian		NG_FREE_HOOK(hook);
94870700Sjulian	}
94952419Sjulian}
95052419Sjulian
95152419Sjulian/*
95252419Sjulian * Add an unconnected hook to a node. Only used internally.
95370939Sjulian * Assumes node is locked. (XXX not yet true )
95452419Sjulian */
95552419Sjulianstatic int
95652419Sjulianng_add_hook(node_p node, const char *name, hook_p *hookp)
95752419Sjulian{
95852419Sjulian	hook_p hook;
95952419Sjulian	int error = 0;
96052419Sjulian
96152419Sjulian	/* Check that the given name is good */
96252419Sjulian	if (name == NULL) {
96371047Sjulian		TRAP_ERROR();
96452419Sjulian		return (EINVAL);
96552419Sjulian	}
96654096Sarchie	if (ng_findhook(node, name) != NULL) {
96771047Sjulian		TRAP_ERROR();
96854096Sarchie		return (EEXIST);
96952419Sjulian	}
97052419Sjulian
97152419Sjulian	/* Allocate the hook and link it up */
97270784Sjulian	NG_ALLOC_HOOK(hook);
97352419Sjulian	if (hook == NULL) {
97471047Sjulian		TRAP_ERROR();
97552419Sjulian		return (ENOMEM);
97652419Sjulian	}
97770939Sjulian	hook->hk_refs = 1;		/* add a reference for us to return */
97870784Sjulian	hook->hk_flags = HK_INVALID;
97970939Sjulian	hook->hk_peer = &ng_deadhook;	/* start off this way */
98070784Sjulian	hook->hk_node = node;
98170784Sjulian	NG_NODE_REF(node);		/* each hook counts as a reference */
98252419Sjulian
98370939Sjulian	/* Set hook name */
98470939Sjulian	strncpy(NG_HOOK_NAME(hook), name, NG_HOOKLEN);
98570939Sjulian
98670939Sjulian	/*
98770939Sjulian	 * Check if the node type code has something to say about it
98870939Sjulian	 * If it fails, the unref of the hook will also unref the node.
98970939Sjulian	 */
99070935Sjulian	if (node->nd_type->newhook != NULL) {
99170935Sjulian		if ((error = (*node->nd_type->newhook)(node, hook, name))) {
99270784Sjulian			NG_HOOK_UNREF(hook);	/* this frees the hook */
99370700Sjulian			return (error);
99470700Sjulian		}
99570935Sjulian	}
99652419Sjulian	/*
99752419Sjulian	 * The 'type' agrees so far, so go ahead and link it in.
99852419Sjulian	 * We'll ask again later when we actually connect the hooks.
99952419Sjulian	 */
100070784Sjulian	LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
100170784Sjulian	node->nd_numhooks++;
100270939Sjulian	NG_HOOK_REF(hook);	/* one for the node */
100352419Sjulian
100452419Sjulian	if (hookp)
100552419Sjulian		*hookp = hook;
100670939Sjulian	return (0);
100752419Sjulian}
100852419Sjulian
100952419Sjulian/*
101054096Sarchie * Find a hook
101154096Sarchie *
101254096Sarchie * Node types may supply their own optimized routines for finding
101354096Sarchie * hooks.  If none is supplied, we just do a linear search.
101470939Sjulian * XXX Possibly we should add a reference to the hook?
101554096Sarchie */
101654096Sarchiehook_p
101754096Sarchieng_findhook(node_p node, const char *name)
101854096Sarchie{
101954096Sarchie	hook_p hook;
102054096Sarchie
102170784Sjulian	if (node->nd_type->findhook != NULL)
102270784Sjulian		return (*node->nd_type->findhook)(node, name);
102370784Sjulian	LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
102470912Sjulian		if (NG_HOOK_IS_VALID(hook)
102570917Sarchie		&& (strcmp(NG_HOOK_NAME(hook), name) == 0))
102654096Sarchie			return (hook);
102754096Sarchie	}
102854096Sarchie	return (NULL);
102954096Sarchie}
103054096Sarchie
103154096Sarchie/*
103252419Sjulian * Destroy a hook
103352419Sjulian *
103452419Sjulian * As hooks are always attached, this really destroys two hooks.
103552419Sjulian * The one given, and the one attached to it. Disconnect the hooks
103670939Sjulian * from each other first. We reconnect the peer hook to the 'dead'
103770939Sjulian * hook so that it can still exist after we depart. We then
103870939Sjulian * send the peer its own destroy message. This ensures that we only
103970939Sjulian * interact with the peer's structures when it is locked processing that
104070939Sjulian * message. We hold a reference to the peer hook so we are guaranteed that
104170939Sjulian * the peer hook and node are still going to exist until
104270939Sjulian * we are finished there as the hook holds a ref on the node.
104370939Sjulian * We run this same code again on the peer hook, but that time it is already
104470939Sjulian * attached to the 'dead' hook.
104571047Sjulian *
104671047Sjulian * This routine is called at all stages of hook creation
104771047Sjulian * on error detection and must be able to handle any such stage.
104852419Sjulian */
104952419Sjulianvoid
105052419Sjulianng_destroy_hook(hook_p hook)
105152419Sjulian{
105270784Sjulian	hook_p peer = NG_HOOK_PEER(hook);
105371047Sjulian	node_p node = NG_HOOK_NODE(hook);
105452419Sjulian
105571047Sjulian	if (hook == &ng_deadhook) {	/* better safe than sorry */
105671047Sjulian		printf("ng_destroy_hook called on deadhook\n");
105771047Sjulian		return;
105871047Sjulian	}
105970784Sjulian	hook->hk_flags |= HK_INVALID;		/* as soon as possible */
106070939Sjulian	if (peer && (peer != &ng_deadhook)) {
106170939Sjulian		/*
106270939Sjulian		 * Set the peer to point to ng_deadhook
106370939Sjulian		 * from this moment on we are effectively independent it.
106470939Sjulian		 * send it an rmhook message of it's own.
106570939Sjulian		 */
106670939Sjulian		peer->hk_peer = &ng_deadhook;	/* They no longer know us */
106770939Sjulian		hook->hk_peer = &ng_deadhook;	/* Nor us, them */
106871047Sjulian		if (NG_HOOK_NODE(peer) == &ng_deadnode) {
106971047Sjulian			/*
107071047Sjulian			 * If it's already divorced from a node,
107171047Sjulian			 * just free it.
107271047Sjulian			 */
107371047Sjulian			/* nothing */
107471047Sjulian		} else {
107571047Sjulian			ng_rmhook_self(peer); 	/* Send it a surprise */
107671047Sjulian		}
107770942Sjulian		NG_HOOK_UNREF(peer);		/* account for peer link */
107870942Sjulian		NG_HOOK_UNREF(hook);		/* account for peer link */
107952419Sjulian	}
108052419Sjulian
108152419Sjulian	/*
108252419Sjulian	 * Remove the hook from the node's list to avoid possible recursion
108352419Sjulian	 * in case the disconnection results in node shutdown.
108452419Sjulian	 */
108571047Sjulian	if (node == &ng_deadnode) { /* happens if called from ng_con_nodes() */
108671047Sjulian		return;
108771047Sjulian	}
108870784Sjulian	LIST_REMOVE(hook, hk_hooks);
108970784Sjulian	node->nd_numhooks--;
109070784Sjulian	if (node->nd_type->disconnect) {
109152419Sjulian		/*
109271047Sjulian		 * The type handler may elect to destroy the node so don't
109371047Sjulian		 * trust its existance after this point. (except
109471047Sjulian		 * that we still hold a reference on it. (which we
109571047Sjulian		 * inherrited from the hook we are destroying)
109652419Sjulian		 */
109770784Sjulian		(*node->nd_type->disconnect) (hook);
109852419Sjulian	}
109971047Sjulian
110071047Sjulian	/*
110171047Sjulian	 * Note that because we will point to ng_deadnode, the original node
110271047Sjulian	 * is not decremented automatically so we do that manually.
110371047Sjulian	 */
110471047Sjulian	_NG_HOOK_NODE(hook) = &ng_deadnode;
110571047Sjulian	NG_NODE_UNREF(node);	/* We no longer point to it so adjust count */
110671047Sjulian	NG_HOOK_UNREF(hook);	/* Account for linkage (in list) to node */
110752419Sjulian}
110852419Sjulian
110952419Sjulian/*
111052419Sjulian * Take two hooks on a node and merge the connection so that the given node
111152419Sjulian * is effectively bypassed.
111252419Sjulian */
111352419Sjulianint
111452419Sjulianng_bypass(hook_p hook1, hook_p hook2)
111552419Sjulian{
111670784Sjulian	if (hook1->hk_node != hook2->hk_node) {
111771047Sjulian		TRAP_ERROR();
111852419Sjulian		return (EINVAL);
111970784Sjulian	}
112070784Sjulian	hook1->hk_peer->hk_peer = hook2->hk_peer;
112170784Sjulian	hook2->hk_peer->hk_peer = hook1->hk_peer;
112252419Sjulian
112370939Sjulian	hook1->hk_peer = &ng_deadhook;
112470939Sjulian	hook2->hk_peer = &ng_deadhook;
112570939Sjulian
112652419Sjulian	/* XXX If we ever cache methods on hooks update them as well */
112752419Sjulian	ng_destroy_hook(hook1);
112852419Sjulian	ng_destroy_hook(hook2);
112952419Sjulian	return (0);
113052419Sjulian}
113152419Sjulian
113252419Sjulian/*
113352419Sjulian * Install a new netgraph type
113452419Sjulian */
113552419Sjulianint
113652419Sjulianng_newtype(struct ng_type *tp)
113752419Sjulian{
113852419Sjulian	const size_t namelen = strlen(tp->name);
113952419Sjulian
114052419Sjulian	/* Check version and type name fields */
114170159Sjulian	if ((tp->version != NG_ABI_VERSION)
114270159Sjulian	|| (namelen == 0)
114370159Sjulian	|| (namelen > NG_TYPELEN)) {
114471047Sjulian		TRAP_ERROR();
114552419Sjulian		return (EINVAL);
114652419Sjulian	}
114752419Sjulian
114852419Sjulian	/* Check for name collision */
114952419Sjulian	if (ng_findtype(tp->name) != NULL) {
115071047Sjulian		TRAP_ERROR();
115152419Sjulian		return (EEXIST);
115252419Sjulian	}
115352419Sjulian
115470700Sjulian
115552419Sjulian	/* Link in new type */
115670700Sjulian	mtx_enter(&ng_typelist_mtx, MTX_DEF);
115770700Sjulian	LIST_INSERT_HEAD(&ng_typelist, tp, types);
115871603Sjulian	tp->refs = 1;	/* first ref is linked list */
115970700Sjulian	mtx_exit(&ng_typelist_mtx, MTX_DEF);
116052419Sjulian	return (0);
116152419Sjulian}
116252419Sjulian
116352419Sjulian/*
116452419Sjulian * Look for a type of the name given
116552419Sjulian */
116652419Sjulianstruct ng_type *
116752419Sjulianng_findtype(const char *typename)
116852419Sjulian{
116952419Sjulian	struct ng_type *type;
117052419Sjulian
117170700Sjulian	mtx_enter(&ng_typelist_mtx, MTX_DEF);
117270700Sjulian	LIST_FOREACH(type, &ng_typelist, types) {
117352419Sjulian		if (strcmp(type->name, typename) == 0)
117452419Sjulian			break;
117552419Sjulian	}
117670700Sjulian	mtx_exit(&ng_typelist_mtx, MTX_DEF);
117752419Sjulian	return (type);
117852419Sjulian}
117952419Sjulian
118052419Sjulian/************************************************************************
118152419Sjulian			Composite routines
118252419Sjulian************************************************************************/
118352419Sjulian/*
118471047Sjulian * Connect two nodes using the specified hooks, using queued functions.
118552419Sjulian */
118671849Sjulianstatic void
118771047Sjulianng_con_part3(node_p node, hook_p hook, void *arg1, int arg2)
118852419Sjulian{
118952419Sjulian
119071047Sjulian	/*
119171047Sjulian	 * When we run, we know that the node 'node' is locked for us.
119271047Sjulian	 * Our caller has a reference on the hook.
119371047Sjulian	 * Our caller has a reference on the node.
119471047Sjulian	 * (In this case our caller is ng_apply_item() ).
119571047Sjulian	 * The peer hook has a reference on the hook.
119671849Sjulian	 * We are all set up except for the final call to the node, and
119771849Sjulian	 * the clearing of the INVALID flag.
119871047Sjulian	 */
119971047Sjulian	if (NG_HOOK_NODE(hook) == &ng_deadnode) {
120071047Sjulian		/*
120171047Sjulian		 * The node must have been freed again since we last visited
120271047Sjulian		 * here. ng_destry_hook() has this effect but nothing else does.
120371047Sjulian		 * We should just release our references and
120471047Sjulian		 * free anything we can think of.
120571047Sjulian		 * Since we know it's been destroyed, and it's our caller
120671047Sjulian		 * that holds the references, just return.
120771047Sjulian		 */
120871849Sjulian		return ;
120952419Sjulian	}
121071047Sjulian	if (hook->hk_node->nd_type->connect) {
121171849Sjulian		if ((*hook->hk_node->nd_type->connect) (hook)) {
121271047Sjulian			ng_destroy_hook(hook);	/* also zaps peer */
121371849Sjulian			printf("failed in ng_con_part3()\n");
121471849Sjulian			return ;
121571047Sjulian		}
121652419Sjulian	}
121771047Sjulian	/*
121871047Sjulian	 *  XXX this is wrong for SMP. Possibly we need
121971047Sjulian	 * to separate out 'create' and 'invalid' flags.
122071047Sjulian	 * should only set flags on hooks we have locked under our node.
122171047Sjulian	 */
122271047Sjulian	hook->hk_flags &= ~HK_INVALID;
122371849Sjulian	return ;
122471047Sjulian}
122552419Sjulian
122671849Sjulianstatic void
122771047Sjulianng_con_part2(node_p node, hook_p hook, void *arg1, int arg2)
122871047Sjulian{
122971047Sjulian
123052419Sjulian	/*
123171047Sjulian	 * When we run, we know that the node 'node' is locked for us.
123271047Sjulian	 * Our caller has a reference on the hook.
123371047Sjulian	 * Our caller has a reference on the node.
123471047Sjulian	 * (In this case our caller is ng_apply_item() ).
123571047Sjulian	 * The peer hook has a reference on the hook.
123671047Sjulian	 * our node pointer points to the 'dead' node.
123771047Sjulian	 * First check the hook name is unique.
123871849Sjulian	 * Should not happen because we checked before queueing this.
123952419Sjulian	 */
124071047Sjulian	if (ng_findhook(node, NG_HOOK_NAME(hook)) != NULL) {
124171047Sjulian		TRAP_ERROR();
124271047Sjulian		ng_destroy_hook(hook); /* should destroy peer too */
124371849Sjulian		printf("failed in ng_con_part2()\n");
124471849Sjulian		return ;
124571047Sjulian	}
124670939Sjulian	/*
124771047Sjulian	 * Check if the node type code has something to say about it
124871047Sjulian	 * If it fails, the unref of the hook will also unref the attached node,
124971047Sjulian	 * however since that node is 'ng_deadnode' this will do nothing.
125071047Sjulian	 * The peer hook will also be destroyed.
125170939Sjulian	 */
125271047Sjulian	if (node->nd_type->newhook != NULL) {
125371849Sjulian		if ((*node->nd_type->newhook)(node, hook, hook->hk_name)) {
125471047Sjulian			ng_destroy_hook(hook); /* should destroy peer too */
125571849Sjulian			printf("failed in ng_con_part2()\n");
125671849Sjulian			return ;
125771047Sjulian		}
125871047Sjulian	}
125971047Sjulian
126071047Sjulian	/*
126171047Sjulian	 * The 'type' agrees so far, so go ahead and link it in.
126271047Sjulian	 * We'll ask again later when we actually connect the hooks.
126371047Sjulian	 */
126471047Sjulian	hook->hk_node = node;		/* just overwrite ng_deadnode */
126571047Sjulian	NG_NODE_REF(node);		/* each hook counts as a reference */
126671047Sjulian	LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
126771047Sjulian	node->nd_numhooks++;
126871047Sjulian	NG_HOOK_REF(hook);	/* one for the node */
126971047Sjulian
127071047Sjulian	/*
127171047Sjulian	 * We now have a symetrical situation, where both hooks have been
127271047Sjulian	 * linked to theur nodes, the newhook methods have been called
127371047Sjulian	 * And the references are all correct. The hooks are still marked
127471047Sjulian	 * as invalid, as we have not called the 'connect' methods
127571047Sjulian	 * yet.
127671047Sjulian	 * We can call the local one immediatly as we have the
127771047Sjulian	 * node locked, but we need to queue the remote one.
127871047Sjulian	 */
127971047Sjulian	if (hook->hk_node->nd_type->connect) {
128071849Sjulian		if ((*hook->hk_node->nd_type->connect) (hook)) {
128171047Sjulian			ng_destroy_hook(hook);	/* also zaps peer */
128271849Sjulian			printf("failed in ng_con_part2(A)\n");
128371849Sjulian			return ;
128471047Sjulian		}
128571047Sjulian	}
128671849Sjulian	if (ng_send_fn(hook->hk_peer->hk_node, hook->hk_peer,
128771849Sjulian			&ng_con_part3, arg1, arg2)) {
128871849Sjulian		printf("failed in ng_con_part2(B)");
128971849Sjulian		ng_destroy_hook(hook);	/* also zaps peer */
129071849Sjulian		return ;
129171849Sjulian	}
129271047Sjulian	hook->hk_flags &= ~HK_INVALID; /* need both to be able to work */
129371849Sjulian	return ;
129452419Sjulian}
129552419Sjulian
129652419Sjulian/*
129771047Sjulian * Connect this node with another node. We assume that this node is
129871047Sjulian * currently locked, as we are only called from an NGM_CONNECT message.
129952419Sjulian */
130071047Sjulianstatic int
130152419Sjulianng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
130252419Sjulian{
130352419Sjulian	int     error;
130452419Sjulian	hook_p  hook;
130552419Sjulian	hook_p  hook2;
130652419Sjulian
130771849Sjulian	if (ng_findhook(node2, name2) != NULL) {
130871849Sjulian		return(EEXIST);
130971849Sjulian	}
131070939Sjulian	if ((error = ng_add_hook(node, name, &hook)))  /* gives us a ref */
131152419Sjulian		return (error);
131271047Sjulian	/* Allocate the other hook and link it up */
131371047Sjulian	NG_ALLOC_HOOK(hook2);
131471047Sjulian	if (hook == NULL) {
131571047Sjulian		TRAP_ERROR();
131671047Sjulian		ng_destroy_hook(hook);	/* XXX check ref counts so far */
131771047Sjulian		NG_HOOK_UNREF(hook);	/* including our ref */
131871047Sjulian		return (ENOMEM);
131971047Sjulian	}
132071047Sjulian	hook2->hk_refs = 1;		/* start with a reference for us. */
132171047Sjulian	hook2->hk_flags = HK_INVALID;
132271047Sjulian	hook2->hk_peer = hook;		/* Link the two together */
132371047Sjulian	hook->hk_peer = hook2;
132471047Sjulian	NG_HOOK_REF(hook);		/* Add a ref for the peer to each*/
132571047Sjulian	NG_HOOK_REF(hook2);
132671047Sjulian	hook2->hk_node = &ng_deadnode;
132771047Sjulian	strncpy(NG_HOOK_NAME(hook2), name2, NG_HOOKLEN);
132871047Sjulian
132971047Sjulian	/*
133071047Sjulian	 * Queue the function above.
133171047Sjulian	 * Procesing continues in that function in the lock context of
133271047Sjulian	 * the other node.
133371047Sjulian	 */
133471849Sjulian	ng_send_fn(node2, hook2, &ng_con_part2, NULL, 0);
133571047Sjulian
133671047Sjulian	NG_HOOK_UNREF(hook);		/* Let each hook go if it wants to */
133771047Sjulian	NG_HOOK_UNREF(hook2);
133871849Sjulian	return (0);
133971047Sjulian}
134071047Sjulian
134171047Sjulian/*
134271047Sjulian * Make a peer and connect.
134371047Sjulian * We assume that the local node is locked.
134471047Sjulian * The new node probably doesn't need a lock until
134571047Sjulian * it has a hook, because it cannot really have any work until then,
134671047Sjulian * but we should think about it a bit more.
134771047Sjulian *
134871047Sjulian * The problem may come if the other node also fires up
134971047Sjulian * some hardware or a timer or some other source of activation,
135071047Sjulian * also it may already get a command msg via it's ID.
135171047Sjulian *
135271047Sjulian * We could use the same method as ng_con_nodes() but we'd have
135371047Sjulian * to add ability to remove the node when failing. (Not hard, just
135471047Sjulian * make arg1 point to the node to remove).
135571047Sjulian * Unless of course we just ignore failure to connect and leave
135671047Sjulian * an unconnected node?
135771047Sjulian */
135871047Sjulianstatic int
135971047Sjulianng_mkpeer(node_p node, const char *name, const char *name2, char *type)
136071047Sjulian{
136171047Sjulian	node_p  node2;
136271047Sjulian	hook_p  hook1;
136371047Sjulian	hook_p  hook2;
136471047Sjulian	int     error;
136571047Sjulian
136671047Sjulian	if ((error = ng_make_node(type, &node2))) {
136752419Sjulian		return (error);
136852419Sjulian	}
136970939Sjulian
137071047Sjulian	if ((error = ng_add_hook(node, name, &hook1))) { /* gives us a ref */
137171849Sjulian		ng_rmnode(node2, NULL, NULL, 0);
137271047Sjulian		return (error);
137371047Sjulian	}
137471047Sjulian
137571047Sjulian	if ((error = ng_add_hook(node2, name2, &hook2))) {
137671849Sjulian		ng_rmnode(node2, NULL, NULL, 0);
137771047Sjulian		ng_destroy_hook(hook1);
137871047Sjulian		NG_HOOK_UNREF(hook1);
137971047Sjulian		return (error);
138071047Sjulian	}
138171047Sjulian
138270939Sjulian	/*
138371047Sjulian	 * Actually link the two hooks together.
138471047Sjulian	 */
138571047Sjulian	hook1->hk_peer = hook2;
138671047Sjulian	hook2->hk_peer = hook1;
138771047Sjulian
138871047Sjulian	/* Each hook is referenced by the other */
138971047Sjulian	NG_HOOK_REF(hook1);
139071047Sjulian	NG_HOOK_REF(hook2);
139171047Sjulian
139271047Sjulian	/* Give each node the opportunity to veto the pending connection */
139371047Sjulian	if (hook1->hk_node->nd_type->connect) {
139471047Sjulian		error = (*hook1->hk_node->nd_type->connect) (hook1);
139571047Sjulian	}
139671047Sjulian
139771047Sjulian	if ((error == 0) && hook2->hk_node->nd_type->connect) {
139871047Sjulian		error = (*hook2->hk_node->nd_type->connect) (hook2);
139971047Sjulian
140071047Sjulian	}
140171047Sjulian
140271047Sjulian	/*
140370939Sjulian	 * drop the references we were holding on the two hooks.
140470939Sjulian	 */
140571047Sjulian	if (error) {
140671047Sjulian		ng_destroy_hook(hook2);	/* also zaps hook1 */
140771849Sjulian		ng_rmnode(node2, NULL, NULL, 0);
140871047Sjulian	} else {
140971047Sjulian		/* As a last act, allow the hooks to be used */
141071047Sjulian		hook1->hk_flags &= ~HK_INVALID;
141171047Sjulian		hook2->hk_flags &= ~HK_INVALID;
141271047Sjulian	}
141371047Sjulian	NG_HOOK_UNREF(hook1);
141470939Sjulian	NG_HOOK_UNREF(hook2);
141570939Sjulian	return (error);
141652419Sjulian}
141771047Sjulian
141870700Sjulian/************************************************************************
141970700Sjulian		Utility routines to send self messages
142070700Sjulian************************************************************************/
142170700Sjulian
142271849Sjulian/* Shut this node down as soon as everyone is clear of it */
142371849Sjulian/* Should add arg "immediatly" to jump the queue */
142470700Sjulianint
142571849Sjulianng_rmnode_self(node_p node)
142670700Sjulian{
142771849Sjulian	int		error;
142852419Sjulian
142971849Sjulian	if (node == &ng_deadnode)
143071849Sjulian		return (0);
143171849Sjulian	if (node->nd_flags & NG_CLOSING)
143271849Sjulian		return (0);
143370700Sjulian
143471849Sjulian	error = ng_send_fn(node, NULL, &ng_rmnode, NULL, 0);
143571849Sjulian	return (error);
143670700Sjulian}
143770700Sjulian
143871849Sjulianstatic void
143971047Sjulianng_rmhook_part2(node_p node, hook_p hook, void *arg1, int arg2)
144071047Sjulian{
144171047Sjulian	ng_destroy_hook(hook);
144271849Sjulian	return ;
144371047Sjulian}
144471047Sjulian
144570935Sjulianint
144670935Sjulianng_rmhook_self(hook_p hook)
144770935Sjulian{
144871047Sjulian	int		error;
144970935Sjulian	node_p node = NG_HOOK_NODE(hook);
145070935Sjulian
145171047Sjulian	if (node == &ng_deadnode)
145271047Sjulian		return (0);
145371047Sjulian
145471047Sjulian	error = ng_send_fn(node, hook, &ng_rmhook_part2, NULL, 0);
145571047Sjulian	return (error);
145670935Sjulian}
145770935Sjulian
145870700Sjulian/***********************************************************************
145952419Sjulian * Parse and verify a string of the form:  <NODE:><PATH>
146052419Sjulian *
146152419Sjulian * Such a string can refer to a specific node or a specific hook
146252419Sjulian * on a specific node, depending on how you look at it. In the
146352419Sjulian * latter case, the PATH component must not end in a dot.
146452419Sjulian *
146552419Sjulian * Both <NODE:> and <PATH> are optional. The <PATH> is a string
146652419Sjulian * of hook names separated by dots. This breaks out the original
146752419Sjulian * string, setting *nodep to "NODE" (or NULL if none) and *pathp
146852419Sjulian * to "PATH" (or NULL if degenerate). Also, *hookp will point to
146952419Sjulian * the final hook component of <PATH>, if any, otherwise NULL.
147052419Sjulian *
147152419Sjulian * This returns -1 if the path is malformed. The char ** are optional.
147270700Sjulian ***********************************************************************/
147352419Sjulianint
147452419Sjulianng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
147552419Sjulian{
147652419Sjulian	char   *node, *path, *hook;
147752419Sjulian	int     k;
147852419Sjulian
147952419Sjulian	/*
148052419Sjulian	 * Extract absolute NODE, if any
148152419Sjulian	 */
148252419Sjulian	for (path = addr; *path && *path != ':'; path++);
148352419Sjulian	if (*path) {
148452419Sjulian		node = addr;	/* Here's the NODE */
148552419Sjulian		*path++ = '\0';	/* Here's the PATH */
148652419Sjulian
148752419Sjulian		/* Node name must not be empty */
148852419Sjulian		if (!*node)
148952419Sjulian			return -1;
149052419Sjulian
149152419Sjulian		/* A name of "." is OK; otherwise '.' not allowed */
149252419Sjulian		if (strcmp(node, ".") != 0) {
149352419Sjulian			for (k = 0; node[k]; k++)
149452419Sjulian				if (node[k] == '.')
149552419Sjulian					return -1;
149652419Sjulian		}
149752419Sjulian	} else {
149852419Sjulian		node = NULL;	/* No absolute NODE */
149952419Sjulian		path = addr;	/* Here's the PATH */
150052419Sjulian	}
150152419Sjulian
150252419Sjulian	/* Snoop for illegal characters in PATH */
150352419Sjulian	for (k = 0; path[k]; k++)
150452419Sjulian		if (path[k] == ':')
150552419Sjulian			return -1;
150652419Sjulian
150752419Sjulian	/* Check for no repeated dots in PATH */
150852419Sjulian	for (k = 0; path[k]; k++)
150952419Sjulian		if (path[k] == '.' && path[k + 1] == '.')
151052419Sjulian			return -1;
151152419Sjulian
151252419Sjulian	/* Remove extra (degenerate) dots from beginning or end of PATH */
151352419Sjulian	if (path[0] == '.')
151452419Sjulian		path++;
151552419Sjulian	if (*path && path[strlen(path) - 1] == '.')
151652419Sjulian		path[strlen(path) - 1] = 0;
151752419Sjulian
151852419Sjulian	/* If PATH has a dot, then we're not talking about a hook */
151952419Sjulian	if (*path) {
152052419Sjulian		for (hook = path, k = 0; path[k]; k++)
152152419Sjulian			if (path[k] == '.') {
152252419Sjulian				hook = NULL;
152352419Sjulian				break;
152452419Sjulian			}
152552419Sjulian	} else
152652419Sjulian		path = hook = NULL;
152752419Sjulian
152852419Sjulian	/* Done */
152952419Sjulian	if (nodep)
153052419Sjulian		*nodep = node;
153152419Sjulian	if (pathp)
153252419Sjulian		*pathp = path;
153352419Sjulian	if (hookp)
153452419Sjulian		*hookp = hook;
153552419Sjulian	return (0);
153652419Sjulian}
153752419Sjulian
153852419Sjulian/*
153952419Sjulian * Given a path, which may be absolute or relative, and a starting node,
154070700Sjulian * return the destination node.
154152419Sjulian */
154252419Sjulianint
154370700Sjulianng_path2noderef(node_p here, const char *address,
154470700Sjulian				node_p *destp, hook_p *lasthook)
154552419Sjulian{
154652419Sjulian	char    fullpath[NG_PATHLEN + 1];
154752419Sjulian	char   *nodename, *path, pbuf[2];
154870700Sjulian	node_p  node, oldnode;
154952419Sjulian	char   *cp;
155059728Sjulian	hook_p hook = NULL;
155152419Sjulian
155252419Sjulian	/* Initialize */
155370784Sjulian	if (destp == NULL) {
155471047Sjulian		TRAP_ERROR();
155552419Sjulian		return EINVAL;
155670784Sjulian	}
155752419Sjulian	*destp = NULL;
155852419Sjulian
155952419Sjulian	/* Make a writable copy of address for ng_path_parse() */
156052419Sjulian	strncpy(fullpath, address, sizeof(fullpath) - 1);
156152419Sjulian	fullpath[sizeof(fullpath) - 1] = '\0';
156252419Sjulian
156352419Sjulian	/* Parse out node and sequence of hooks */
156452419Sjulian	if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
156571047Sjulian		TRAP_ERROR();
156652419Sjulian		return EINVAL;
156752419Sjulian	}
156852419Sjulian	if (path == NULL) {
156952419Sjulian		pbuf[0] = '.';	/* Needs to be writable */
157052419Sjulian		pbuf[1] = '\0';
157152419Sjulian		path = pbuf;
157252419Sjulian	}
157352419Sjulian
157470700Sjulian	/*
157570700Sjulian	 * For an absolute address, jump to the starting node.
157670700Sjulian	 * Note that this holds a reference on the node for us.
157770700Sjulian	 * Don't forget to drop the reference if we don't need it.
157870700Sjulian	 */
157952419Sjulian	if (nodename) {
158070700Sjulian		node = ng_name2noderef(here, nodename);
158152419Sjulian		if (node == NULL) {
158271047Sjulian			TRAP_ERROR();
158352419Sjulian			return (ENOENT);
158452419Sjulian		}
158570700Sjulian	} else {
158670700Sjulian		if (here == NULL) {
158771047Sjulian			TRAP_ERROR();
158870700Sjulian			return (EINVAL);
158970700Sjulian		}
159052419Sjulian		node = here;
159170784Sjulian		NG_NODE_REF(node);
159270700Sjulian	}
159352419Sjulian
159470700Sjulian	/*
159570700Sjulian	 * Now follow the sequence of hooks
159670700Sjulian	 * XXX
159770700Sjulian	 * We actually cannot guarantee that the sequence
159870700Sjulian	 * is not being demolished as we crawl along it
159970700Sjulian	 * without extra-ordinary locking etc.
160070700Sjulian	 * So this is a bit dodgy to say the least.
160170700Sjulian	 * We can probably hold up some things by holding
160270700Sjulian	 * the nodelist mutex for the time of this
160370700Sjulian	 * crawl if we wanted.. At least that way we wouldn't have to
160470700Sjulian	 * worry about the nodes dissappearing, but the hooks would still
160570700Sjulian	 * be a problem.
160670700Sjulian	 */
160752419Sjulian	for (cp = path; node != NULL && *cp != '\0'; ) {
160852419Sjulian		char *segment;
160952419Sjulian
161052419Sjulian		/*
161152419Sjulian		 * Break out the next path segment. Replace the dot we just
161252419Sjulian		 * found with a NUL; "cp" points to the next segment (or the
161352419Sjulian		 * NUL at the end).
161452419Sjulian		 */
161552419Sjulian		for (segment = cp; *cp != '\0'; cp++) {
161652419Sjulian			if (*cp == '.') {
161752419Sjulian				*cp++ = '\0';
161852419Sjulian				break;
161952419Sjulian			}
162052419Sjulian		}
162152419Sjulian
162252419Sjulian		/* Empty segment */
162352419Sjulian		if (*segment == '\0')
162452419Sjulian			continue;
162552419Sjulian
162652419Sjulian		/* We have a segment, so look for a hook by that name */
162754096Sarchie		hook = ng_findhook(node, segment);
162852419Sjulian
162952419Sjulian		/* Can't get there from here... */
163052419Sjulian		if (hook == NULL
163170784Sjulian		    || NG_HOOK_PEER(hook) == NULL
163270784Sjulian		    || NG_HOOK_NOT_VALID(hook)
163370784Sjulian		    || NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))) {
163471047Sjulian			TRAP_ERROR();
163570784Sjulian			NG_NODE_UNREF(node);
163670784Sjulian#if 0
163770784Sjulian			printf("hooknotvalid %s %s %d %d %d %d ",
163870784Sjulian					path,
163970784Sjulian					segment,
164070784Sjulian					hook == NULL,
164170784Sjulian		     			NG_HOOK_PEER(hook) == NULL,
164270784Sjulian		     			NG_HOOK_NOT_VALID(hook),
164370784Sjulian		     			NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook)));
164470784Sjulian#endif
164552419Sjulian			return (ENOENT);
164652419Sjulian		}
164752419Sjulian
164870700Sjulian		/*
164970700Sjulian		 * Hop on over to the next node
165070700Sjulian		 * XXX
165170700Sjulian		 * Big race conditions here as hooks and nodes go away
165270700Sjulian		 * *** Idea.. store an ng_ID_t in each hook and use that
165370700Sjulian		 * instead of the direct hook in this crawl?
165470700Sjulian		 */
165570700Sjulian		oldnode = node;
165670784Sjulian		if ((node = NG_PEER_NODE(hook)))
165770784Sjulian			NG_NODE_REF(node);	/* XXX RACE */
165870784Sjulian		NG_NODE_UNREF(oldnode);	/* XXX another race */
165970784Sjulian		if (NG_NODE_NOT_VALID(node)) {
166070784Sjulian			NG_NODE_UNREF(node);	/* XXX more races */
166170700Sjulian			node = NULL;
166270700Sjulian		}
166352419Sjulian	}
166452419Sjulian
166552419Sjulian	/* If node somehow missing, fail here (probably this is not needed) */
166652419Sjulian	if (node == NULL) {
166771047Sjulian		TRAP_ERROR();
166852419Sjulian		return (ENXIO);
166952419Sjulian	}
167052419Sjulian
167152419Sjulian	/* Done */
167252419Sjulian	*destp = node;
167359900Sarchie	if (lasthook != NULL)
167470784Sjulian		*lasthook = (hook ? NG_HOOK_PEER(hook) : NULL);
167552419Sjulian	return (0);
167652419Sjulian}
167752419Sjulian
167870700Sjulian/***************************************************************\
167970700Sjulian* Input queue handling.
168070700Sjulian* All activities are submitted to the node via the input queue
168170700Sjulian* which implements a multiple-reader/single-writer gate.
168270700Sjulian* Items which cannot be handled immeditly are queued.
168370700Sjulian*
168470700Sjulian* read-write queue locking inline functions			*
168570700Sjulian\***************************************************************/
168670700Sjulian
168770700Sjulianstatic __inline item_p ng_dequeue(struct ng_queue * ngq);
168870700Sjulianstatic __inline item_p ng_acquire_read(struct ng_queue * ngq,
168970700Sjulian					item_p  item);
169070700Sjulianstatic __inline item_p ng_acquire_write(struct ng_queue * ngq,
169170700Sjulian					item_p  item);
169270700Sjulianstatic __inline void	ng_leave_read(struct ng_queue * ngq);
169370700Sjulianstatic __inline void	ng_leave_write(struct ng_queue * ngq);
169470700Sjulianstatic __inline void	ng_queue_rw(struct ng_queue * ngq,
169570700Sjulian					item_p  item, int rw);
169670700Sjulian
169752419Sjulian/*
169870700Sjulian * Definition of the bits fields in the ng_queue flag word.
169970700Sjulian * Defined here rather than in netgraph.h because no-one should fiddle
170070700Sjulian * with them.
170170700Sjulian *
170270700Sjulian * The ordering here is important! don't shuffle these. If you add
170370700Sjulian * READ_PENDING to the word when it has READ_PENDING already set, you
170470700Sjulian * generate a carry into the reader count, this you atomically add a reader,
170570700Sjulian * and remove the pending reader count! Similarly for the pending writer
170670700Sjulian * flag, adding WRITE_PENDING generates a carry and sets the WRITER_ACTIVE
170770700Sjulian * flag, while clearing WRITE_PENDING. When 'SINGLE_THREAD_ONLY' is set, then
170870700Sjulian * it is only permitted to do WRITER operations. Reader operations will
170970700Sjulian * result in errors.
171070700Sjulian * But that "hack" is unnecessary: "cpp" can do the math for us!
171152419Sjulian */
171270700Sjulian/*-
171370700Sjulian Safety Barrier--------+ (adjustable to suit taste) (not used yet)
171470700Sjulian                       |
171570700Sjulian                       V
171670700Sjulian+-------+-------+-------+-------+-------+-------+-------+-------+
171770700Sjulian| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
171870700Sjulian|A|c|t|i|v|e| |R|e|a|d|e|r| |C|o|u|n|t| | | | | | | | | |R|A|W|S|
171970700Sjulian| | | | | | | | | | | | | | | | | | | | | | | | | | | | |P|W|P|T|
172070700Sjulian+-------+-------+-------+-------+-------+-------+-------+-------+
172170700Sjulian\_________________________ ____________________________/ | | | |
172270700Sjulian                          V                              | | | |
172370700Sjulian                [active reader count]                    | | | |
172470700Sjulian                                                         | | | |
172570700Sjulian        Read Pending ------------------------------------+ | | |
172670700Sjulian                                                           | | |
172770700Sjulian        Active Writer -------------------------------------+ | |
172870700Sjulian                                                             | |
172970700Sjulian        Write Pending ---------------------------------------+ |
173070700Sjulian                                                               |
173170700Sjulian        Single Threading Only ---------------------------------+
173270700Sjulian*/
173370700Sjulian#define	SINGLE_THREAD_ONLY 0x00000001	/* if set, even reads single thread */
173470700Sjulian#define WRITE_PENDING	0x00000002
173570700Sjulian#define	WRITER_ACTIVE	0x00000004
173670700Sjulian#define READ_PENDING	0x00000008
173770700Sjulian#define	READER_INCREMENT 0x00000010
173870700Sjulian#define	READER_MASK	0xfffffff0	/* Not valid if WRITER_ACTIVE is set */
173970700Sjulian#define SAFETY_BARRIER	0x00100000	/* 64K items queued should be enough */
174070700Sjulian/*
174170700Sjulian * Taking into account the current state of the queue and node, possibly take
174270700Sjulian * the next entry off the queue and return it. Return NULL if there was
174370700Sjulian * nothing we could return, either because there really was nothing there, or
174470700Sjulian * because the node was in a state where it cannot yet process the next item
174570700Sjulian * on the queue.
174670700Sjulian *
174770700Sjulian * This MUST MUST MUST be called with the mutex held.
174870700Sjulian */
174970700Sjulianstatic __inline item_p
175070700Sjulianng_dequeue(struct ng_queue *ngq)
175170700Sjulian{
175270700Sjulian	item_p item;
175370700Sjulian	u_int		add_arg;
175470700Sjulian	/*
175570700Sjulian	 * If there is a writer, then the answer is "no". Everything else
175670700Sjulian	 * stops when there is a WRITER.
175770700Sjulian	 */
175870700Sjulian	if (ngq->q_flags & WRITER_ACTIVE) {
175970700Sjulian		return (NULL);
176070700Sjulian	}
176170700Sjulian	/* Now take a look at what's on the queue and what's running */
176270700Sjulian	if ((ngq->q_flags & ~(READER_MASK | SINGLE_THREAD_ONLY)) == READ_PENDING) {
176370700Sjulian		/*
176470700Sjulian		 * It was a reader and we have no write active. We don't care
176570700Sjulian		 * how many readers are already active. Adjust the count for
176670700Sjulian		 * the item we are about to dequeue. Adding READ_PENDING to
176770700Sjulian		 * the exisiting READ_PENDING clears it and generates a carry
176870700Sjulian		 * into the reader count.
176970700Sjulian		 */
177070700Sjulian		add_arg = READ_PENDING;
177170700Sjulian	} else if ((ngq->q_flags & ~SINGLE_THREAD_ONLY) == WRITE_PENDING) {
177270700Sjulian		/*
177370700Sjulian		 * There is a pending write, no readers and no active writer.
177470700Sjulian		 * This means we can go ahead with the pending writer. Note
177570700Sjulian		 * the fact that we now have a writer, ready for when we take
177670700Sjulian		 * it off the queue.
177770700Sjulian		 *
177870700Sjulian		 * We don't need to worry about a possible collision with the
177970700Sjulian		 * fasttrack reader.
178070700Sjulian		 *
178170700Sjulian		 * The fasttrack thread may take a long time to discover that we
178270700Sjulian		 * are running so we would have an inconsistent state in the
178370700Sjulian		 * flags for a while. Since we ignore the reader count
178470700Sjulian		 * entirely when the WRITER_ACTIVE flag is set, this should
178570700Sjulian		 * not matter (in fact it is defined that way). If it tests
178670700Sjulian		 * the flag before this operation, the WRITE_PENDING flag
178770700Sjulian		 * will make it fail, and if it tests it later, the
178870700Sjulian		 * ACTIVE_WRITER flag will do the same. If it is SO slow that
178970700Sjulian		 * we have actually completed the operation, and neither flag
179070700Sjulian		 * is set (nor the READ_PENDING) by the time that it tests
179170700Sjulian		 * the flags, then it is actually ok for it to continue. If
179270700Sjulian		 * it completes and we've finished and the read pending is
179370700Sjulian		 * set it still fails.
179470700Sjulian		 *
179570700Sjulian		 * So we can just ignore it,  as long as we can ensure that the
179670700Sjulian		 * transition from WRITE_PENDING state to the WRITER_ACTIVE
179770700Sjulian		 * state is atomic.
179870700Sjulian		 *
179970700Sjulian		 * After failing, first it will be held back by the mutex, then
180070700Sjulian		 * when it can proceed, it will queue its request, then it
180170700Sjulian		 * would arrive at this function. Usually it will have to
180270700Sjulian		 * leave empty handed because the ACTIVE WRITER bit wil be
180370700Sjulian		 * set.
180470700Sjulian		 */
180570700Sjulian		/*
180670700Sjulian		 * Adjust the flags for the item we are about to dequeue.
180770700Sjulian		 * Adding WRITE_PENDING to the exisiting WRITE_PENDING clears
180870700Sjulian		 * it and generates a carry into the WRITER_ACTIVE flag, all
180970700Sjulian		 * atomically.
181070700Sjulian		 */
181170700Sjulian		add_arg = WRITE_PENDING;
181270700Sjulian		/*
181370700Sjulian		 * We want to write "active writer, no readers " Now go make
181470700Sjulian		 * it true. In fact there may be a number in the readers
181570700Sjulian		 * count but we know it is not true and will be fixed soon.
181670700Sjulian		 * We will fix the flags for the next pending entry in a
181770700Sjulian		 * moment.
181870700Sjulian		 */
181970700Sjulian	} else {
182070700Sjulian		/*
182170700Sjulian		 * We can't dequeue anything.. return and say so. Probably we
182270700Sjulian		 * have a write pending and the readers count is non zero. If
182370700Sjulian		 * we got here because a reader hit us just at the wrong
182470700Sjulian		 * moment with the fasttrack code, and put us in a strange
182570700Sjulian		 * state, then it will be through in just a moment, (as soon
182670700Sjulian		 * as we release the mutex) and keep things moving.
182770700Sjulian		 */
182870700Sjulian		return (0);
182970700Sjulian	}
183052419Sjulian
183170700Sjulian	/*
183270700Sjulian	 * Now we dequeue the request (whatever it may be) and correct the
183370700Sjulian	 * pending flags and the next and last pointers.
183470700Sjulian	 */
183570700Sjulian	item = ngq->queue;
183670700Sjulian	ngq->queue = item->el_next;
183770700Sjulian	if (ngq->last == &(item->el_next)) {
183870700Sjulian		/*
183970700Sjulian		 * that was the last entry in the queue so set the 'last
184070700Sjulian		 * pointer up correctly and make sure the pending flags are
184170700Sjulian		 * clear.
184270700Sjulian		 */
184370700Sjulian		ngq->last = &(ngq->queue);
184470700Sjulian		/*
184570700Sjulian		 * Whatever flag was set is cleared and the carry sets the
184670700Sjulian		 * correct new active state/count. So we don't need to change
184770700Sjulian		 * add_arg.
184870700Sjulian		 */
184970700Sjulian	} else {
185071047Sjulian		if ((ngq->queue->el_flags & NGQF_RW) == NGQF_READER) {
185170700Sjulian			/*
185270700Sjulian			 * If we had a READ_PENDING and have another one, we
185370700Sjulian			 * just want to add READ_PENDING twice (the same as
185470700Sjulian			 * adding READER_INCREMENT). If we had WRITE_PENDING,
185570700Sjulian			 * we want to add READ_PENDING + WRITE_PENDING to
185670700Sjulian			 * clear the old WRITE_PENDING, set ACTIVE_WRITER,
185770700Sjulian			 * and set READ_PENDING. Either way we just add
185870700Sjulian			 * READ_PENDING to whatever we already had.
185970700Sjulian			 */
186070700Sjulian			add_arg += READ_PENDING;
186170700Sjulian		} else {
186270700Sjulian			/*
186370700Sjulian			 * If we had a WRITE_PENDING and have another one, we
186470700Sjulian			 * just want to add WRITE_PENDING twice (the same as
186570700Sjulian			 * adding ACTIVE_WRITER). If we had READ_PENDING, we
186670700Sjulian			 * want to add READ_PENDING + WRITE_PENDING to clear
186770700Sjulian			 * the old READ_PENDING, increment the readers, and
186870700Sjulian			 * set WRITE_PENDING. Either way we just add
186970700Sjulian			 * WRITE_PENDING to whatever we already had.
187070700Sjulian			 */
187170700Sjulian			add_arg += WRITE_PENDING;
187270700Sjulian		}
187370700Sjulian	}
187470700Sjulian	atomic_add_long(&ngq->q_flags, add_arg);
187570700Sjulian	/*
187670700Sjulian	 * We have successfully cleared the old pending flag, set the new one
187770700Sjulian	 * if it is needed, and incremented the appropriate active field.
187870700Sjulian	 * (all in one atomic addition.. wow)
187970700Sjulian	 */
188070700Sjulian	return (item);
188170700Sjulian}
188252419Sjulian
188370700Sjulian/*
188470700Sjulian * Queue a packet to be picked up by someone else.
188570700Sjulian * We really don't care who, but we can't or don't want to hang around
188670700Sjulian * to process it ourselves. We are probably an interrupt routine..
188770700Sjulian * 1 = writer, 0 = reader
188870700Sjulian * We should set something to indicate NETISR requested
188970700Sjulian * If it's the first item queued.
189070700Sjulian */
189170700Sjulian#define NGQRW_R 0
189270700Sjulian#define NGQRW_W 1
189370700Sjulianstatic __inline void
189470700Sjulianng_queue_rw(struct ng_queue * ngq, item_p  item, int rw)
189570700Sjulian{
189670700Sjulian	item->el_next = NULL;	/* maybe not needed */
189770700Sjulian	*ngq->last = item;
189870700Sjulian	/*
189970700Sjulian	 * If it was the first item in the queue then we need to
190070700Sjulian	 * set the last pointer and the type flags.
190170700Sjulian	 */
190270700Sjulian	if (ngq->last == &(ngq->queue)) {
190370700Sjulian		/*
190470700Sjulian		 * When called with constants for rw, the optimiser will
190570700Sjulian		 * remove the unneeded branch below.
190670700Sjulian		 */
190770700Sjulian		if (rw == NGQRW_W) {
190870700Sjulian			atomic_add_long(&ngq->q_flags, WRITE_PENDING);
190970700Sjulian		} else {
191070700Sjulian			atomic_add_long(&ngq->q_flags, READ_PENDING);
191170700Sjulian		}
191270700Sjulian	}
191370700Sjulian	ngq->last = &(item->el_next);
191470700Sjulian}
191552419Sjulian
191670700Sjulian
191752419Sjulian/*
191870700Sjulian * This function 'cheats' in that it first tries to 'grab' the use of the
191970700Sjulian * node, without going through the mutex. We can do this becasue of the
192070700Sjulian * semantics of the lock. The semantics include a clause that says that the
192170700Sjulian * value of the readers count is invalid if the WRITER_ACTIVE flag is set. It
192270700Sjulian * also says that the WRITER_ACTIVE flag cannot be set if the readers count
192370700Sjulian * is not zero. Note that this talks about what is valid to SET the
192470700Sjulian * WRITER_ACTIVE flag, because from the moment it is set, the value if the
192570700Sjulian * reader count is immaterial, and not valid. The two 'pending' flags have a
192670700Sjulian * similar effect, in that If they are orthogonal to the two active fields in
192770700Sjulian * how they are set, but if either is set, the attempted 'grab' need to be
192870700Sjulian * backed out because there is earlier work, and we maintain ordering in the
192970700Sjulian * queue. The result of this is that the reader request can try obtain use of
193070700Sjulian * the node with only a single atomic addition, and without any of the mutex
193170700Sjulian * overhead. If this fails the operation degenerates to the same as for other
193270700Sjulian * cases.
193370700Sjulian *
193452419Sjulian */
193570700Sjulianstatic __inline item_p
193670700Sjulianng_acquire_read(struct ng_queue *ngq, item_p item)
193752419Sjulian{
193852419Sjulian
193970700Sjulian	/* ######### Hack alert ######### */
194070700Sjulian	atomic_add_long(&ngq->q_flags, READER_INCREMENT);
194170700Sjulian	if ((ngq->q_flags & (~READER_MASK)) == 0) {
194270700Sjulian		/* Successfully grabbed node */
194370700Sjulian		return (item);
194470700Sjulian	}
194570700Sjulian	/* undo the damage if we didn't succeed */
194670700Sjulian	atomic_subtract_long(&ngq->q_flags, READER_INCREMENT);
194770700Sjulian
194870700Sjulian	/* ######### End Hack alert ######### */
194970700Sjulian	mtx_enter((&ngq->q_mtx), MTX_SPIN);
195069922Sjulian	/*
195170700Sjulian	 * Try again. Another processor (or interrupt for that matter) may
195270700Sjulian	 * have removed the last queued item that was stopping us from
195370700Sjulian	 * running, between the previous test, and the moment that we took
195470700Sjulian	 * the mutex. (Or maybe a writer completed.)
195569922Sjulian	 */
195670700Sjulian	if ((ngq->q_flags & (~READER_MASK)) == 0) {
195770700Sjulian		atomic_add_long(&ngq->q_flags, READER_INCREMENT);
195870700Sjulian		mtx_exit((&ngq->q_mtx), MTX_SPIN);
195970700Sjulian		return (item);
196070700Sjulian	}
196170700Sjulian
196270700Sjulian	/*
196370700Sjulian	 * Quick check that we are doing things right.
196470700Sjulian	 */
196570700Sjulian	if (ngq->q_flags & SINGLE_THREAD_ONLY) {
196670700Sjulian		panic("Calling single treaded queue incorrectly");
196770700Sjulian	}
196870700Sjulian
196970700Sjulian	/*
197070700Sjulian	 * and queue the request for later.
197170700Sjulian	 */
197271047Sjulian	item->el_flags |= NGQF_READER;
197370700Sjulian	ng_queue_rw(ngq, item, NGQRW_R);
197470700Sjulian
197570700Sjulian	/*
197670700Sjulian	 * Ok, so that's the item successfully queued for later. So now we
197770700Sjulian	 * see if we can dequeue something to run instead.
197870700Sjulian	 */
197970700Sjulian	item = ng_dequeue(ngq);
198070700Sjulian	mtx_exit(&(ngq->q_mtx), MTX_SPIN);
198170700Sjulian	return (item);
198270700Sjulian}
198370700Sjulian
198470700Sjulianstatic __inline item_p
198570700Sjulianng_acquire_write(struct ng_queue *ngq, item_p item)
198670700Sjulian{
198770700Sjulianrestart:
198870700Sjulian	mtx_enter(&(ngq->q_mtx), MTX_SPIN);
198970700Sjulian	/*
199070700Sjulian	 * If there are no readers, no writer, and no pending packets, then
199170700Sjulian	 * we can just go ahead. In all other situations we need to queue the
199270700Sjulian	 * request
199370700Sjulian	 */
199470700Sjulian	if ((ngq->q_flags & (~SINGLE_THREAD_ONLY)) == 0) {
199570700Sjulian		atomic_add_long(&ngq->q_flags, WRITER_ACTIVE);
199670700Sjulian		mtx_exit((&ngq->q_mtx), MTX_SPIN);
199770700Sjulian		if (ngq->q_flags & READER_MASK) {
199870700Sjulian			/* Collision with fast-track reader */
199970700Sjulian			atomic_add_long(&ngq->q_flags, -WRITER_ACTIVE);
200070700Sjulian			goto restart;
200169922Sjulian		}
200270700Sjulian
200370700Sjulian		return (item);
200452419Sjulian	}
200552419Sjulian
200670700Sjulian	/*
200770700Sjulian	 * and queue the request for later.
200870700Sjulian	 */
200971047Sjulian	item->el_flags &= ~NGQF_RW;
201070700Sjulian	ng_queue_rw(ngq, item, NGQRW_W);
201170700Sjulian
201270700Sjulian	/*
201370700Sjulian	 * Ok, so that's the item successfully queued for later. So now we
201470700Sjulian	 * see if we can dequeue something to run instead.
201570700Sjulian	 */
201670700Sjulian	item = ng_dequeue(ngq);
201770700Sjulian	mtx_exit(&(ngq->q_mtx), MTX_SPIN);
201870700Sjulian	return (item);
201970700Sjulian}
202070700Sjulian
202170700Sjulianstatic __inline void
202270700Sjulianng_leave_read(struct ng_queue *ngq)
202370700Sjulian{
202470700Sjulian	atomic_subtract_long(&ngq->q_flags, READER_INCREMENT);
202570700Sjulian}
202670700Sjulian
202770700Sjulianstatic __inline void
202870700Sjulianng_leave_write(struct ng_queue *ngq)
202970700Sjulian{
203070700Sjulian	atomic_subtract_long(&ngq->q_flags, WRITER_ACTIVE);
203170700Sjulian}
203270700Sjulian
203370700Sjulianstatic void
203470700Sjulianng_flush_input_queue(struct ng_queue * ngq)
203570700Sjulian{
203670700Sjulian	item_p item;
203770700Sjulian	u_int		add_arg;
203870700Sjulian	mtx_enter(&ngq->q_mtx, MTX_SPIN);
203970700Sjulian	for (;;) {
204070700Sjulian		/* Now take a look at what's on the queue */
204170700Sjulian		if (ngq->q_flags & READ_PENDING) {
204270700Sjulian			add_arg = -READ_PENDING;
204370700Sjulian		} else if (ngq->q_flags & WRITE_PENDING) {
204470700Sjulian			add_arg = -WRITE_PENDING;
204570700Sjulian		} else {
204670700Sjulian			break;
204770700Sjulian		}
204870700Sjulian
204970700Sjulian		item = ngq->queue;
205070700Sjulian		ngq->queue = item->el_next;
205170700Sjulian		if (ngq->last == &(item->el_next)) {
205270700Sjulian			ngq->last = &(ngq->queue);
205370700Sjulian		} else {
205471047Sjulian			if ((ngq->queue->el_flags & NGQF_RW) == NGQF_READER) {
205570700Sjulian				add_arg += READ_PENDING;
205670700Sjulian			} else {
205770700Sjulian				add_arg += WRITE_PENDING;
205870700Sjulian			}
205970700Sjulian		}
206070700Sjulian		atomic_add_long(&ngq->q_flags, add_arg);
206170700Sjulian
206270700Sjulian		mtx_exit(&ngq->q_mtx, MTX_SPIN);
206370700Sjulian		NG_FREE_ITEM(item);
206470700Sjulian		mtx_enter(&ngq->q_mtx, MTX_SPIN);
206570700Sjulian	}
206670700Sjulian	mtx_exit(&ngq->q_mtx, MTX_SPIN);
206770700Sjulian}
206870700Sjulian
206970700Sjulian/***********************************************************************
207070700Sjulian* Externally visible method for sending or queueing messages or data.
207170700Sjulian***********************************************************************/
207270700Sjulian
207370700Sjulian/*
207471849Sjulian * The module code should have filled out the item correctly by this stage:
207570700Sjulian * Common:
207670700Sjulian *    reference to destination node.
207770700Sjulian *    Reference to destination rcv hook if relevant.
207870700Sjulian * Data:
207970700Sjulian *    pointer to mbuf
208070700Sjulian *    pointer to metadata
208170700Sjulian * Control_Message:
208270700Sjulian *    pointer to msg.
208370700Sjulian *    ID of original sender node. (return address)
208471849Sjulian * Function:
208571849Sjulian *    Function pointer
208671849Sjulian *    void * argument
208771849Sjulian *    integer argument
208870700Sjulian *
208970700Sjulian * The nodes have several routines and macros to help with this task:
209070700Sjulian */
209170700Sjulian
209270700Sjulianint
209370700Sjulianng_snd_item(item_p item, int queue)
209470700Sjulian{
209571849Sjulian	hook_p hook = NGI_HOOK(item);
209671849Sjulian	node_p dest = NGI_NODE(item);
209770700Sjulian	int rw;
209870700Sjulian	int error = 0, ierror;
209970700Sjulian	item_p	oitem;
210070784Sjulian	struct ng_queue * ngq = &dest->nd_input_queue;
210170700Sjulian
210270784Sjulian#ifdef	NETGRAPH_DEBUG
210370700Sjulian        _ngi_check(item, __FILE__, __LINE__);
210470700Sjulian#endif
210570700Sjulian
210670700Sjulian	if (item == NULL) {
210771047Sjulian		TRAP_ERROR();
210870700Sjulian		return (EINVAL);	/* failed to get queue element */
210970700Sjulian	}
211070700Sjulian	if (dest == NULL) {
211170700Sjulian		NG_FREE_ITEM(item);
211271047Sjulian		TRAP_ERROR();
211370700Sjulian		return (EINVAL);	/* No address */
211470700Sjulian	}
211571047Sjulian	switch(item->el_flags & NGQF_TYPE) {
211671047Sjulian	case NGQF_DATA:
211769922Sjulian		/*
211870700Sjulian		 * DATA MESSAGE
211970700Sjulian		 * Delivered to a node via a non-optional hook.
212070700Sjulian		 * Both should be present in the item even though
212170700Sjulian		 * the node is derivable from the hook.
212270700Sjulian		 * References are held on both by the item.
212369922Sjulian		 */
212470700Sjulian		CHECK_DATA_MBUF(NGI_M(item));
212570700Sjulian		if (hook == NULL) {
212670700Sjulian			NG_FREE_ITEM(item);
212771047Sjulian			TRAP_ERROR();
212870700Sjulian			return(EINVAL);
212970700Sjulian		}
213070784Sjulian		if ((NG_HOOK_NOT_VALID(hook))
213170784Sjulian		|| (NG_NODE_NOT_VALID(NG_HOOK_NODE(hook)))) {
213270700Sjulian			NG_FREE_ITEM(item);
213370700Sjulian			return (ENOTCONN);
213469922Sjulian		}
213570784Sjulian		if ((hook->hk_flags & HK_QUEUE)) {
213670700Sjulian			queue = 1;
213770700Sjulian		}
213870700Sjulian		/* By default data is a reader in the locking scheme */
213970700Sjulian		item->el_flags |= NGQF_READER;
214070700Sjulian		rw = NGQRW_R;
214171047Sjulian		break;
214271047Sjulian	case NGQF_MESG:
214370700Sjulian		/*
214470700Sjulian		 * CONTROL MESSAGE
214570700Sjulian		 * Delivered to a node.
214670700Sjulian		 * Hook is optional.
214770700Sjulian		 * References are held by the item on the node and
214870700Sjulian		 * the hook if it is present.
214970700Sjulian		 */
215070784Sjulian		if (hook && (hook->hk_flags & HK_QUEUE)) {
215170700Sjulian			queue = 1;
215270700Sjulian		}
215370700Sjulian		/* Data messages count as writers unles explicitly exempted */
215470700Sjulian		if (NGI_MSG(item)->header.cmd & NGM_READONLY) {
215570700Sjulian			item->el_flags |= NGQF_READER;
215670700Sjulian			rw = NGQRW_R;
215770700Sjulian		} else {
215871047Sjulian			item->el_flags &= ~NGQF_RW;
215970700Sjulian			rw = NGQRW_W;
216070700Sjulian		}
216171047Sjulian		break;
216271047Sjulian	case NGQF_FN:
216371047Sjulian		item->el_flags &= ~NGQF_RW;
216471047Sjulian		rw = NGQRW_W;
216571047Sjulian		break;
216671047Sjulian	default:
216771047Sjulian		NG_FREE_ITEM(item);
216871047Sjulian		TRAP_ERROR();
216971047Sjulian		return (EINVAL);
217069922Sjulian	}
217170700Sjulian	/*
217270700Sjulian	 * If the node specifies single threading, force writer semantics
217370700Sjulian	 * Similarly the node may say one hook always produces writers.
217470700Sjulian	 * These are over-rides.
217570700Sjulian	 */
217670700Sjulian	if ((ngq->q_flags & SINGLE_THREAD_ONLY)
217770784Sjulian	|| (dest->nd_flags & NG_FORCE_WRITER)
217870784Sjulian	|| (hook && (hook->hk_flags & HK_FORCE_WRITER))) {
217970700Sjulian			rw = NGQRW_W;
218071047Sjulian			item->el_flags &= ~NGQF_READER;
218170700Sjulian	}
218270700Sjulian	if (queue) {
218370700Sjulian		/* Put it on the queue for that node*/
218470784Sjulian#ifdef	NETGRAPH_DEBUG
218570700Sjulian        _ngi_check(item, __FILE__, __LINE__);
218670700Sjulian#endif
218770700Sjulian		mtx_enter(&(ngq->q_mtx), MTX_SPIN);
218870700Sjulian		ng_queue_rw(ngq, item, rw);
218970700Sjulian		mtx_exit(&(ngq->q_mtx), MTX_SPIN);
219070700Sjulian		/*
219170700Sjulian		 * If there are active elements then we can rely on
219270700Sjulian		 * them. if not we should not rely on another packet
219370700Sjulian		 * coming here by another path,
219470700Sjulian		 * so it is best to put us in the netisr list.
219570700Sjulian		 */
219670700Sjulian		if ((ngq->q_flags & (READER_MASK|WRITER_ACTIVE)) == 0) {
219770700Sjulian			ng_setisr(ngq->q_node);
219870700Sjulian		}
219970700Sjulian		return (0);
220070700Sjulian	}
220170700Sjulian	/*
220270700Sjulian	 * Take a queue item and a node and see if we can apply the item to
220370700Sjulian	 * the node. We may end up getting a different item to apply instead.
220470700Sjulian	 * Will allow for a piggyback reply only in the case where
220570700Sjulian	 * there is no queueing.
220670700Sjulian	 */
220769922Sjulian
220870700Sjulian	oitem = item;
220970700Sjulian	/*
221070700Sjulian	 * We already decided how we will be queueud or treated.
221170700Sjulian	 * Try get the appropriate operating permission.
221270700Sjulian	 */
221370700Sjulian 	if (rw == NGQRW_R) {
221470700Sjulian		item = ng_acquire_read(ngq, item);
221570700Sjulian	} else {
221670700Sjulian		item = ng_acquire_write(ngq, item);
221770700Sjulian	}
221852419Sjulian
221970700Sjulian	/*
222070700Sjulian	 * May have come back with a different item.
222170700Sjulian	 * or maybe none at all. The one we started with will
222270700Sjulian	 * have been queued in thises cases.
222370700Sjulian	 */
222470700Sjulian	if (item == NULL) {
222570700Sjulian		return (0);
222670700Sjulian	}
222752419Sjulian
222870784Sjulian#ifdef	NETGRAPH_DEBUG
222970700Sjulian        _ngi_check(item, __FILE__, __LINE__);
223070700Sjulian#endif
223171849Sjulian	ierror = ng_apply_item(item); /* drops r/w lock when done */
223252419Sjulian
223370700Sjulian	/* only return an error if it was our initial item.. (compat hack) */
223470700Sjulian	if (oitem == item) {
223570700Sjulian		error = ierror;
223670700Sjulian	}
223770700Sjulian
223852419Sjulian	/*
223970700Sjulian	 * Now we've handled the packet we brought, (or a friend of it) let's
224070700Sjulian	 * look for any other packets that may have been queued up. We hold
224170700Sjulian	 * no locks, so if someone puts something in the queue after
224270700Sjulian	 * we check that it is empty, it is their problem
224370700Sjulian	 * to ensure it is processed. If we have the netisr thread cme in here
224470700Sjulian	 * while we still say we have stuff to do, we may get a boost
224570700Sjulian	 * in SMP systems. :-)
224652419Sjulian	 */
224770700Sjulian	for (;;) {
224870700Sjulian		/* quick hack to save all that mutex stuff */
224970700Sjulian		if ((ngq->q_flags & (WRITE_PENDING | READ_PENDING)) == 0) {
225070784Sjulian			if (dest->nd_flags & NG_WORKQ)
225170700Sjulian				ng_worklist_remove(dest);
225271849Sjulian			return (error);
225370700Sjulian		}
225471849Sjulian
225570700Sjulian		/*
225670700Sjulian		 * dequeue acquires and adjusts the input_queue as it dequeues
225770700Sjulian		 * packets. It acquires the rw lock as needed.
225870700Sjulian		 */
225970700Sjulian		mtx_enter(&ngq->q_mtx, MTX_SPIN);
226070700Sjulian		item = ng_dequeue(ngq);
226170700Sjulian		mtx_exit(&ngq->q_mtx, MTX_SPIN);
226270700Sjulian		if (!item) {
226370700Sjulian			/*
226470700Sjulian			 * If we have no work to do
226570700Sjulian			 * then we certainly don't need to be
226670700Sjulian			 * on the worklist.
226770700Sjulian			 */
226870784Sjulian			if (dest->nd_flags & NG_WORKQ)
226970700Sjulian				ng_worklist_remove(dest);
227071849Sjulian			return (error);
227170700Sjulian		}
227270700Sjulian
227370700Sjulian		/*
227470700Sjulian		 * We have the appropriate lock, so run the item.
227570700Sjulian		 * When finished it will drop the lock accordingly
227670700Sjulian		 */
227771849Sjulian		ierror = ng_apply_item(item);
227870700Sjulian
227970700Sjulian		/*
228070700Sjulian		 * only return an error if it was our initial
228170700Sjulian		 * item.. (compat hack)
228270700Sjulian		 */
228370700Sjulian		if (oitem == item) {
228470700Sjulian			error = ierror;
228570700Sjulian		}
228670700Sjulian	}
228771849Sjulian	return (error);
228852419Sjulian}
228952419Sjulian
229052419Sjulian/*
229170700Sjulian * We have an item that was possibly queued somewhere.
229270700Sjulian * It should contain all the information needed
229370700Sjulian * to run it on the appropriate node/hook.
229452419Sjulian */
229552419Sjulianstatic int
229671849Sjulianng_apply_item(item_p item)
229752419Sjulian{
229871849Sjulian	node_p	node;
229970700Sjulian	hook_p  hook;
230071849Sjulian	int	was_reader = ((item->el_flags & NGQF_RW));
230171849Sjulian	int	error = 0;
230270700Sjulian	ng_rcvdata_t *rcvdata;
230371885Sjulian	ng_rcvmsg_t *rcvmsg;
230452419Sjulian
230571849Sjulian	NGI_GET_HOOK(item, hook); /* clears stored hook */
230671849Sjulian	NGI_GET_NODE(item, node); /* clears stored node */
230770784Sjulian#ifdef	NETGRAPH_DEBUG
230870700Sjulian        _ngi_check(item, __FILE__, __LINE__);
230970700Sjulian#endif
231071047Sjulian	switch (item->el_flags & NGQF_TYPE) {
231170700Sjulian	case NGQF_DATA:
231270700Sjulian		/*
231370700Sjulian		 * Check things are still ok as when we were queued.
231470700Sjulian		 */
231570700Sjulian		if ((hook == NULL)
231670784Sjulian		|| NG_HOOK_NOT_VALID(hook)
231771885Sjulian		|| NG_NODE_NOT_VALID(node) ) {
231870700Sjulian			error = EIO;
231970700Sjulian			NG_FREE_ITEM(item);
232071885Sjulian			break;
232170700Sjulian		}
232271885Sjulian		/*
232371885Sjulian		 * If no receive method, just silently drop it.
232471885Sjulian		 * Give preference to the hook over-ride method
232571885Sjulian		 */
232671885Sjulian		if ((!(rcvdata = hook->hk_rcvdata))
232771885Sjulian		&& (!(rcvdata = NG_HOOK_NODE(hook)->nd_type->rcvdata))) {
232871885Sjulian			error = 0;
232971885Sjulian			NG_FREE_ITEM(item);
233071885Sjulian			break;
233171885Sjulian		}
233271885Sjulian		error = (*rcvdata)(hook, item);
233370700Sjulian		break;
233470700Sjulian	case NGQF_MESG:
233570700Sjulian		if (hook) {
233670784Sjulian			if (NG_HOOK_NOT_VALID(hook)) {
233771849Sjulian				/*
233871849Sjulian				 * The hook has been zapped then we can't
233971849Sjulian				 * use it. Immediatly drop its reference.
234071849Sjulian				 * The message may not need it.
234171849Sjulian				 */
234270784Sjulian				NG_HOOK_UNREF(hook);
234370700Sjulian				hook = NULL;
234470700Sjulian			}
234570700Sjulian		}
234670700Sjulian		/*
234770700Sjulian		 * Similarly, if the node is a zombie there is
234870700Sjulian		 * nothing we can do with it, drop everything.
234970700Sjulian		 */
235070784Sjulian		if (NG_NODE_NOT_VALID(node)) {
235171047Sjulian			TRAP_ERROR();
235270700Sjulian			error = EINVAL;
235370700Sjulian			NG_FREE_ITEM(item);
235470700Sjulian		} else {
235570700Sjulian			/*
235670700Sjulian			 * Call the appropriate message handler for the object.
235770700Sjulian			 * It is up to the message handler to free the message.
235870700Sjulian			 * If it's a generic message, handle it generically,
235970700Sjulian			 * otherwise call the type's message handler
236070700Sjulian			 * (if it exists)
236170700Sjulian			 * XXX (race). Remember that a queued message may
236270700Sjulian			 * reference a node or hook that has just been
236370700Sjulian			 * invalidated. It will exist as the queue code
236470700Sjulian			 * is holding a reference, but..
236570700Sjulian			 */
236670700Sjulian
236770700Sjulian			struct ng_mesg *msg = NGI_MSG(item);
236870700Sjulian
236971885Sjulian			/*
237071885Sjulian			 * check if the generic handler owns it.
237171885Sjulian			 */
237270700Sjulian			if ((msg->header.typecookie == NGM_GENERIC_COOKIE)
237370700Sjulian			&& ((msg->header.flags & NGF_RESP) == 0)) {
237470700Sjulian				error = ng_generic_msg(node, item, hook);
237571885Sjulian				break;
237670700Sjulian			}
237771885Sjulian			/*
237871885Sjulian			 * Now see if there is a handler (hook or node specific)
237971885Sjulian			 * in the target node. If none, silently discard.
238071885Sjulian			 */
238171885Sjulian			if (((!hook) || (!(rcvmsg = hook->hk_rcvmsg)))
238271885Sjulian			&& (!(rcvmsg = node->nd_type->rcvmsg))) {
238371885Sjulian				TRAP_ERROR();
238471885Sjulian				error = 0;
238571885Sjulian				NG_FREE_ITEM(item);
238671885Sjulian				break;
238771885Sjulian			}
238871885Sjulian			error = (*rcvmsg)(node, item, hook);
238970700Sjulian		}
239070700Sjulian		break;
239171047Sjulian	case NGQF_FN:
239271047Sjulian		/*
239371047Sjulian		 *  We have to implicitly trust the hook,
239471047Sjulian		 * as some of these are used for system purposes
239571849Sjulian		 * where the hook is invalid. In the case of
239671849Sjulian		 * the shutdown message we allow it to hit
239771849Sjulian		 * even if the node is invalid.
239871047Sjulian		 */
239971849Sjulian		if ((NG_NODE_NOT_VALID(node))
240071849Sjulian		&& (NGI_FN(item) != &ng_rmnode)) {
240171047Sjulian			TRAP_ERROR();
240271047Sjulian			error = EINVAL;
240371047Sjulian			break;
240471047Sjulian		}
240571849Sjulian		(*NGI_FN(item))(node, hook, NGI_ARG1(item), NGI_ARG2(item));
240671047Sjulian		NG_FREE_ITEM(item);
240771047Sjulian		break;
240871047Sjulian
240970700Sjulian	}
241070700Sjulian	/*
241170700Sjulian	 * We held references on some of the resources
241270700Sjulian	 * that we took from the item. Now that we have
241370700Sjulian	 * finished doing everything, drop those references.
241470700Sjulian	 */
241570700Sjulian	if (hook) {
241670784Sjulian		NG_HOOK_UNREF(hook);
241770700Sjulian	}
241870700Sjulian
241970700Sjulian	if (was_reader) {
242070784Sjulian		ng_leave_read(&node->nd_input_queue);
242170700Sjulian	} else {
242270784Sjulian		ng_leave_write(&node->nd_input_queue);
242370700Sjulian	}
242470784Sjulian	NG_NODE_UNREF(node);
242570700Sjulian	return (error);
242670700Sjulian}
242770700Sjulian
242870700Sjulian/***********************************************************************
242970700Sjulian * Implement the 'generic' control messages
243070700Sjulian ***********************************************************************/
243170700Sjulianstatic int
243270700Sjulianng_generic_msg(node_p here, item_p item, hook_p lasthook)
243370700Sjulian{
243470700Sjulian	int error = 0;
243570700Sjulian	struct ng_mesg *msg;
243670700Sjulian	struct ng_mesg *resp = NULL;
243770700Sjulian
243870700Sjulian	NGI_GET_MSG(item, msg);
243952419Sjulian	if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
244071047Sjulian		TRAP_ERROR();
244170700Sjulian		error = EINVAL;
244270700Sjulian		goto out;
244352419Sjulian	}
244452419Sjulian	switch (msg->header.cmd) {
244552419Sjulian	case NGM_SHUTDOWN:
244671849Sjulian		ng_rmnode(here, NULL, NULL, 0);
244752419Sjulian		break;
244852419Sjulian	case NGM_MKPEER:
244952419Sjulian	    {
245052419Sjulian		struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
245152419Sjulian
245252419Sjulian		if (msg->header.arglen != sizeof(*mkp)) {
245371047Sjulian			TRAP_ERROR();
245470700Sjulian			error = EINVAL;
245570700Sjulian			break;
245652419Sjulian		}
245752419Sjulian		mkp->type[sizeof(mkp->type) - 1] = '\0';
245852419Sjulian		mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
245952419Sjulian		mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
246052419Sjulian		error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
246152419Sjulian		break;
246252419Sjulian	    }
246352419Sjulian	case NGM_CONNECT:
246452419Sjulian	    {
246552419Sjulian		struct ngm_connect *const con =
246652419Sjulian			(struct ngm_connect *) msg->data;
246752419Sjulian		node_p node2;
246852419Sjulian
246952419Sjulian		if (msg->header.arglen != sizeof(*con)) {
247071047Sjulian			TRAP_ERROR();
247170700Sjulian			error = EINVAL;
247270700Sjulian			break;
247352419Sjulian		}
247452419Sjulian		con->path[sizeof(con->path) - 1] = '\0';
247552419Sjulian		con->ourhook[sizeof(con->ourhook) - 1] = '\0';
247652419Sjulian		con->peerhook[sizeof(con->peerhook) - 1] = '\0';
247770700Sjulian		/* Don't forget we get a reference.. */
247870700Sjulian		error = ng_path2noderef(here, con->path, &node2, NULL);
247952419Sjulian		if (error)
248052419Sjulian			break;
248152419Sjulian		error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
248270784Sjulian		NG_NODE_UNREF(node2);
248352419Sjulian		break;
248452419Sjulian	    }
248552419Sjulian	case NGM_NAME:
248652419Sjulian	    {
248752419Sjulian		struct ngm_name *const nam = (struct ngm_name *) msg->data;
248852419Sjulian
248952419Sjulian		if (msg->header.arglen != sizeof(*nam)) {
249071047Sjulian			TRAP_ERROR();
249170700Sjulian			error = EINVAL;
249270700Sjulian			break;
249352419Sjulian		}
249452419Sjulian		nam->name[sizeof(nam->name) - 1] = '\0';
249552419Sjulian		error = ng_name_node(here, nam->name);
249652419Sjulian		break;
249752419Sjulian	    }
249852419Sjulian	case NGM_RMHOOK:
249952419Sjulian	    {
250052419Sjulian		struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
250152419Sjulian		hook_p hook;
250252419Sjulian
250352419Sjulian		if (msg->header.arglen != sizeof(*rmh)) {
250471047Sjulian			TRAP_ERROR();
250570700Sjulian			error = EINVAL;
250670700Sjulian			break;
250752419Sjulian		}
250852419Sjulian		rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
250954096Sarchie		if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
251052419Sjulian			ng_destroy_hook(hook);
251152419Sjulian		break;
251252419Sjulian	    }
251352419Sjulian	case NGM_NODEINFO:
251452419Sjulian	    {
251552419Sjulian		struct nodeinfo *ni;
251652419Sjulian
251770700Sjulian		NG_MKRESPONSE(resp, msg, sizeof(*ni), M_NOWAIT);
251852419Sjulian		if (resp == NULL) {
251952419Sjulian			error = ENOMEM;
252052419Sjulian			break;
252152419Sjulian		}
252252419Sjulian
252352419Sjulian		/* Fill in node info */
252470700Sjulian		ni = (struct nodeinfo *) resp->data;
252570784Sjulian		if (NG_NODE_HAS_NAME(here))
252670784Sjulian			strncpy(ni->name, NG_NODE_NAME(here), NG_NODELEN);
252770784Sjulian		strncpy(ni->type, here->nd_type->name, NG_TYPELEN);
252852722Sjulian		ni->id = ng_node2ID(here);
252970784Sjulian		ni->hooks = here->nd_numhooks;
253052419Sjulian		break;
253152419Sjulian	    }
253252419Sjulian	case NGM_LISTHOOKS:
253352419Sjulian	    {
253470784Sjulian		const int nhooks = here->nd_numhooks;
253552419Sjulian		struct hooklist *hl;
253652419Sjulian		struct nodeinfo *ni;
253752419Sjulian		hook_p hook;
253852419Sjulian
253952419Sjulian		/* Get response struct */
254070700Sjulian		NG_MKRESPONSE(resp, msg, sizeof(*hl)
254170700Sjulian		    + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
254252419Sjulian		if (resp == NULL) {
254352419Sjulian			error = ENOMEM;
254452419Sjulian			break;
254552419Sjulian		}
254670700Sjulian		hl = (struct hooklist *) resp->data;
254752419Sjulian		ni = &hl->nodeinfo;
254852419Sjulian
254952419Sjulian		/* Fill in node info */
255070784Sjulian		if (NG_NODE_HAS_NAME(here))
255170784Sjulian			strncpy(ni->name, NG_NODE_NAME(here), NG_NODELEN);
255270784Sjulian		strncpy(ni->type, here->nd_type->name, NG_TYPELEN);
255352722Sjulian		ni->id = ng_node2ID(here);
255452419Sjulian
255552419Sjulian		/* Cycle through the linked list of hooks */
255652419Sjulian		ni->hooks = 0;
255770784Sjulian		LIST_FOREACH(hook, &here->nd_hooks, hk_hooks) {
255852419Sjulian			struct linkinfo *const link = &hl->link[ni->hooks];
255952419Sjulian
256052419Sjulian			if (ni->hooks >= nhooks) {
256152419Sjulian				log(LOG_ERR, "%s: number of %s changed\n",
256252419Sjulian				    __FUNCTION__, "hooks");
256352419Sjulian				break;
256452419Sjulian			}
256570784Sjulian			if (NG_HOOK_NOT_VALID(hook))
256652419Sjulian				continue;
256770784Sjulian			strncpy(link->ourhook, NG_HOOK_NAME(hook), NG_HOOKLEN);
256870784Sjulian			strncpy(link->peerhook,
256970784Sjulian				NG_PEER_HOOK_NAME(hook), NG_HOOKLEN);
257070784Sjulian			if (NG_PEER_NODE_NAME(hook)[0] != '\0')
257152419Sjulian				strncpy(link->nodeinfo.name,
257270784Sjulian				    NG_PEER_NODE_NAME(hook), NG_NODELEN);
257352419Sjulian			strncpy(link->nodeinfo.type,
257470784Sjulian			   NG_PEER_NODE(hook)->nd_type->name, NG_TYPELEN);
257570784Sjulian			link->nodeinfo.id = ng_node2ID(NG_PEER_NODE(hook));
257670784Sjulian			link->nodeinfo.hooks = NG_PEER_NODE(hook)->nd_numhooks;
257752419Sjulian			ni->hooks++;
257852419Sjulian		}
257952419Sjulian		break;
258052419Sjulian	    }
258152419Sjulian
258252419Sjulian	case NGM_LISTNAMES:
258352419Sjulian	case NGM_LISTNODES:
258452419Sjulian	    {
258552419Sjulian		const int unnamed = (msg->header.cmd == NGM_LISTNODES);
258652419Sjulian		struct namelist *nl;
258752419Sjulian		node_p node;
258852419Sjulian		int num = 0;
258952419Sjulian
259070700Sjulian		mtx_enter(&ng_nodelist_mtx, MTX_DEF);
259152419Sjulian		/* Count number of nodes */
259270784Sjulian		LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
259370912Sjulian			if (NG_NODE_IS_VALID(node)
259470912Sjulian			&& (unnamed || NG_NODE_HAS_NAME(node))) {
259552419Sjulian				num++;
259670912Sjulian			}
259752419Sjulian		}
259870700Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);
259952419Sjulian
260052419Sjulian		/* Get response struct */
260170700Sjulian		NG_MKRESPONSE(resp, msg, sizeof(*nl)
260270700Sjulian		    + (num * sizeof(struct nodeinfo)), M_NOWAIT);
260352419Sjulian		if (resp == NULL) {
260452419Sjulian			error = ENOMEM;
260552419Sjulian			break;
260652419Sjulian		}
260770700Sjulian		nl = (struct namelist *) resp->data;
260852419Sjulian
260952419Sjulian		/* Cycle through the linked list of nodes */
261052419Sjulian		nl->numnames = 0;
261170700Sjulian		mtx_enter(&ng_nodelist_mtx, MTX_DEF);
261270784Sjulian		LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
261352419Sjulian			struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
261452419Sjulian
261552419Sjulian			if (nl->numnames >= num) {
261652419Sjulian				log(LOG_ERR, "%s: number of %s changed\n",
261752419Sjulian				    __FUNCTION__, "nodes");
261852419Sjulian				break;
261952419Sjulian			}
262070784Sjulian			if (NG_NODE_NOT_VALID(node))
262152419Sjulian				continue;
262270784Sjulian			if (!unnamed && (! NG_NODE_HAS_NAME(node)))
262352419Sjulian				continue;
262470784Sjulian			if (NG_NODE_HAS_NAME(node))
262570784Sjulian				strncpy(np->name, NG_NODE_NAME(node), NG_NODELEN);
262670784Sjulian			strncpy(np->type, node->nd_type->name, NG_TYPELEN);
262752722Sjulian			np->id = ng_node2ID(node);
262870784Sjulian			np->hooks = node->nd_numhooks;
262952419Sjulian			nl->numnames++;
263052419Sjulian		}
263170700Sjulian		mtx_exit(&ng_nodelist_mtx, MTX_DEF);
263252419Sjulian		break;
263352419Sjulian	    }
263452419Sjulian
263552419Sjulian	case NGM_LISTTYPES:
263652419Sjulian	    {
263752419Sjulian		struct typelist *tl;
263852419Sjulian		struct ng_type *type;
263952419Sjulian		int num = 0;
264052419Sjulian
264170700Sjulian		mtx_enter(&ng_typelist_mtx, MTX_DEF);
264252419Sjulian		/* Count number of types */
264370912Sjulian		LIST_FOREACH(type, &ng_typelist, types) {
264452419Sjulian			num++;
264570912Sjulian		}
264670700Sjulian		mtx_exit(&ng_typelist_mtx, MTX_DEF);
264752419Sjulian
264852419Sjulian		/* Get response struct */
264970700Sjulian		NG_MKRESPONSE(resp, msg, sizeof(*tl)
265070700Sjulian		    + (num * sizeof(struct typeinfo)), M_NOWAIT);
265152419Sjulian		if (resp == NULL) {
265252419Sjulian			error = ENOMEM;
265352419Sjulian			break;
265452419Sjulian		}
265570700Sjulian		tl = (struct typelist *) resp->data;
265652419Sjulian
265752419Sjulian		/* Cycle through the linked list of types */
265852419Sjulian		tl->numtypes = 0;
265970700Sjulian		mtx_enter(&ng_typelist_mtx, MTX_DEF);
266070700Sjulian		LIST_FOREACH(type, &ng_typelist, types) {
266152419Sjulian			struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
266252419Sjulian
266352419Sjulian			if (tl->numtypes >= num) {
266452419Sjulian				log(LOG_ERR, "%s: number of %s changed\n",
266552419Sjulian				    __FUNCTION__, "types");
266652419Sjulian				break;
266752419Sjulian			}
266859879Sarchie			strncpy(tp->type_name, type->name, NG_TYPELEN);
266971603Sjulian			tp->numnodes = type->refs - 1; /* don't count list */
267052419Sjulian			tl->numtypes++;
267152419Sjulian		}
267270700Sjulian		mtx_exit(&ng_typelist_mtx, MTX_DEF);
267352419Sjulian		break;
267452419Sjulian	    }
267552419Sjulian
267653913Sarchie	case NGM_BINARY2ASCII:
267753913Sarchie	    {
267864510Sarchie		int bufSize = 20 * 1024;	/* XXX hard coded constant */
267953913Sarchie		const struct ng_parse_type *argstype;
268053913Sarchie		const struct ng_cmdlist *c;
268170700Sjulian		struct ng_mesg *binary, *ascii;
268253913Sarchie
268353913Sarchie		/* Data area must contain a valid netgraph message */
268453913Sarchie		binary = (struct ng_mesg *)msg->data;
268553913Sarchie		if (msg->header.arglen < sizeof(struct ng_mesg)
268670912Sjulian		    || (msg->header.arglen - sizeof(struct ng_mesg)
268770912Sjulian		      < binary->header.arglen)) {
268871047Sjulian			TRAP_ERROR();
268953913Sarchie			error = EINVAL;
269053913Sarchie			break;
269153913Sarchie		}
269253913Sarchie
269370700Sjulian		/* Get a response message with lots of room */
269470700Sjulian		NG_MKRESPONSE(resp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
269570159Sjulian		if (resp == NULL) {
269653913Sarchie			error = ENOMEM;
269753913Sarchie			break;
269853913Sarchie		}
269970700Sjulian		ascii = (struct ng_mesg *)resp->data;
270053913Sarchie
270153913Sarchie		/* Copy binary message header to response message payload */
270253913Sarchie		bcopy(binary, ascii, sizeof(*binary));
270353913Sarchie
270453913Sarchie		/* Find command by matching typecookie and command number */
270570784Sjulian		for (c = here->nd_type->cmdlist;
270653913Sarchie		    c != NULL && c->name != NULL; c++) {
270753913Sarchie			if (binary->header.typecookie == c->cookie
270853913Sarchie			    && binary->header.cmd == c->cmd)
270953913Sarchie				break;
271053913Sarchie		}
271153913Sarchie		if (c == NULL || c->name == NULL) {
271253913Sarchie			for (c = ng_generic_cmds; c->name != NULL; c++) {
271353913Sarchie				if (binary->header.typecookie == c->cookie
271453913Sarchie				    && binary->header.cmd == c->cmd)
271553913Sarchie					break;
271653913Sarchie			}
271753913Sarchie			if (c->name == NULL) {
271870700Sjulian				NG_FREE_MSG(resp);
271953913Sarchie				error = ENOSYS;
272053913Sarchie				break;
272153913Sarchie			}
272253913Sarchie		}
272353913Sarchie
272453913Sarchie		/* Convert command name to ASCII */
272553913Sarchie		snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
272653913Sarchie		    "%s", c->name);
272753913Sarchie
272853913Sarchie		/* Convert command arguments to ASCII */
272953913Sarchie		argstype = (binary->header.flags & NGF_RESP) ?
273053913Sarchie		    c->respType : c->mesgType;
273170912Sjulian		if (argstype == NULL) {
273253913Sarchie			*ascii->data = '\0';
273370912Sjulian		} else {
273453913Sarchie			if ((error = ng_unparse(argstype,
273553913Sarchie			    (u_char *)binary->data,
273653913Sarchie			    ascii->data, bufSize)) != 0) {
273770700Sjulian				NG_FREE_MSG(resp);
273853913Sarchie				break;
273953913Sarchie			}
274053913Sarchie		}
274153913Sarchie
274253913Sarchie		/* Return the result as struct ng_mesg plus ASCII string */
274353913Sarchie		bufSize = strlen(ascii->data) + 1;
274453913Sarchie		ascii->header.arglen = bufSize;
274570700Sjulian		resp->header.arglen = sizeof(*ascii) + bufSize;
274653913Sarchie		break;
274753913Sarchie	    }
274853913Sarchie
274953913Sarchie	case NGM_ASCII2BINARY:
275053913Sarchie	    {
275153913Sarchie		int bufSize = 2000;	/* XXX hard coded constant */
275253913Sarchie		const struct ng_cmdlist *c;
275353913Sarchie		const struct ng_parse_type *argstype;
275470700Sjulian		struct ng_mesg *ascii, *binary;
275559178Sarchie		int off = 0;
275653913Sarchie
275753913Sarchie		/* Data area must contain at least a struct ng_mesg + '\0' */
275853913Sarchie		ascii = (struct ng_mesg *)msg->data;
275970912Sjulian		if ((msg->header.arglen < sizeof(*ascii) + 1)
276070912Sjulian		    || (ascii->header.arglen < 1)
276170912Sjulian		    || (msg->header.arglen
276270912Sjulian		      < sizeof(*ascii) + ascii->header.arglen)) {
276371047Sjulian			TRAP_ERROR();
276453913Sarchie			error = EINVAL;
276553913Sarchie			break;
276653913Sarchie		}
276753913Sarchie		ascii->data[ascii->header.arglen - 1] = '\0';
276853913Sarchie
276970700Sjulian		/* Get a response message with lots of room */
277070700Sjulian		NG_MKRESPONSE(resp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
277170159Sjulian		if (resp == NULL) {
277253913Sarchie			error = ENOMEM;
277353913Sarchie			break;
277453913Sarchie		}
277570700Sjulian		binary = (struct ng_mesg *)resp->data;
277653913Sarchie
277753913Sarchie		/* Copy ASCII message header to response message payload */
277853913Sarchie		bcopy(ascii, binary, sizeof(*ascii));
277953913Sarchie
278053913Sarchie		/* Find command by matching ASCII command string */
278170784Sjulian		for (c = here->nd_type->cmdlist;
278253913Sarchie		    c != NULL && c->name != NULL; c++) {
278353913Sarchie			if (strcmp(ascii->header.cmdstr, c->name) == 0)
278453913Sarchie				break;
278553913Sarchie		}
278653913Sarchie		if (c == NULL || c->name == NULL) {
278753913Sarchie			for (c = ng_generic_cmds; c->name != NULL; c++) {
278853913Sarchie				if (strcmp(ascii->header.cmdstr, c->name) == 0)
278953913Sarchie					break;
279053913Sarchie			}
279153913Sarchie			if (c->name == NULL) {
279270700Sjulian				NG_FREE_MSG(resp);
279353913Sarchie				error = ENOSYS;
279453913Sarchie				break;
279553913Sarchie			}
279653913Sarchie		}
279753913Sarchie
279853913Sarchie		/* Convert command name to binary */
279953913Sarchie		binary->header.cmd = c->cmd;
280053913Sarchie		binary->header.typecookie = c->cookie;
280153913Sarchie
280253913Sarchie		/* Convert command arguments to binary */
280353913Sarchie		argstype = (binary->header.flags & NGF_RESP) ?
280453913Sarchie		    c->respType : c->mesgType;
280570912Sjulian		if (argstype == NULL) {
280653913Sarchie			bufSize = 0;
280770912Sjulian		} else {
280853913Sarchie			if ((error = ng_parse(argstype, ascii->data,
280953913Sarchie			    &off, (u_char *)binary->data, &bufSize)) != 0) {
281070700Sjulian				NG_FREE_MSG(resp);
281153913Sarchie				break;
281253913Sarchie			}
281353913Sarchie		}
281453913Sarchie
281553913Sarchie		/* Return the result */
281653913Sarchie		binary->header.arglen = bufSize;
281770700Sjulian		resp->header.arglen = sizeof(*binary) + bufSize;
281853913Sarchie		break;
281953913Sarchie	    }
282053913Sarchie
282162471Sphk	case NGM_TEXT_CONFIG:
282252419Sjulian	case NGM_TEXT_STATUS:
282352419Sjulian		/*
282452419Sjulian		 * This one is tricky as it passes the command down to the
282552419Sjulian		 * actual node, even though it is a generic type command.
282670700Sjulian		 * This means we must assume that the item/msg is already freed
282752419Sjulian		 * when control passes back to us.
282852419Sjulian		 */
282970784Sjulian		if (here->nd_type->rcvmsg != NULL) {
283070700Sjulian			NGI_MSG(item) = msg; /* put it back as we found it */
283170784Sjulian			return((*here->nd_type->rcvmsg)(here, item, lasthook));
283252419Sjulian		}
283352419Sjulian		/* Fall through if rcvmsg not supported */
283452419Sjulian	default:
283571047Sjulian		TRAP_ERROR();
283652419Sjulian		error = EINVAL;
283752419Sjulian	}
283870700Sjulian	/*
283970700Sjulian	 * Sometimes a generic message may be statically allocated
284070700Sjulian	 * to avoid problems with allocating when in tight memeory situations.
284170700Sjulian	 * Don't free it if it is so.
284270700Sjulian	 * I break them appart here, because erros may cause a free if the item
284370700Sjulian	 * in which case we'd be doing it twice.
284470700Sjulian	 * they are kept together above, to simplify freeing.
284570700Sjulian	 */
284670700Sjulianout:
284770700Sjulian	NG_RESPOND_MSG(error, here, item, resp);
284871849Sjulian	if (msg)
284970700Sjulian		NG_FREE_MSG(msg);
285052419Sjulian	return (error);
285152419Sjulian}
285252419Sjulian
285352419Sjulian/*
285459879Sarchie * Copy a 'meta'.
285559879Sarchie *
285659879Sarchie * Returns new meta, or NULL if original meta is NULL or ENOMEM.
285759879Sarchie */
285859879Sarchiemeta_p
285959879Sarchieng_copy_meta(meta_p meta)
286059879Sarchie{
286159879Sarchie	meta_p meta2;
286259879Sarchie
286359879Sarchie	if (meta == NULL)
286459879Sarchie		return (NULL);
286570700Sjulian	MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH_META, M_NOWAIT);
286659879Sarchie	if (meta2 == NULL)
286759879Sarchie		return (NULL);
286859879Sarchie	meta2->allocated_len = meta->used_len;
286959879Sarchie	bcopy(meta, meta2, meta->used_len);
287059879Sarchie	return (meta2);
287159879Sarchie}
287259879Sarchie
287352419Sjulian/************************************************************************
287452419Sjulian			Module routines
287552419Sjulian************************************************************************/
287652419Sjulian
287752419Sjulian/*
287852419Sjulian * Handle the loading/unloading of a netgraph node type module
287952419Sjulian */
288052419Sjulianint
288152419Sjulianng_mod_event(module_t mod, int event, void *data)
288252419Sjulian{
288352419Sjulian	struct ng_type *const type = data;
288452419Sjulian	int s, error = 0;
288552419Sjulian
288652419Sjulian	switch (event) {
288752419Sjulian	case MOD_LOAD:
288852419Sjulian
288952419Sjulian		/* Register new netgraph node type */
289052419Sjulian		s = splnet();
289152419Sjulian		if ((error = ng_newtype(type)) != 0) {
289252419Sjulian			splx(s);
289352419Sjulian			break;
289452419Sjulian		}
289552419Sjulian
289652419Sjulian		/* Call type specific code */
289752419Sjulian		if (type->mod_event != NULL)
289870700Sjulian			if ((error = (*type->mod_event)(mod, event, data))) {
289970700Sjulian				mtx_enter(&ng_typelist_mtx, MTX_DEF);
290071603Sjulian				type->refs--;	/* undo it */
290152419Sjulian				LIST_REMOVE(type, types);
290270700Sjulian				mtx_exit(&ng_typelist_mtx, MTX_DEF);
290370700Sjulian			}
290452419Sjulian		splx(s);
290552419Sjulian		break;
290652419Sjulian
290752419Sjulian	case MOD_UNLOAD:
290852419Sjulian		s = splnet();
290971603Sjulian		if (type->refs > 1) {		/* make sure no nodes exist! */
291052419Sjulian			error = EBUSY;
291171603Sjulian		} else {
291271603Sjulian			if (type->refs == 0) {
291371603Sjulian				/* failed load, nothing to undo */
291471603Sjulian				splx(s);
291571603Sjulian				break;
291671603Sjulian			}
291752419Sjulian			if (type->mod_event != NULL) {	/* check with type */
291852419Sjulian				error = (*type->mod_event)(mod, event, data);
291952419Sjulian				if (error != 0) {	/* type refuses.. */
292052419Sjulian					splx(s);
292152419Sjulian					break;
292252419Sjulian				}
292352419Sjulian			}
292470700Sjulian			mtx_enter(&ng_typelist_mtx, MTX_DEF);
292552419Sjulian			LIST_REMOVE(type, types);
292670700Sjulian			mtx_exit(&ng_typelist_mtx, MTX_DEF);
292752419Sjulian		}
292852419Sjulian		splx(s);
292952419Sjulian		break;
293052419Sjulian
293152419Sjulian	default:
293252419Sjulian		if (type->mod_event != NULL)
293352419Sjulian			error = (*type->mod_event)(mod, event, data);
293452419Sjulian		else
293552419Sjulian			error = 0;		/* XXX ? */
293652419Sjulian		break;
293752419Sjulian	}
293852419Sjulian	return (error);
293952419Sjulian}
294052419Sjulian
294152419Sjulian/*
294252419Sjulian * Handle loading and unloading for this code.
294352419Sjulian * The only thing we need to link into is the NETISR strucure.
294452419Sjulian */
294552419Sjulianstatic int
294652419Sjulianngb_mod_event(module_t mod, int event, void *data)
294752419Sjulian{
294852419Sjulian	int s, error = 0;
294952419Sjulian
295052419Sjulian	switch (event) {
295152419Sjulian	case MOD_LOAD:
295252419Sjulian		/* Register line discipline */
295370700Sjulian		mtx_init(&ng_worklist_mtx, "netgraph worklist mutex", 0);
295470700Sjulian		mtx_init(&ng_typelist_mtx, "netgraph types mutex", 0);
295570700Sjulian		mtx_init(&ng_nodelist_mtx, "netgraph nodelist mutex", 0);
295670700Sjulian		mtx_init(&ng_idhash_mtx, "netgraph idhash mutex", 0);
295770700Sjulian		mtx_init(&ngq_mtx, "netgraph netisr mutex", 0);
295852419Sjulian		s = splimp();
295952419Sjulian		error = register_netisr(NETISR_NETGRAPH, ngintr);
296052419Sjulian		splx(s);
296152419Sjulian		break;
296252419Sjulian	case MOD_UNLOAD:
296352419Sjulian		/* You cant unload it because an interface may be using it.  */
296452419Sjulian		error = EBUSY;
296552419Sjulian		break;
296652419Sjulian	default:
296752419Sjulian		error = EOPNOTSUPP;
296852419Sjulian		break;
296952419Sjulian	}
297052419Sjulian	return (error);
297152419Sjulian}
297252419Sjulian
297352419Sjulianstatic moduledata_t netgraph_mod = {
297452419Sjulian	"netgraph",
297552419Sjulian	ngb_mod_event,
297652419Sjulian	(NULL)
297752419Sjulian};
297852419SjulianDECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
297952419Sjulian
298052419Sjulian/************************************************************************
298170700Sjulian			Queue element get/free routines
298252419Sjulian************************************************************************/
298352419Sjulian
298452419Sjulian
298570700Sjulianstatic int			allocated;	/* number of items malloc'd */
298670700Sjulianstatic int			maxalloc = 128;	/* limit the damage of a leak */
298770700Sjulianstatic const int		ngqfreemax = 64;/* cache at most this many */
298870700Sjulianstatic const int		ngqfreelow = 4; /* try malloc if free < this */
298970700Sjulianstatic volatile int		ngqfreesize;	/* number of cached entries */
299070784Sjulian#ifdef	NETGRAPH_DEBUG
299170700Sjulianstatic TAILQ_HEAD(, ng_item) ng_itemlist = TAILQ_HEAD_INITIALIZER(ng_itemlist);
299270700Sjulian#endif
299352419Sjulian/*
299452419Sjulian * Get a queue entry
299570700Sjulian * This is usually called when a packet first enters netgraph.
299670700Sjulian * By definition, this is usually from an interrupt, or from a user.
299770700Sjulian * Users are not so important, but try be quick for the times that it's
299870700Sjulian * an interrupt. Use atomic operations to cope with collisions
299970700Sjulian * with interrupts and other processors. Assumes MALLOC is SMP safe.
300070700Sjulian * XXX If reserve is low, we should try to get 2 from malloc as this
300170700Sjulian * would indicate it often fails.
300252419Sjulian */
300370700Sjulianstatic item_p
300452419Sjulianng_getqblk(void)
300552419Sjulian{
300670700Sjulian	item_p item = NULL;
300752419Sjulian
300870700Sjulian	/*
300970700Sjulian	 * Try get a cached queue block, or else allocate a new one
301070700Sjulian	 * If we are less than our reserve, try malloc. If malloc
301170700Sjulian	 * fails, then that's what the reserve is for...
301270700Sjulian	 * Don't completely trust ngqfreesize, as it is subject
301370700Sjulian	 * to races.. (it'll eventually catch up but may be out by one or two
301470700Sjulian	 * for brief moments(under SMP or interrupts).
301570700Sjulian	 * ngqfree is the final arbiter. We have our little reserve
301670700Sjulian	 * because we use M_NOWAIT for malloc. This just helps us
301770700Sjulian	 * avoid dropping packets while not increasing the time
301871650Sjulian	 * we take to service the interrupt (on average) (I hope).
301970700Sjulian	 */
302070700Sjulian	for (;;) {
302170700Sjulian		if ((ngqfreesize < ngqfreelow) || (ngqfree == NULL)) {
302270700Sjulian			if (allocated < maxalloc) {  /* don't leak forever */
302370700Sjulian				MALLOC(item, item_p ,
302470700Sjulian				    sizeof(*item), M_NETGRAPH_ITEM,
302570700Sjulian				    (M_NOWAIT | M_ZERO));
302670700Sjulian				if (item) {
302770784Sjulian#ifdef	NETGRAPH_DEBUG
302870700Sjulian					TAILQ_INSERT_TAIL(&ng_itemlist,
302970700Sjulian								item, all);
303070784Sjulian#endif	/* NETGRAPH_DEBUG */
303170700Sjulian					atomic_add_int(&allocated, 1);
303270700Sjulian					break;
303370700Sjulian				}
303470700Sjulian			}
303570700Sjulian		}
303652419Sjulian
303770700Sjulian		/*
303870700Sjulian		 * We didn't or couldn't malloc.
303970700Sjulian		 * try get one from our cache.
304070700Sjulian		 * item must be NULL to get here.
304170700Sjulian		 */
304270700Sjulian		if ((item = ngqfree) != NULL) {
304370700Sjulian			/*
304470700Sjulian			 * Atomically try grab the first item
304570700Sjulian			 * and put it's successor in its place.
304670700Sjulian			 * If we fail, just try again.. someone else
304770700Sjulian			 * beat us to this one or freed one.
304870700Sjulian			 * Don't worry about races with ngqfreesize.
304970700Sjulian			 * Close enough is good enough..
305070700Sjulian			 */
305170700Sjulian			if (atomic_cmpset_ptr(&ngqfree, item, item->el_next)) {
305270700Sjulian				atomic_subtract_int(&ngqfreesize, 1);
305371650Sjulian				item->el_flags &= ~NGQF_FREE;
305470700Sjulian				break;
305570700Sjulian			}
305671650Sjulian			/*
305771650Sjulian			 * something got there before we did.. try again
305871650Sjulian			 * (go around the loop again)
305971650Sjulian			 */
306070700Sjulian			item = NULL;
306170700Sjulian		} else {
306270700Sjulian			/* We really ran out */
306370700Sjulian			break;
306452419Sjulian		}
306552419Sjulian	}
306670700Sjulian	return (item);
306752419Sjulian}
306852419Sjulian
306952419Sjulian/*
307052419Sjulian * Release a queue entry
307152419Sjulian */
307270700Sjulianvoid
307370700Sjulianng_free_item(item_p item)
307452419Sjulian{
307552419Sjulian
307670700Sjulian	/*
307770700Sjulian	 * The item may hold resources on it's own. We need to free
307870700Sjulian	 * these before we can free the item. What they are depends upon
307970700Sjulian	 * what kind of item it is. it is important that nodes zero
308070700Sjulian	 * out pointers to resources that they remove from the item
308170700Sjulian	 * or we release them again here.
308270700Sjulian	 */
308370700Sjulian	if (item->el_flags & NGQF_FREE) {
308470700Sjulian		panic(" Freeing free queue item");
308552419Sjulian	}
308671047Sjulian	switch (item->el_flags & NGQF_TYPE) {
308770700Sjulian	case NGQF_DATA:
308870700Sjulian		/* If we have an mbuf and metadata still attached.. */
308970700Sjulian		NG_FREE_M(_NGI_M(item));
309070700Sjulian		NG_FREE_META(_NGI_META(item));
309170700Sjulian		break;
309270700Sjulian	case NGQF_MESG:
309370700Sjulian		_NGI_RETADDR(item) = NULL;
309470700Sjulian		NG_FREE_MSG(_NGI_MSG(item));
309570700Sjulian		break;
309671047Sjulian	case NGQF_FN:
309771047Sjulian		/* nothing to free really, */
309871047Sjulian		_NGI_FN(item) = NULL;
309971047Sjulian		_NGI_ARG1(item) = NULL;
310071047Sjulian		_NGI_ARG2(item) = 0;
310171047Sjulian	case NGQF_UNDEF:
310252419Sjulian	}
310371849Sjulian	/* If we still have a node or hook referenced... */
310471849Sjulian	_NGI_CLR_NODE(item);
310571849Sjulian	_NGI_CLR_HOOK(item);
310670700Sjulian	item->el_flags |= NGQF_FREE;
310752419Sjulian
310870700Sjulian	/*
310970700Sjulian	 * We have freed any resources held by the item.
311070700Sjulian	 * now we can free the item itself.
311170700Sjulian	 */
311270700Sjulian	if (ngqfreesize < ngqfreemax) { /* don't worry about races */
311370700Sjulian		for (;;) {
311470700Sjulian			item->el_next = ngqfree;
311570700Sjulian			if (atomic_cmpset_ptr(&ngqfree, item->el_next, item)) {
311670700Sjulian				break;
311770700Sjulian			}
311870700Sjulian		}
311970700Sjulian		atomic_add_int(&ngqfreesize, 1);
312070700Sjulian	} else {
312170700Sjulian		/* This is the only place that should use this Macro */
312270784Sjulian#ifdef	NETGRAPH_DEBUG
312370700Sjulian		TAILQ_REMOVE(&ng_itemlist, item, all);
312470784Sjulian#endif	/* NETGRAPH_DEBUG */
312570700Sjulian		NG_FREE_ITEM_REAL(item);
312670700Sjulian		atomic_subtract_int(&allocated, 1);
312770700Sjulian	}
312870700Sjulian}
312952419Sjulian
313070784Sjulian#ifdef	NETGRAPH_DEBUG
313170700Sjulianvoid
313270784Sjuliandumphook (hook_p hook, char *file, int line)
313370784Sjulian{
313470784Sjulian	printf("hook: name %s, %d refs, Last touched:\n",
313570784Sjulian		_NG_HOOK_NAME(hook), hook->hk_refs);
313670784Sjulian	printf("	Last active @ %s, line %d\n",
313770784Sjulian		hook->lastfile, hook->lastline);
313870784Sjulian	if (line) {
313970784Sjulian		printf(" problem discovered at file %s, line %d\n", file, line);
314070784Sjulian	}
314170784Sjulian}
314270784Sjulian
314370784Sjulianvoid
314470784Sjuliandumpnode(node_p node, char *file, int line)
314570784Sjulian{
314670784Sjulian	printf("node: ID [%x]: type '%s', %d hooks, flags 0x%x, %d refs, %s:\n",
314771047Sjulian		_NG_NODE_ID(node), node->nd_type->name,
314870784Sjulian		node->nd_numhooks, node->nd_flags,
314970784Sjulian		node->nd_refs, node->nd_name);
315070784Sjulian	printf("	Last active @ %s, line %d\n",
315170784Sjulian		node->lastfile, node->lastline);
315270784Sjulian	if (line) {
315370784Sjulian		printf(" problem discovered at file %s, line %d\n", file, line);
315470784Sjulian	}
315570784Sjulian}
315670784Sjulian
315770784Sjulianvoid
315870700Sjuliandumpitem(item_p item, char *file, int line)
315970700Sjulian{
316070700Sjulian	if (item->el_flags & NGQF_FREE) {
316170700Sjulian		printf(" Free item, freed at %s, line %d\n",
316270700Sjulian			item->lastfile, item->lastline);
316352419Sjulian	} else {
316470700Sjulian		printf(" ACTIVE item, last used at %s, line %d",
316570700Sjulian			item->lastfile, item->lastline);
316671047Sjulian		switch(item->el_flags & NGQF_TYPE) {
316771047Sjulian		case NGQF_DATA:
316871047Sjulian			printf(" - [data]\n");
316971047Sjulian			break;
317071047Sjulian		case NGQF_MESG:
317170700Sjulian			printf(" - retaddr[%d]:\n", _NGI_RETADDR(item));
317271047Sjulian			break;
317371047Sjulian		case NGQF_FN:
317471047Sjulian			printf(" - fn@%p (%p, %p, %p, %d (%x))\n",
317571047Sjulian				item->body.fn.fn_fn,
317671849Sjulian				NGI_NODE(item),
317771849Sjulian				NGI_HOOK(item),
317871047Sjulian				item->body.fn.fn_arg1,
317971047Sjulian				item->body.fn.fn_arg2,
318071047Sjulian				item->body.fn.fn_arg2);
318171047Sjulian			break;
318271047Sjulian		case NGQF_UNDEF:
318371047Sjulian			printf(" - UNDEFINED!\n");
318470700Sjulian		}
318552419Sjulian	}
318670784Sjulian	if (line) {
318770784Sjulian		printf(" problem discovered at file %s, line %d\n", file, line);
318871849Sjulian		if (NGI_NODE(item)) {
318970784Sjulian			printf("node %p ([%x])\n",
319071849Sjulian				NGI_NODE(item), ng_node2ID(NGI_NODE(item)));
319170784Sjulian		}
319270784Sjulian	}
319370700Sjulian}
319452419Sjulian
319570784Sjulianstatic void
319670784Sjulianng_dumpitems(void)
319770784Sjulian{
319870784Sjulian	item_p item;
319970784Sjulian	int i = 1;
320070784Sjulian	TAILQ_FOREACH(item, &ng_itemlist, all) {
320170784Sjulian		printf("[%d] ", i++);
320270784Sjulian		dumpitem(item, NULL, 0);
320370784Sjulian	}
320470784Sjulian}
320570784Sjulian
320670784Sjulianstatic void
320770784Sjulianng_dumpnodes(void)
320870784Sjulian{
320970784Sjulian	node_p node;
321070784Sjulian	int i = 1;
321170784Sjulian	SLIST_FOREACH(node, &ng_allnodes, nd_all) {
321270784Sjulian		printf("[%d] ", i++);
321370784Sjulian		dumpnode(node, NULL, 0);
321470784Sjulian	}
321570784Sjulian}
321670784Sjulian
321770784Sjulianstatic void
321870784Sjulianng_dumphooks(void)
321970784Sjulian{
322070784Sjulian	hook_p hook;
322170784Sjulian	int i = 1;
322270784Sjulian	SLIST_FOREACH(hook, &ng_allhooks, hk_all) {
322370784Sjulian		printf("[%d] ", i++);
322470784Sjulian		dumphook(hook, NULL, 0);
322570784Sjulian	}
322670784Sjulian}
322770784Sjulian
322870700Sjulianstatic int
322970700Sjuliansysctl_debug_ng_dump_items(SYSCTL_HANDLER_ARGS)
323070700Sjulian{
323170700Sjulian	int error;
323270700Sjulian	int val;
323370700Sjulian	int i;
323470700Sjulian
323570700Sjulian	val = allocated;
323670700Sjulian	i = 1;
323770700Sjulian	error = sysctl_handle_int(oidp, &val, sizeof(int), req);
323871047Sjulian	if (error != 0 || req->newptr == NULL)
323971047Sjulian		return (error);
324071047Sjulian	if (val == 42) {
324170784Sjulian		ng_dumpitems();
324270784Sjulian		ng_dumpnodes();
324370784Sjulian		ng_dumphooks();
324470700Sjulian	}
324571047Sjulian	return (0);
324652419Sjulian}
324752419Sjulian
324871047SjulianSYSCTL_PROC(_debug, OID_AUTO, ng_dump_items, CTLTYPE_INT | CTLFLAG_RW,
324971047Sjulian    0, sizeof(int), sysctl_debug_ng_dump_items, "I", "Number of allocated items");
325070784Sjulian#endif	/* NETGRAPH_DEBUG */
325170700Sjulian
325270700Sjulian
325370700Sjulian/***********************************************************************
325470700Sjulian* Worklist routines
325570700Sjulian**********************************************************************/
325670700Sjulian/* NETISR thread enters here */
325752419Sjulian/*
325870700Sjulian * Pick a node off the list of nodes with work,
325970700Sjulian * try get an item to process off it.
326070700Sjulian * If there are no more, remove the node from the list.
326152419Sjulian */
326270700Sjulianstatic void
326370700Sjulianngintr(void)
326452419Sjulian{
326570700Sjulian	item_p item;
326670700Sjulian	node_p  node = NULL;
326752419Sjulian
326870700Sjulian	for (;;) {
326971849Sjulian		mtx_enter(&ng_worklist_mtx, MTX_DEF);
327070700Sjulian		node = TAILQ_FIRST(&ng_worklist);
327170700Sjulian		if (!node) {
327271849Sjulian			mtx_exit(&ng_worklist_mtx, MTX_DEF);
327370700Sjulian			break;
327469922Sjulian		}
327570784Sjulian		TAILQ_REMOVE(&ng_worklist, node, nd_work);
327671849Sjulian		mtx_exit(&ng_worklist_mtx, MTX_DEF);
327770700Sjulian		/*
327870700Sjulian		 * We have the node. We also take over the reference
327970700Sjulian		 * that the list had on it.
328070700Sjulian		 * Now process as much as you can, until it won't
328170700Sjulian		 * let you have another item off the queue.
328270700Sjulian		 * All this time, keep the reference
328370700Sjulian		 * that lets us be sure that the node still exists.
328470700Sjulian		 * Let the reference go at the last minute.
328570700Sjulian		 */
328670700Sjulian		for (;;) {
328770784Sjulian			mtx_enter(&node->nd_input_queue.q_mtx, MTX_SPIN);
328870784Sjulian			item = ng_dequeue(&node->nd_input_queue);
328970700Sjulian			if (item == NULL) {
329070700Sjulian				/*
329170700Sjulian				 * Say we are on the queue as long as
329270700Sjulian				 * we are processing it here.
329370700Sjulian				 * it probably wouldn't come here while we
329470700Sjulian				 * are processing anyhow.
329570700Sjulian				 */
329670784Sjulian				node->nd_flags &= ~NG_WORKQ;
329770784Sjulian				mtx_exit(&node->nd_input_queue.q_mtx, MTX_SPIN);
329870784Sjulian				NG_NODE_UNREF(node);
329970700Sjulian				break; /* go look for another node */
330070700Sjulian			} else {
330170784Sjulian				mtx_exit(&node->nd_input_queue.q_mtx, MTX_SPIN);
330271849Sjulian				ng_apply_item(item);
330370700Sjulian			}
330470700Sjulian		}
330552419Sjulian	}
330670700Sjulian}
330769922Sjulian
330870700Sjulianstatic void
330970700Sjulianng_worklist_remove(node_p node)
331070700Sjulian{
331171849Sjulian	mtx_enter(&ng_worklist_mtx, MTX_DEF);
331270784Sjulian	if (node->nd_flags & NG_WORKQ) {
331370784Sjulian		TAILQ_REMOVE(&ng_worklist, node, nd_work);
331470784Sjulian		NG_NODE_UNREF(node);
331570700Sjulian	}
331670784Sjulian	node->nd_flags &= ~NG_WORKQ;
331771849Sjulian	mtx_exit(&ng_worklist_mtx, MTX_DEF);
331870700Sjulian}
331970700Sjulian
332070700Sjulianstatic void
332170700Sjulianng_setisr(node_p node)
332270700Sjulian{
332371849Sjulian	mtx_enter(&ng_worklist_mtx, MTX_DEF);
332470784Sjulian	if ((node->nd_flags & NG_WORKQ) == 0) {
332569922Sjulian		/*
332670700Sjulian		 * If we are not already on the work queue,
332770700Sjulian		 * then put us on.
332869922Sjulian		 */
332970784Sjulian		node->nd_flags |= NG_WORKQ;
333070784Sjulian		TAILQ_INSERT_TAIL(&ng_worklist, node, nd_work);
333170784Sjulian		NG_NODE_REF(node);
333270700Sjulian	}
333371849Sjulian	mtx_exit(&ng_worklist_mtx, MTX_DEF);
333470700Sjulian	schednetisr(NETISR_NETGRAPH);
333570700Sjulian}
333670700Sjulian
333770700Sjulian
333870700Sjulian/***********************************************************************
333970700Sjulian* Externally useable functions to set up a queue item ready for sending
334070700Sjulian***********************************************************************/
334170700Sjulian
334270784Sjulian#ifdef	NETGRAPH_DEBUG
334370784Sjulian#define	ITEM_DEBUG_CHECKS						\
334470700Sjulian	do {								\
334571849Sjulian		if (NGI_NODE(item) ) {					\
334670700Sjulian			printf("item already has node");		\
334770700Sjulian			Debugger("has node");				\
334871849Sjulian			NGI_CLR_NODE(item);				\
334970700Sjulian		}							\
335071849Sjulian		if (NGI_HOOK(item) ) {					\
335170700Sjulian			printf("item already has hook");		\
335270700Sjulian			Debugger("has hook");				\
335371849Sjulian			NGI_CLR_HOOK(item);				\
335470700Sjulian		}							\
335570700Sjulian	} while (0)
335670700Sjulian#else
335770784Sjulian#define ITEM_DEBUG_CHECKS
335870700Sjulian#endif
335970700Sjulian
336070700Sjulian/*
336170700Sjulian * Put elements into the item.
336270700Sjulian * Hook and node references will be removed when the item is dequeued.
336370700Sjulian * (or equivalent)
336470700Sjulian * (XXX) Unsafe because no reference held by peer on remote node.
336570700Sjulian * remote node might go away in this timescale.
336670700Sjulian * We know the hooks can't go away because that would require getting
336770700Sjulian * a writer item on both nodes and we must have at least a  reader
336870700Sjulian * here to eb able to do this.
336970700Sjulian * Note that the hook loaded is the REMOTE hook.
337070700Sjulian *
337170700Sjulian * This is possibly in the critical path for new data.
337270700Sjulian */
337370700Sjulianitem_p
337470700Sjulianng_package_data(struct mbuf *m, meta_p meta)
337570700Sjulian{
337670700Sjulian	item_p item;
337770700Sjulian
337870700Sjulian	if ((item = ng_getqblk()) == NULL) {
337970700Sjulian		NG_FREE_M(m);
338070700Sjulian		NG_FREE_META(meta);
338170700Sjulian		return (NULL);
338270700Sjulian	}
338370784Sjulian	ITEM_DEBUG_CHECKS;
338470700Sjulian	item->el_flags = NGQF_DATA;
338570700Sjulian	item->el_next = NULL;
338670700Sjulian	NGI_M(item) = m;
338770700Sjulian	NGI_META(item) = meta;
338870700Sjulian	return (item);
338970700Sjulian}
339070700Sjulian
339170700Sjulian/*
339270700Sjulian * Allocate a queue item and put items into it..
339370700Sjulian * Evaluate the address as this will be needed to queue it and
339470700Sjulian * to work out what some of the fields should be.
339570700Sjulian * Hook and node references will be removed when the item is dequeued.
339670700Sjulian * (or equivalent)
339770700Sjulian */
339870700Sjulianitem_p
339970700Sjulianng_package_msg(struct ng_mesg *msg)
340070700Sjulian{
340170700Sjulian	item_p item;
340270700Sjulian
340370700Sjulian	if ((item = ng_getqblk()) == NULL) {
340471849Sjulian		NG_FREE_MSG(msg);
340570700Sjulian		return (NULL);
340669922Sjulian	}
340770784Sjulian	ITEM_DEBUG_CHECKS;
340870700Sjulian	item->el_flags = NGQF_MESG;
340970700Sjulian	item->el_next = NULL;
341070700Sjulian	/*
341170700Sjulian	 * Set the current lasthook into the queue item
341270700Sjulian	 */
341370700Sjulian	NGI_MSG(item) = msg;
341470700Sjulian	NGI_RETADDR(item) = NULL;
341570700Sjulian	return (item);
341670700Sjulian}
341769922Sjulian
341870700Sjulian
341970700Sjulian
342071849Sjulian#define SET_RETADDR(item, here, retaddr)				\
342171047Sjulian	do {	/* Data or fn items don't have retaddrs */		\
342271047Sjulian		if ((item->el_flags & NGQF_TYPE) == NGQF_MESG) {	\
342370700Sjulian			if (retaddr) {					\
342470700Sjulian				NGI_RETADDR(item) = retaddr;		\
342570700Sjulian			} else {					\
342670700Sjulian				/*					\
342770700Sjulian				 * The old return address should be ok.	\
342870700Sjulian				 * If there isn't one, use the address	\
342970700Sjulian				 * here.				\
343070700Sjulian				 */					\
343170700Sjulian				if (NGI_RETADDR(item) == 0) {		\
343270700Sjulian					NGI_RETADDR(item)		\
343370700Sjulian						= ng_node2ID(here);	\
343470700Sjulian				}					\
343570700Sjulian			}						\
343670700Sjulian		}							\
343770700Sjulian	} while (0)
343870700Sjulian
343970700Sjulianint
344070700Sjulianng_address_hook(node_p here, item_p item, hook_p hook, ng_ID_t retaddr)
344170700Sjulian{
344271849Sjulian	hook_p peer;
344371849Sjulian	node_p peernode;
344470784Sjulian	ITEM_DEBUG_CHECKS;
344570700Sjulian	/*
344670700Sjulian	 * Quick sanity check..
344770784Sjulian	 * Since a hook holds a reference on it's node, once we know
344870784Sjulian	 * that the peer is still connected (even if invalid,) we know
344970784Sjulian	 * that the peer node is present, though maybe invalid.
345070700Sjulian	 */
345170700Sjulian	if ((hook == NULL)
345270784Sjulian	|| NG_HOOK_NOT_VALID(hook)
345370784Sjulian	|| (NG_HOOK_PEER(hook) == NULL)
345470784Sjulian	|| NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))
345570784Sjulian	|| NG_NODE_NOT_VALID(NG_PEER_NODE(hook))) {
345670700Sjulian		NG_FREE_ITEM(item);
345771047Sjulian		TRAP_ERROR();
345870700Sjulian		return (EINVAL);
345952419Sjulian	}
346052419Sjulian
346170700Sjulian	/*
346270700Sjulian	 * Transfer our interest to the other (peer) end.
346370700Sjulian	 */
346471849Sjulian	peer = NG_HOOK_PEER(hook);
346571849Sjulian	NG_HOOK_REF(peer);
346671849Sjulian	NGI_SET_HOOK(item, peer);
346771849Sjulian	peernode = NG_PEER_NODE(hook);
346871849Sjulian	NG_NODE_REF(peernode);
346971849Sjulian	NGI_SET_NODE(item, peernode);
347070700Sjulian	return (0);
347170700Sjulian}
347252419Sjulian
347370700Sjulianint
347470700Sjulianng_address_path(node_p here, item_p item, char *address, ng_ID_t retaddr)
347570700Sjulian{
347670700Sjulian	node_p  dest = NULL;
347770700Sjulian	hook_p	hook = NULL;
347870700Sjulian	int     error;
347970700Sjulian
348070784Sjulian	ITEM_DEBUG_CHECKS;
348170700Sjulian	/*
348270700Sjulian	 * Note that ng_path2noderef increments the reference count
348370700Sjulian	 * on the node for us if it finds one. So we don't have to.
348470700Sjulian	 */
348570700Sjulian	error = ng_path2noderef(here, address, &dest, &hook);
348670700Sjulian	if (error) {
348770700Sjulian		NG_FREE_ITEM(item);
348870784Sjulian		return (error);
348952419Sjulian	}
349071849Sjulian	NGI_SET_NODE(item, dest);
349171849Sjulian	if ( hook) {
349270784Sjulian		NG_HOOK_REF(hook);	/* don't let it go while on the queue */
349371849Sjulian		NGI_SET_HOOK(item, hook);
349471849Sjulian	}
349571849Sjulian	SET_RETADDR(item, here, retaddr);
349670700Sjulian	return (0);
349770700Sjulian}
349852419Sjulian
349970700Sjulianint
350070700Sjulianng_address_ID(node_p here, item_p item, ng_ID_t ID, ng_ID_t retaddr)
350170700Sjulian{
350270700Sjulian	node_p dest;
350370700Sjulian
350470784Sjulian	ITEM_DEBUG_CHECKS;
350570700Sjulian	/*
350670700Sjulian	 * Find the target node.
350770700Sjulian	 */
350870700Sjulian	dest = ng_ID2noderef(ID); /* GETS REFERENCE! */
350970700Sjulian	if (dest == NULL) {
351070700Sjulian		NG_FREE_ITEM(item);
351171047Sjulian		TRAP_ERROR();
351270700Sjulian		return(EINVAL);
351370700Sjulian	}
351470700Sjulian	/* Fill out the contents */
351570700Sjulian	item->el_flags = NGQF_MESG;
351670700Sjulian	item->el_next = NULL;
351771849Sjulian	NGI_SET_NODE(item, dest);
351871849Sjulian	NGI_CLR_HOOK(item);
351971849Sjulian	SET_RETADDR(item, here, retaddr);
352052419Sjulian	return (0);
352152419Sjulian}
352252419Sjulian
352352419Sjulian/*
352470700Sjulian * special case to send a message to self (e.g. destroy node)
352570700Sjulian * Possibly indicate an arrival hook too.
352670700Sjulian * Useful for removing that hook :-)
352752419Sjulian */
352870700Sjulianitem_p
352970700Sjulianng_package_msg_self(node_p here, hook_p hook, struct ng_mesg *msg)
353052419Sjulian{
353170700Sjulian	item_p item;
353252419Sjulian
353370700Sjulian	/*
353470700Sjulian	 * Find the target node.
353570700Sjulian	 * If there is a HOOK argument, then use that in preference
353670700Sjulian	 * to the address.
353770700Sjulian	 */
353870700Sjulian	if ((item = ng_getqblk()) == NULL) {
353971849Sjulian		NG_FREE_MSG(msg);
354070700Sjulian		return (NULL);
354152419Sjulian	}
354270700Sjulian
354370700Sjulian	/* Fill out the contents */
354470700Sjulian	item->el_flags = NGQF_MESG;
354570700Sjulian	item->el_next = NULL;
354670784Sjulian	NG_NODE_REF(here);
354771849Sjulian	NGI_SET_NODE(item, here);
354871849Sjulian	if (hook) {
354970784Sjulian		NG_HOOK_REF(hook);
355071849Sjulian		NGI_SET_HOOK(item, hook);
355171849Sjulian	}
355270700Sjulian	NGI_MSG(item) = msg;
355370700Sjulian	NGI_RETADDR(item) = ng_node2ID(here);
355470700Sjulian	return (item);
355552419Sjulian}
355652419Sjulian
355771047Sjulianint
355871047Sjulianng_send_fn(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2)
355971047Sjulian{
356071047Sjulian	item_p item;
356171047Sjulian
356271047Sjulian	if ((item = ng_getqblk()) == NULL) {
356371047Sjulian		return (ENOMEM);
356471047Sjulian	}
356571047Sjulian	item->el_flags = NGQF_FN | NGQF_WRITER;
356671047Sjulian	NG_NODE_REF(node);
356771849Sjulian	NGI_SET_NODE(item, node);
356871849Sjulian	if (hook) {
356971047Sjulian		NG_HOOK_REF(hook);
357071849Sjulian		NGI_SET_HOOK(item, hook);
357171047Sjulian	}
357271047Sjulian	NGI_FN(item) = fn;
357371047Sjulian	NGI_ARG1(item) = arg1;
357471047Sjulian	NGI_ARG2(item) = arg2;
357571047Sjulian	return (ng_snd_item(item, 0));
357671047Sjulian}
357771047Sjulian
357870700Sjulian/*
357970700Sjulian * Set the address, if none given, give the node here.
358070700Sjulian */
358170700Sjulianvoid
358270700Sjulianng_replace_retaddr(node_p here, item_p item, ng_ID_t retaddr)
358370700Sjulian{
358470700Sjulian	if (retaddr) {
358570700Sjulian		NGI_RETADDR(item) = retaddr;
358670700Sjulian	} else {
358770700Sjulian		/*
358870700Sjulian		 * The old return address should be ok.
358970700Sjulian		 * If there isn't one, use the address here.
359070700Sjulian		 */
359170700Sjulian		NGI_RETADDR(item) = ng_node2ID(here);
359270700Sjulian	}
359370700Sjulian}
359452419Sjulian
359570700Sjulian#define TESTING
359670700Sjulian#ifdef TESTING
359770700Sjulian/* just test all the macros */
359870700Sjulianvoid
359970700Sjulianng_macro_test(item_p item);
360070700Sjulianvoid
360170700Sjulianng_macro_test(item_p item)
360270700Sjulian{
360370700Sjulian	node_p node = NULL;
360470700Sjulian	hook_p hook = NULL;
360570700Sjulian	struct mbuf *m;
360670700Sjulian	meta_p meta;
360770700Sjulian	struct ng_mesg *msg;
360870700Sjulian	ng_ID_t retaddr;
360970700Sjulian	int	error;
361070700Sjulian
361170700Sjulian	NGI_GET_M(item, m);
361270700Sjulian	NGI_GET_META(item, meta);
361370700Sjulian	NGI_GET_MSG(item, msg);
361470700Sjulian	retaddr = NGI_RETADDR(item);
361570700Sjulian	NG_SEND_DATA(error, hook, m, meta);
361670700Sjulian	NG_SEND_DATA_ONLY(error, hook, m);
361770700Sjulian	NG_FWD_NEW_DATA(error, item, hook, m);
361870784Sjulian	NG_FWD_ITEM_HOOK(error, item, hook);
361970700Sjulian	NG_SEND_MSG_HOOK(error, node, msg, hook, retaddr);
362070700Sjulian	NG_SEND_MSG_ID(error, node, msg, retaddr, retaddr);
362170700Sjulian	NG_SEND_MSG_PATH(error, node, msg, ".:", retaddr);
362270700Sjulian	NG_QUEUE_MSG(error, node, msg, ".:", retaddr);
362370700Sjulian	NG_FWD_MSG_HOOK(error, node, item, hook, retaddr);
362470700Sjulian}
362570700Sjulian#endif /* TESTING */
362670700Sjulian
3627