ng_base.c revision 172806
113675Sdyson/*
213675Sdyson * ng_base.c
313675Sdyson */
413675Sdyson
513675Sdyson/*-
613675Sdyson * Copyright (c) 1996-1999 Whistle Communications, Inc.
713675Sdyson * All rights reserved.
813675Sdyson *
913675Sdyson * Subject to the following obligations and disclaimer of warranty, use and
1013675Sdyson * redistribution of this software, in source or object code forms, with or
1113675Sdyson * without modifications are expressly permitted by Whistle Communications;
1213675Sdyson * provided, however, that:
1313675Sdyson * 1. Any and all reproductions of the source or object code must include the
1413675Sdyson *    copyright notice above and the following disclaimer of warranties; and
1513675Sdyson * 2. No rights are granted, in any manner or form, to use Whistle
1614037Sdyson *    Communications, Inc. trademarks, including the mark "WHISTLE
1713675Sdyson *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
1813675Sdyson *    such appears in the above copyright notice or in the software.
1913675Sdyson *
2013675Sdyson * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
2113675Sdyson * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
2213675Sdyson * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
2313675Sdyson * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
2413675Sdyson * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
2513675Sdyson * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
2613675Sdyson * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
2713907Sdyson * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
2813907Sdyson * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
2913907Sdyson * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
3013907Sdyson * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
3113907Sdyson * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
3213907Sdyson * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
3313907Sdyson * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3413907Sdyson * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3513907Sdyson * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
3613907Sdyson * OF SUCH DAMAGE.
3713913Sdyson *
3813907Sdyson * Authors: Julian Elischer <julian@freebsd.org>
3913907Sdyson *          Archie Cobbs <archie@freebsd.org>
4013907Sdyson *
4113907Sdyson * $FreeBSD: head/sys/netgraph/ng_base.c 172806 2007-10-19 15:04:17Z mav $
4213907Sdyson * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
4313907Sdyson */
4413907Sdyson
4513907Sdyson/*
46118764Ssilby * This file implements the base netgraph code.
47117325Ssilby */
48118764Ssilby
49117325Ssilby#include <sys/param.h>
50118764Ssilby#include <sys/systm.h>
51133790Ssilby#include <sys/ctype.h>
52133790Ssilby#include <sys/errno.h>
53117325Ssilby#include <sys/kdb.h>
54133790Ssilby#include <sys/kernel.h>
55133790Ssilby#include <sys/ktr.h>
56117325Ssilby#include <sys/limits.h>
57133790Ssilby#include <sys/malloc.h>
58133790Ssilby#include <sys/mbuf.h>
59117325Ssilby#include <sys/queue.h>
60133790Ssilby#include <sys/sysctl.h>
61133790Ssilby#include <sys/syslog.h>
62133790Ssilby#include <sys/refcount.h>
63133790Ssilby
64133790Ssilby#include <net/netisr.h>
65133790Ssilby
66133790Ssilby#include <netgraph/ng_message.h>
67133790Ssilby#include <netgraph/netgraph.h>
68133790Ssilby#include <netgraph/ng_parse.h>
69133049Ssilby
70133790SsilbyMODULE_VERSION(netgraph, NG_ABI_VERSION);
71133790Ssilby
72133790Ssilby/* List of all active nodes */
73133790Ssilbystatic LIST_HEAD(, ng_node) ng_nodelist;
74133790Ssilbystatic struct mtx	ng_nodelist_mtx;
75133790Ssilby
76133790Ssilby/* Mutex to protect topology events. */
77133790Ssilbystatic struct mtx	ng_topo_mtx;
78133790Ssilby
79133049Ssilby#ifdef	NETGRAPH_DEBUG
80133049Ssilbystatic struct mtx	ngq_mtx;	/* protects the queue item list */
81133049Ssilby
82133049Ssilbystatic SLIST_HEAD(, ng_node) ng_allnodes;
83133790Ssilbystatic LIST_HEAD(, ng_node) ng_freenodes; /* in debug, we never free() them */
84133790Ssilbystatic SLIST_HEAD(, ng_hook) ng_allhooks;
85133049Ssilbystatic LIST_HEAD(, ng_hook) ng_freehooks; /* in debug, we never free() them */
86133049Ssilby
87133049Ssilbystatic void ng_dumpitems(void);
88133049Ssilbystatic void ng_dumpnodes(void);
8913907Sdysonstatic void ng_dumphooks(void);
9013907Sdyson
91116182Sobrien#endif	/* NETGRAPH_DEBUG */
92116182Sobrien/*
93116182Sobrien * DEAD versions of the structures.
94101768Srwatson * In order to avoid races, it is sometimes neccesary to point
95101768Srwatson * at SOMETHING even though theoretically, the current entity is
9613675Sdyson * INVALID. Use these to avoid these races.
9713675Sdyson */
9824131Sbdestruct ng_type ng_deadtype = {
9913675Sdyson	NG_ABI_VERSION,
10013675Sdyson	"dead",
10124206Sbde	NULL,	/* modevent */
10291372Salfred	NULL,	/* constructor */
10376166Smarkm	NULL,	/* rcvmsg */
104101768Srwatson	NULL,	/* shutdown */
10576827Salfred	NULL,	/* newhook */
10624206Sbde	NULL,	/* findhook */
10713675Sdyson	NULL,	/* connect */
10891968Salfred	NULL,	/* rcvdata */
10929356Speter	NULL,	/* disconnect */
11070834Swollman	NULL, 	/* cmdlist */
11113675Sdyson};
112117325Ssilby
11313675Sdysonstruct ng_node ng_deadnode = {
11413675Sdyson	"dead",
11576166Smarkm	&ng_deadtype,
11655112Sbde	NGF_INVALID,
11734924Sbde	1,	/* refs */
11859288Sjlemon	0,	/* numhooks */
11913675Sdyson	NULL,	/* private */
12013675Sdyson	0,	/* ID */
12113675Sdyson	LIST_HEAD_INITIALIZER(ng_deadnode.hooks),
12213675Sdyson	{},	/* all_nodes list entry */
12313675Sdyson	{},	/* id hashtable list entry */
12413675Sdyson	{},	/* workqueue entry */
12513675Sdyson	{	0,
12613675Sdyson		{}, /* should never use! (should hang) */
12713907Sdyson		NULL,
12892751Sjeff		&ng_deadnode.nd_input_queue.queue,
12913675Sdyson		&ng_deadnode
13014037Sdyson	},
13114037Sdyson#ifdef	NETGRAPH_DEBUG
13214037Sdyson	ND_MAGIC,
13314037Sdyson	__FILE__,
13414037Sdyson	__LINE__,
13514037Sdyson	{NULL}
13614037Sdyson#endif	/* NETGRAPH_DEBUG */
13714037Sdyson};
13814037Sdyson
13914037Sdysonstruct ng_hook ng_deadhook = {
140108255Sphk	"dead",
141108255Sphk	NULL,		/* private */
142108255Sphk	HK_INVALID | HK_DEAD,
143108255Sphk	1,		/* refs always >= 1 */
144108255Sphk	0,		/* undefined data link type */
145108255Sphk	&ng_deadhook,	/* Peer is self */
146108255Sphk	&ng_deadnode,	/* attached to deadnode */
14713675Sdyson	{},		/* hooks list */
14872521Sjlemon	NULL,		/* override rcvmsg() */
149116546Sphk	NULL,		/* override rcvdata() */
150116546Sphk#ifdef	NETGRAPH_DEBUG
151116546Sphk	HK_MAGIC,
152116546Sphk	__FILE__,
153116546Sphk	__LINE__,
154116546Sphk	{NULL}
155116546Sphk#endif	/* NETGRAPH_DEBUG */
156116546Sphk};
15772521Sjlemon
15813675Sdyson/*
15959288Sjlemon * END DEAD STRUCTURES
16059288Sjlemon */
16159288Sjlemon/* List nodes with unallocated work */
16259288Sjlemonstatic TAILQ_HEAD(, ng_node) ng_worklist = TAILQ_HEAD_INITIALIZER(ng_worklist);
16372521Sjlemonstatic struct mtx	ng_worklist_mtx;   /* MUST LOCK NODE FIRST */
16472521Sjlemon
16572521Sjlemon/* List of installed types */
16672521Sjlemonstatic LIST_HEAD(, ng_type) ng_typelist;
16759288Sjlemonstatic struct mtx	ng_typelist_mtx;
16813675Sdyson
16913675Sdyson/* Hash related definitions */
17013675Sdyson/* XXX Don't need to initialise them because it's a LIST */
17113675Sdyson#define NG_ID_HASH_SIZE 32 /* most systems wont need even this many */
17213675Sdysonstatic LIST_HEAD(, ng_node) ng_ID_hash[NG_ID_HASH_SIZE];
17313675Sdysonstatic struct mtx	ng_idhash_mtx;
17413907Sdyson/* Method to find a node.. used twice so do it here */
17513907Sdyson#define NG_IDHASH_FN(ID) ((ID) % (NG_ID_HASH_SIZE))
17613675Sdyson#define NG_IDHASH_FIND(ID, node)					\
177117325Ssilby	do { 								\
17817124Sbde		mtx_assert(&ng_idhash_mtx, MA_OWNED);			\
179133790Ssilby		LIST_FOREACH(node, &ng_ID_hash[NG_IDHASH_FN(ID)],	\
180133790Ssilby						nd_idnodes) {		\
181133790Ssilby			if (NG_NODE_IS_VALID(node)			\
182133790Ssilby			&& (NG_NODE_ID(node) == ID)) {			\
18313907Sdyson				break;					\
184117325Ssilby			}						\
185117325Ssilby		}							\
186121307Ssilby	} while (0)
187117325Ssilby
188117325Ssilby
189117364Ssilby/* Internal functions */
190117325Ssilbystatic int	ng_add_hook(node_p node, const char *name, hook_p * hookp);
191117325Ssilbystatic int	ng_generic_msg(node_p here, item_p item, hook_p lasthook);
192133790Ssilbystatic ng_ID_t	ng_decodeidname(const char *name);
193133790Ssilbystatic int	ngb_mod_event(module_t mod, int event, void *data);
194133790Ssilbystatic void	ng_worklist_remove(node_p node);
195133790Ssilbystatic void	ngintr(void);
196133790Ssilbystatic int	ng_apply_item(node_p node, item_p item, int rw);
197133790Ssilbystatic void	ng_flush_input_queue(struct ng_queue * ngq);
198133790Ssilbystatic void	ng_setisr(node_p node);
199133790Ssilbystatic node_p	ng_ID2noderef(ng_ID_t ID);
200117325Ssilbystatic int	ng_con_nodes(item_p item, node_p node, const char *name,
20191413Salfred		    node_p node2, const char *name2);
20291413Salfredstatic int	ng_con_part2(node_p node, item_p item, hook_p hook);
20391413Salfredstatic int	ng_con_part3(node_p node, item_p item, hook_p hook);
204133790Ssilbystatic int	ng_mkpeer(node_p node, const char *name,
20591413Salfred						const char *name2, char *type);
20691413Salfred
20791413Salfred/* Imported, these used to be externally visible, some may go back. */
20814037Sdysonvoid	ng_destroy_hook(hook_p hook);
20991413Salfrednode_p	ng_name2noderef(node_p node, const char *name);
21091413Salfredint	ng_path2noderef(node_p here, const char *path,
21191413Salfred	node_p *dest, hook_p *lasthook);
21291413Salfredint	ng_make_node(const char *type, node_p *nodepp);
21314037Sdysonint	ng_path_parse(char *addr, char **node, char **path, char **hook);
21491413Salfredvoid	ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3);
215132579Srwatsonvoid	ng_unname(node_p node);
21613675Sdyson
217132987Sgreen
218125293Srwatson/* Our own netgraph malloc type */
219132987SgreenMALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
220125293SrwatsonMALLOC_DEFINE(M_NETGRAPH_HOOK, "netgraph_hook", "netgraph hook structures");
221125293SrwatsonMALLOC_DEFINE(M_NETGRAPH_NODE, "netgraph_node", "netgraph node structures");
22292751SjeffMALLOC_DEFINE(M_NETGRAPH_ITEM, "netgraph_item", "netgraph item structures");
22327899SdysonMALLOC_DEFINE(M_NETGRAPH_MSG, "netgraph_msg", "netgraph name storage");
22491372Salfred
22591372Salfred/* Should not be visible outside this file */
22691372Salfred
22791372Salfred#define _NG_ALLOC_HOOK(hook) \
22891372Salfred	MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH_HOOK, M_NOWAIT | M_ZERO)
229118880Salc#define _NG_ALLOC_NODE(node) \
230125293Srwatson	MALLOC(node, node_p, sizeof(*node), M_NETGRAPH_NODE, M_NOWAIT | M_ZERO)
231125293Srwatson
232125293Srwatson#define	NG_QUEUE_LOCK_INIT(n)			\
233118880Salc	mtx_init(&(n)->q_mtx, "ng_node", NULL, MTX_DEF)
23491372Salfred#define	NG_QUEUE_LOCK(n)			\
23591372Salfred	mtx_lock(&(n)->q_mtx)
236132987Sgreen#define	NG_QUEUE_UNLOCK(n)			\
237132987Sgreen	mtx_unlock(&(n)->q_mtx)
238125293Srwatson#define	NG_WORKLIST_LOCK_INIT()			\
239125293Srwatson	mtx_init(&ng_worklist_mtx, "ng_worklist", NULL, MTX_DEF)
240125293Srwatson#define	NG_WORKLIST_LOCK()			\
241125293Srwatson	mtx_lock(&ng_worklist_mtx)
242125293Srwatson#define	NG_WORKLIST_UNLOCK()			\
243125293Srwatson	mtx_unlock(&ng_worklist_mtx)
244125293Srwatson
245125293Srwatson#ifdef NETGRAPH_DEBUG /*----------------------------------------------*/
246125293Srwatson/*
247125293Srwatson * In debug mode:
248125293Srwatson * In an attempt to help track reference count screwups
249125293Srwatson * we do not free objects back to the malloc system, but keep them
250125293Srwatson * in a local cache where we can examine them and keep information safely
251125293Srwatson * after they have been freed.
252125293Srwatson * We use this scheme for nodes and hooks, and to some extent for items.
253125293Srwatson */
254125293Srwatsonstatic __inline hook_p
255125293Srwatsonng_alloc_hook(void)
256125293Srwatson{
257125293Srwatson	hook_p hook;
258125293Srwatson	SLIST_ENTRY(ng_hook) temp;
259125293Srwatson	mtx_lock(&ng_nodelist_mtx);
260125293Srwatson	hook = LIST_FIRST(&ng_freehooks);
261125293Srwatson	if (hook) {
262125293Srwatson		LIST_REMOVE(hook, hk_hooks);
263125293Srwatson		bcopy(&hook->hk_all, &temp, sizeof(temp));
264125293Srwatson		bzero(hook, sizeof(struct ng_hook));
265125293Srwatson		bcopy(&temp, &hook->hk_all, sizeof(temp));
266125293Srwatson		mtx_unlock(&ng_nodelist_mtx);
267125293Srwatson		hook->hk_magic = HK_MAGIC;
268125293Srwatson	} else {
269125293Srwatson		mtx_unlock(&ng_nodelist_mtx);
270125293Srwatson		_NG_ALLOC_HOOK(hook);
271125293Srwatson		if (hook) {
272125293Srwatson			hook->hk_magic = HK_MAGIC;
273125293Srwatson			mtx_lock(&ng_nodelist_mtx);
274125293Srwatson			SLIST_INSERT_HEAD(&ng_allhooks, hook, hk_all);
275125293Srwatson			mtx_unlock(&ng_nodelist_mtx);
276125293Srwatson		}
277125293Srwatson	}
278125293Srwatson	return (hook);
279125293Srwatson}
280125293Srwatson
281125367Srwatsonstatic __inline node_p
282132987Sgreenng_alloc_node(void)
283125293Srwatson{
284125293Srwatson	node_p node;
285125293Srwatson	SLIST_ENTRY(ng_node) temp;
286125293Srwatson	mtx_lock(&ng_nodelist_mtx);
287125293Srwatson	node = LIST_FIRST(&ng_freenodes);
288125293Srwatson	if (node) {
289125293Srwatson		LIST_REMOVE(node, nd_nodes);
290125293Srwatson		bcopy(&node->nd_all, &temp, sizeof(temp));
291125293Srwatson		bzero(node, sizeof(struct ng_node));
292125293Srwatson		bcopy(&temp, &node->nd_all, sizeof(temp));
293125367Srwatson		mtx_unlock(&ng_nodelist_mtx);
294125367Srwatson		node->nd_magic = ND_MAGIC;
295125293Srwatson	} else {
296125293Srwatson		mtx_unlock(&ng_nodelist_mtx);
297132987Sgreen		_NG_ALLOC_NODE(node);
298132987Sgreen		if (node) {
299125293Srwatson			node->nd_magic = ND_MAGIC;
300125293Srwatson			mtx_lock(&ng_nodelist_mtx);
301125293Srwatson			SLIST_INSERT_HEAD(&ng_allnodes, node, nd_all);
302125293Srwatson			mtx_unlock(&ng_nodelist_mtx);
303125293Srwatson		}
304125293Srwatson	}
305125293Srwatson	return (node);
306125293Srwatson}
307132987Sgreen
308125293Srwatson#define NG_ALLOC_HOOK(hook) do { (hook) = ng_alloc_hook(); } while (0)
309125293Srwatson#define NG_ALLOC_NODE(node) do { (node) = ng_alloc_node(); } while (0)
310125293Srwatson
311125293Srwatson
312125293Srwatson#define NG_FREE_HOOK(hook)						\
313125293Srwatson	do {								\
314125293Srwatson		mtx_lock(&ng_nodelist_mtx);			\
315125293Srwatson		LIST_INSERT_HEAD(&ng_freehooks, hook, hk_hooks);	\
316125293Srwatson		hook->hk_magic = 0;					\
317125293Srwatson		mtx_unlock(&ng_nodelist_mtx);			\
318125293Srwatson	} while (0)
319125293Srwatson
320125293Srwatson#define NG_FREE_NODE(node)						\
321125293Srwatson	do {								\
32213675Sdyson		mtx_lock(&ng_nodelist_mtx);			\
323125293Srwatson		LIST_INSERT_HEAD(&ng_freenodes, node, nd_nodes);	\
324125293Srwatson		node->nd_magic = 0;					\
32513675Sdyson		mtx_unlock(&ng_nodelist_mtx);			\
32613675Sdyson	} while (0)
32713675Sdyson
32813675Sdyson#else /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
32983366Sjulian
33083366Sjulian#define NG_ALLOC_HOOK(hook) _NG_ALLOC_HOOK(hook)
33113675Sdyson#define NG_ALLOC_NODE(node) _NG_ALLOC_NODE(node)
33213675Sdyson
33313675Sdyson#define NG_FREE_HOOK(hook) do { FREE((hook), M_NETGRAPH_HOOK); } while (0)
33413675Sdyson#define NG_FREE_NODE(node) do { FREE((node), M_NETGRAPH_NODE); } while (0)
33583366Sjulian
33613675Sdyson#endif /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
337125293Srwatson
33813675Sdyson/* Set this to kdb_enter("X") to catch all errors as they occur */
33913675Sdyson#ifndef TRAP_ERROR
34027899Sdyson#define TRAP_ERROR()
341125293Srwatson#endif
342125293Srwatson
343125293Srwatsonstatic	ng_ID_t nextID = 1;
344126249Srwatson
345126249Srwatson#ifdef INVARIANTS
346126249Srwatson#define CHECK_DATA_MBUF(m)	do {					\
347125293Srwatson		struct mbuf *n;						\
348125293Srwatson		int total;						\
349125293Srwatson									\
350125293Srwatson		M_ASSERTPKTHDR(m);					\
351125293Srwatson		for (total = 0, n = (m); n != NULL; n = n->m_next) {	\
352125293Srwatson			total += n->m_len;				\
353125293Srwatson			if (n->m_nextpkt != NULL)			\
354133790Ssilby				panic("%s: m_nextpkt", __func__);	\
355133790Ssilby		}							\
356124394Sdes									\
357124394Sdes		if ((m)->m_pkthdr.len != total) {			\
35876364Salfred			panic("%s: %d != %d",				\
35976364Salfred			    __func__, (m)->m_pkthdr.len, total);	\
360124394Sdes		}							\
36113907Sdyson	} while (0)
36213907Sdyson#else
36313675Sdyson#define CHECK_DATA_MBUF(m)
36483366Sjulian#endif
36570915Sdwmalone
36670915Sdwmalone#define ERROUT(x)	do { error = (x); goto done; } while (0)
36770915Sdwmalone
36870915Sdwmalone/************************************************************************
36970915Sdwmalone	Parse type definitions for generic messages
370121256Sdwmalone************************************************************************/
37183366Sjulian
37270915Sdwmalone/* Handy structure parse type defining macro */
37370803Sdwmalone#define DEFINE_PARSE_STRUCT_TYPE(lo, up, args)				\
37470803Sdwmalonestatic const struct ng_parse_struct_field				\
37570803Sdwmalone	ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args;	\
37670803Sdwmalonestatic const struct ng_parse_type ng_generic_ ## lo ## _type = {	\
37770803Sdwmalone	&ng_parse_struct_type,						\
37870803Sdwmalone	&ng_ ## lo ## _type_fields					\
37989306Salfred}
38013675Sdyson
38113675SdysonDEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
382109153SdillonDEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
38313675SdysonDEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
38489306SalfredDEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
38583366SjulianDEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
38670915SdwmaloneDEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
387137355SphkDEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
38883366Sjulian
38970915Sdwmalone/* Get length of an array when the length is stored as a 32 bit
39070915Sdwmalone   value immediately preceding the array -- as with struct namelist
39170915Sdwmalone   and struct typelist. */
39270915Sdwmalonestatic int
393121256Sdwmaloneng_generic_list_getLength(const struct ng_parse_type *type,
39489306Salfred	const u_char *start, const u_char *buf)
39513675Sdyson{
39613675Sdyson	return *((const u_int32_t *)(buf - 4));
397109153Sdillon}
39813675Sdyson
39989306Salfred/* Get length of the array of struct linkinfo inside a struct hooklist */
400121256Sdwmalonestatic int
40183366Sjulianng_generic_linkinfo_getLength(const struct ng_parse_type *type,
40283366Sjulian	const u_char *start, const u_char *buf)
40313675Sdyson{
40413675Sdyson	const struct hooklist *hl = (const struct hooklist *)start;
40513675Sdyson
40613675Sdyson	return hl->nodeinfo.hooks;
40713909Sdyson}
40813909Sdyson
40976364Salfred/* Array type for a variable length array of struct namelist */
41076364Salfredstatic const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
41176364Salfred	&ng_generic_nodeinfo_type,
41213909Sdyson	&ng_generic_list_getLength
41376364Salfred};
414132579Srwatsonstatic const struct ng_parse_type ng_generic_nodeinfoarray_type = {
41513675Sdyson	&ng_parse_array_type,
41676364Salfred	&ng_nodeinfoarray_type_info
41713675Sdyson};
41876364Salfred
419133790Ssilby/* Array type for a variable length array of struct typelist */
420117325Ssilbystatic const struct ng_parse_array_info ng_typeinfoarray_type_info = {
421117325Ssilby	&ng_generic_typeinfo_type,
42213675Sdyson	&ng_generic_list_getLength
423125293Srwatson};
424133790Ssilbystatic const struct ng_parse_type ng_generic_typeinfoarray_type = {
425133790Ssilby	&ng_parse_array_type,
426133790Ssilby	&ng_typeinfoarray_type_info
427133790Ssilby};
428133790Ssilby
429133790Ssilby/* Array type for array of struct linkinfo in struct hooklist */
43079224Sdillonstatic const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
431118764Ssilby	&ng_generic_linkinfo_type,
432118764Ssilby	&ng_generic_linkinfo_getLength
43313675Sdyson};
434122163Salcstatic const struct ng_parse_type ng_generic_linkinfo_array_type = {
43576364Salfred	&ng_parse_array_type,
43613688Sdyson	&ng_generic_linkinfo_array_type_info
43776364Salfred};
438133790Ssilby
439133790SsilbyDEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
440133790SsilbyDEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
441133790Ssilby	(&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
442133790SsilbyDEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
443133790Ssilby	(&ng_generic_nodeinfoarray_type));
444133790Ssilby
445133790Ssilby/* List of commands and how to convert arguments to/from ASCII */
446133790Ssilbystatic const struct ng_cmdlist ng_generic_cmds[] = {
447133790Ssilby	{
448133790Ssilby	  NGM_GENERIC_COOKIE,
449133790Ssilby	  NGM_SHUTDOWN,
450133790Ssilby	  "shutdown",
45176364Salfred	  NULL,
45276364Salfred	  NULL
45376364Salfred	},
454133790Ssilby	{
455133790Ssilby	  NGM_GENERIC_COOKIE,
456133790Ssilby	  NGM_MKPEER,
457133790Ssilby	  "mkpeer",
458133790Ssilby	  &ng_generic_mkpeer_type,
459133790Ssilby	  NULL
460133790Ssilby	},
461133790Ssilby	{
462133790Ssilby	  NGM_GENERIC_COOKIE,
463133790Ssilby	  NGM_CONNECT,
464133790Ssilby	  "connect",
465133790Ssilby	  &ng_generic_connect_type,
466133790Ssilby	  NULL
467133790Ssilby	},
46876364Salfred	{
46976364Salfred	  NGM_GENERIC_COOKIE,
47076364Salfred	  NGM_NAME,
471133790Ssilby	  "name",
47276364Salfred	  &ng_generic_name_type,
473133790Ssilby	  NULL
474110816Salc	},
47576364Salfred	{
47613907Sdyson	  NGM_GENERIC_COOKIE,
47713688Sdyson	  NGM_RMHOOK,
47813907Sdyson	  "rmhook",
479132579Srwatson	  &ng_generic_rmhook_type,
480132579Srwatson	  NULL
481132579Srwatson	},
482132579Srwatson	{
483132579Srwatson	  NGM_GENERIC_COOKIE,
484132579Srwatson	  NGM_NODEINFO,
485132579Srwatson	  "nodeinfo",
486132579Srwatson	  NULL,
487133049Ssilby	  &ng_generic_nodeinfo_type
488133049Ssilby	},
489132579Srwatson	{
490132579Srwatson	  NGM_GENERIC_COOKIE,
491132579Srwatson	  NGM_LISTHOOKS,
492132579Srwatson	  "listhooks",
49313675Sdyson	  NULL,
49413675Sdyson	  &ng_generic_hooklist_type
49513675Sdyson	},
49613907Sdyson	{
49713675Sdyson	  NGM_GENERIC_COOKIE,
49813907Sdyson	  NGM_LISTNAMES,
49913675Sdyson	  "listnames",
50013776Sdyson	  NULL,
50176364Salfred	  &ng_generic_listnodes_type	/* same as NGM_LISTNODES */
50291362Salfred	},
50391362Salfred	{
50413675Sdyson	  NGM_GENERIC_COOKIE,
50591362Salfred	  NGM_LISTNODES,
50691362Salfred	  "listnodes",
50776760Salfred	  NULL,
508124394Sdes	  &ng_generic_listnodes_type
50976760Salfred	},
51013675Sdyson	{
51191362Salfred	  NGM_GENERIC_COOKIE,
51276760Salfred	  NGM_LISTTYPES,
51313675Sdyson	  "listtypes",
51413675Sdyson	  NULL,
51513675Sdyson	  &ng_generic_typeinfo_type
51613675Sdyson	},
51713675Sdyson	{
51813675Sdyson	  NGM_GENERIC_COOKIE,
51913675Sdyson	  NGM_TEXT_CONFIG,
52013675Sdyson	  "textconfig",
52113675Sdyson	  NULL,
52276364Salfred	  &ng_parse_string_type
52391362Salfred	},
524133049Ssilby	{
525133049Ssilby	  NGM_GENERIC_COOKIE,
52691362Salfred	  NGM_TEXT_STATUS,
52713675Sdyson	  "textstatus",
52813675Sdyson	  NULL,
52914177Sdyson	  &ng_parse_string_type
53013675Sdyson	},
53113675Sdyson	{
53213675Sdyson	  NGM_GENERIC_COOKIE,
53314037Sdyson	  NGM_ASCII2BINARY,
53414037Sdyson	  "ascii2binary",
53514037Sdyson	  &ng_parse_ng_mesg_type,
53614037Sdyson	  &ng_parse_ng_mesg_type
53776364Salfred	},
538126252Srwatson	{
53914037Sdyson	  NGM_GENERIC_COOKIE,
54014037Sdyson	  NGM_BINARY2ASCII,
541122352Stanimura	  "binary2ascii",
54214037Sdyson	  &ng_parse_ng_mesg_type,
54341086Struckman	  &ng_parse_ng_mesg_type
54495883Salfred	},
545133741Sjmg	{ 0 }
54614037Sdyson};
54714037Sdyson
548126131Sgreen/************************************************************************
549126131Sgreen			Node routines
550126131Sgreen************************************************************************/
551126131Sgreen
552126131Sgreen/*
553133790Ssilby * Instantiate a node of the requested type
554126131Sgreen */
555133790Ssilbyint
556126131Sgreenng_make_node(const char *typename, node_p *nodepp)
557126131Sgreen{
558126131Sgreen	struct ng_type *type;
559133790Ssilby	int	error;
560133790Ssilby
561133790Ssilby	/* Check that the type makes sense */
562133790Ssilby	if (typename == NULL) {
563133790Ssilby		TRAP_ERROR();
564133790Ssilby		return (EINVAL);
565133790Ssilby	}
566133790Ssilby
567133790Ssilby	/* Locate the node type. If we fail we return. Do not try to load
568133741Sjmg	 * module.
569132579Srwatson	 */
570126131Sgreen	if ((type = ng_findtype(typename)) == NULL)
571126131Sgreen		return (ENXIO);
57213675Sdyson
57313675Sdyson	/*
574101941Srwatson	 * If we have a constructor, then make the node and
57513675Sdyson	 * call the constructor to do type specific initialisation.
57613675Sdyson	 */
577101941Srwatson	if (type->constructor != NULL) {
57883366Sjulian		if ((error = ng_make_node_common(type, nodepp)) == 0) {
57945311Sdt			if ((error = ((*type->constructor)(*nodepp)) != 0)) {
58013675Sdyson				NG_NODE_UNREF(*nodepp);
581109153Sdillon			}
58247748Salc		}
58313675Sdyson	} else {
58418863Sdyson		/*
58513675Sdyson		 * Node has no constructor. We cannot ask for one
58691362Salfred		 * to be made. It must be brought into existence by
58713675Sdyson		 * some external agency. The external agency should
58847748Salc		 * call ng_make_node_common() directly to get the
58947748Salc		 * netgraph part initialised.
59047748Salc		 */
59147748Salc		TRAP_ERROR();
592101768Srwatson		error = EINVAL;
593125293Srwatson	}
594101768Srwatson	return (error);
595101768Srwatson}
596101768Srwatson
597133790Ssilby/*
598133790Ssilby * Generic node creation. Called by node initialisation for externally
599133790Ssilby * instantiated nodes (e.g. hardware, sockets, etc ).
600133790Ssilby * The returned node has a reference count of 1.
601133790Ssilby */
602133790Ssilbyint
603133790Ssilbyng_make_node_common(struct ng_type *type, node_p *nodepp)
604133790Ssilby{
605133790Ssilby	node_p node;
606133790Ssilby
607101768Srwatson	/* Require the node type to have been already installed */
60813675Sdyson	if (ng_findtype(type->name) == NULL) {
60913907Sdyson		TRAP_ERROR();
61013907Sdyson		return (EINVAL);
61113907Sdyson	}
61213675Sdyson
61318863Sdyson	/* Make a node and try attach it to the type */
61413675Sdyson	NG_ALLOC_NODE(node);
61513675Sdyson	if (node == NULL) {
61618863Sdyson		TRAP_ERROR();
61718863Sdyson		return (ENOMEM);
61847748Salc	}
61991362Salfred	node->nd_type = type;
620116127Smux	NG_NODE_REF(node);				/* note reference */
621116127Smux	type->refs++;
622116127Smux
62391362Salfred	NG_QUEUE_LOCK_INIT(&node->nd_input_queue);
62476760Salfred	node->nd_input_queue.queue = NULL;
62513675Sdyson	node->nd_input_queue.last = &node->nd_input_queue.queue;
62676760Salfred	node->nd_input_queue.q_flags = 0;
62713675Sdyson	node->nd_input_queue.q_node = node;
62813675Sdyson
62913675Sdyson	/* Initialize hook list for new node */
63013675Sdyson	LIST_INIT(&node->nd_hooks);
63113675Sdyson
63247748Salc	/* Link us into the node linked list */
63347748Salc	mtx_lock(&ng_nodelist_mtx);
63447748Salc	LIST_INSERT_HEAD(&ng_nodelist, node, nd_nodes);
63547748Salc	mtx_unlock(&ng_nodelist_mtx);
63647748Salc
63747748Salc
63847748Salc	/* get an ID and put us in the hash chain */
63947748Salc	mtx_lock(&ng_idhash_mtx);
64047748Salc	for (;;) { /* wrap protection, even if silly */
64147748Salc		node_p node2 = NULL;
64213675Sdyson		node->nd_ID = nextID++; /* 137/second for 1 year before wrap */
64314037Sdyson
64413907Sdyson		/* Is there a problem with the new number? */
64513907Sdyson		NG_IDHASH_FIND(node->nd_ID, node2); /* already taken? */
64613907Sdyson		if ((node->nd_ID != 0) && (node2 == NULL)) {
64713907Sdyson			break;
64847748Salc		}
64918863Sdyson	}
65018863Sdyson	LIST_INSERT_HEAD(&ng_ID_hash[NG_IDHASH_FN(node->nd_ID)],
65147748Salc							node, nd_idnodes);
65291362Salfred	mtx_unlock(&ng_idhash_mtx);
653127501Salc
654127501Salc	/* Done */
65591362Salfred	*nodepp = node;
65613907Sdyson	return (0);
65713907Sdyson}
65813907Sdyson
65913907Sdyson/*
66013907Sdyson * Forceably start the shutdown process on a node. Either call
66113907Sdyson * its shutdown method, or do the default shutdown if there is
66213907Sdyson * no type-specific method.
66313907Sdyson *
66413907Sdyson * We can only be called from a shutdown message, so we know we have
66514037Sdyson * a writer lock, and therefore exclusive access. It also means
66613675Sdyson * that we should not be on the work queue, but we check anyhow.
66713675Sdyson *
66813675Sdyson * Persistent node types must have a type-specific method which
66976760Salfred * allocates a new node in which case, this one is irretrievably going away,
67013675Sdyson * or cleans up anything it needs, and just makes the node valid again,
67176760Salfred * in which case we allow the node to survive.
67213675Sdyson *
67343623Sdillon * XXX We need to think of how to tell a persistent node that we
67413675Sdyson * REALLY need to go away because the hardware has gone or we
67513675Sdyson * are rebooting.... etc.
67613675Sdyson */
67713675Sdysonvoid
67813675Sdysonng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3)
67913675Sdyson{
68013675Sdyson	hook_p hook;
68143623Sdillon
68243623Sdillon	/* Check if it's already shutting down */
68347748Salc	if ((node->nd_flags & NGF_CLOSING) != 0)
68443623Sdillon		return;
68547748Salc
68613675Sdyson	if (node == &ng_deadnode) {
68716960Sdyson		printf ("shutdown called on deadnode\n");
68843623Sdillon		return;
689124394Sdes	}
690116127Smux
691116127Smux	/* Add an extra reference so it doesn't go away during this */
69243623Sdillon	NG_NODE_REF(node);
69347748Salc
69443623Sdillon	/*
69513675Sdyson	 * Mark it invalid so any newcomers know not to try use it
69647748Salc	 * Also add our own mark so we can't recurse
69747748Salc	 * note that NGF_INVALID does not do this as it's also set during
69813675Sdyson	 * creation
69976760Salfred	 */
70047748Salc	node->nd_flags |= NGF_INVALID|NGF_CLOSING;
70176760Salfred
70247748Salc	/* If node has its pre-shutdown method, then call it first*/
70391362Salfred	if (node->nd_type && node->nd_type->close)
70491362Salfred		(*node->nd_type->close)(node);
70577140Salfred
70647748Salc	/* Notify all remaining connected nodes to disconnect */
70713675Sdyson	while ((hook = LIST_FIRST(&node->nd_hooks)) != NULL)
70847748Salc		ng_destroy_hook(hook);
70947748Salc
71013675Sdyson	/*
71113675Sdyson	 * Drain the input queue forceably.
712101768Srwatson	 * it has no hooks so what's it going to do, bleed on someone?
713101768Srwatson	 * Theoretically we came here from a queue entry that was added
714101768Srwatson	 * Just before the queue was closed, so it should be empty anyway.
71547748Salc	 * Also removes us from worklist if needed.
71613675Sdyson	 */
71791362Salfred	ng_flush_input_queue(&node->nd_input_queue);
71824101Sbde
71955112Sbde	/* Ask the type if it has anything to do in this case */
72047748Salc	if (node->nd_type && node->nd_type->shutdown) {
72147748Salc		(*node->nd_type->shutdown)(node);
72213913Sdyson		if (NG_NODE_IS_VALID(node)) {
72347748Salc			/*
72447748Salc			 * Well, blow me down if the node code hasn't declared
72547748Salc			 * that it doesn't want to die.
72613675Sdyson			 * Presumably it is a persistant node.
72713675Sdyson			 * If we REALLY want it to go away,
72813675Sdyson			 *  e.g. hardware going away,
72913675Sdyson			 * Our caller should set NGF_REALLY_DIE in nd_flags.
73013675Sdyson			 */
73147748Salc			node->nd_flags &= ~(NGF_INVALID|NGF_CLOSING);
73213675Sdyson			NG_NODE_UNREF(node); /* Assume they still have theirs */
73313675Sdyson			return;
73413675Sdyson		}
73513675Sdyson	} else {				/* do the default thing */
73613675Sdyson		NG_NODE_UNREF(node);
73713675Sdyson	}
73814037Sdyson
73914802Sdyson	ng_unname(node); /* basically a NOP these days */
74014037Sdyson
74114037Sdyson	/*
74291362Salfred	 * Remove extra reference, possibly the last
74376760Salfred	 * Possible other holders of references may include
74413675Sdyson	 * timeout callouts, but theoretically the node's supposed to
74513675Sdyson	 * have cancelled them. Possibly hardware dependencies may
74614037Sdyson	 * force a driver to 'linger' with a reference.
74713907Sdyson	 */
74813907Sdyson	NG_NODE_UNREF(node);
74913907Sdyson}
75013907Sdyson
75113675Sdyson/*
75213907Sdyson * Remove a reference to the node, possibly the last.
75313907Sdyson * deadnode always acts as it it were the last.
75413675Sdyson */
75513675Sdysonint
756119872Salcng_unref_node(node_p node)
75718863Sdyson{
758119872Salc	int v;
759112569Sjake
76013907Sdyson	if (node == &ng_deadnode) {
76191412Salfred		return (0);
762133790Ssilby	}
763133790Ssilby
76479224Sdillon	do {
76518863Sdyson		v = node->nd_refs - 1;
76613907Sdyson	} while (! atomic_cmpset_int(&node->nd_refs, v + 1, v));
76713907Sdyson
76813907Sdyson	if (v == 0) { /* we were the last */
769119872Salc
77040286Sdg		mtx_lock(&ng_nodelist_mtx);
77176760Salfred		node->nd_type->refs--; /* XXX maybe should get types lock? */
77276760Salfred		LIST_REMOVE(node, nd_nodes);
77399899Salc		mtx_unlock(&ng_nodelist_mtx);
77499899Salc
77599899Salc		mtx_lock(&ng_idhash_mtx);
77699899Salc		LIST_REMOVE(node, nd_idnodes);
77799899Salc		mtx_unlock(&ng_idhash_mtx);
778119872Salc
779119872Salc		mtx_destroy(&node->nd_input_queue.q_mtx);
78099899Salc		NG_FREE_NODE(node);
781119872Salc	}
782118757Salc	return (v);
78399899Salc}
78476760Salfred
78513907Sdyson/************************************************************************
786120000Salc			Node ID handling
787120000Salc************************************************************************/
788119872Salcstatic node_p
789119872Salcng_ID2noderef(ng_ID_t ID)
79013907Sdyson{
79113907Sdyson	node_p node;
79213907Sdyson	mtx_lock(&ng_idhash_mtx);
79313907Sdyson	NG_IDHASH_FIND(ID, node);
79413907Sdyson	if(node)
79513907Sdyson		NG_NODE_REF(node);
79676760Salfred	mtx_unlock(&ng_idhash_mtx);
79776760Salfred	return(node);
79813907Sdyson}
79913907Sdyson
80013907Sdysonng_ID_t
80113907Sdysonng_node2ID(node_p node)
80213907Sdyson{
80313907Sdyson	return (node ? NG_NODE_ID(node) : 0);
80413907Sdyson}
805104908Smike
80613907Sdyson/************************************************************************
80713907Sdyson			Node name handling
80813907Sdyson************************************************************************/
80913907Sdyson
81076760Salfred/*
81113907Sdyson * Assign a node a name. Once assigned, the name cannot be changed.
81213907Sdyson */
81313907Sdysonint
81413907Sdysonng_name_node(node_p node, const char *name)
81513907Sdyson{
81613907Sdyson	int i;
81713907Sdyson	node_p node2;
81876760Salfred
81913907Sdyson	/* Check the name is valid */
82013907Sdyson	for (i = 0; i < NG_NODESIZ; i++) {
82176364Salfred		if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
822127501Salc			break;
82399899Salc	}
824117325Ssilby	if (i == 0 || name[i] != '\0') {
825118757Salc		TRAP_ERROR();
826117325Ssilby		return (EINVAL);
82799899Salc	}
82891653Stanimura	if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
82913907Sdyson		TRAP_ERROR();
83013907Sdyson		return (EINVAL);
83113907Sdyson	}
83213907Sdyson
83313907Sdyson	/* Check the name isn't already being used */
83413907Sdyson	if ((node2 = ng_name2noderef(node, name)) != NULL) {
83513907Sdyson		NG_NODE_UNREF(node2);
83613907Sdyson		TRAP_ERROR();
83713907Sdyson		return (EADDRINUSE);
83876364Salfred	}
83913907Sdyson
840127501Salc	/* copy it */
841127501Salc	strlcpy(NG_NODE_NAME(node), name, NG_NODESIZ);
84213907Sdyson
84313907Sdyson	return (0);
84413907Sdyson}
84591362Salfred
84613907Sdyson/*
84713907Sdyson * Find a node by absolute name. The name should NOT end with ':'
84813907Sdyson * The name "." means "this node" and "[xxx]" means "the node
84913907Sdyson * with ID (ie, at address) xxx".
85013907Sdyson *
85113907Sdyson * Returns the node if found, else NULL.
85213907Sdyson * Eventually should add something faster than a sequential search.
85313907Sdyson * Note it acquires a reference on the node so you can be sure it's still
854119811Salc * there.
855127501Salc */
856127501Salcnode_p
857127501Salcng_name2noderef(node_p here, const char *name)
858127501Salc{
859127501Salc	node_p node;
860127501Salc	ng_ID_t temp;
861127501Salc
862127501Salc	/* "." means "this node" */
863127501Salc	if (strcmp(name, ".") == 0) {
864127501Salc		NG_NODE_REF(here);
865127501Salc		return(here);
86613907Sdyson	}
86713907Sdyson
86813907Sdyson	/* Check for name-by-ID */
86913907Sdyson	if ((temp = ng_decodeidname(name)) != 0) {
87013907Sdyson		return (ng_ID2noderef(temp));
87113907Sdyson	}
87213907Sdyson
87313907Sdyson	/* Find node by name */
87413907Sdyson	mtx_lock(&ng_nodelist_mtx);
87513907Sdyson	LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
87613907Sdyson		if (NG_NODE_IS_VALID(node)
87713907Sdyson		&& NG_NODE_HAS_NAME(node)
87813907Sdyson		&& (strcmp(NG_NODE_NAME(node), name) == 0)) {
87913907Sdyson			break;
88013907Sdyson		}
88113907Sdyson	}
88276364Salfred	if (node)
88313951Sdyson		NG_NODE_REF(node);
88491362Salfred	mtx_unlock(&ng_nodelist_mtx);
885133049Ssilby	return (node);
886133049Ssilby}
887133049Ssilby
888133049Ssilby/*
889133049Ssilby * Decode an ID name, eg. "[f03034de]". Returns 0 if the
890133049Ssilby * string is not valid, otherwise returns the value.
891133049Ssilby */
89213907Sdysonstatic ng_ID_t
89376760Salfredng_decodeidname(const char *name)
89413951Sdyson{
89513951Sdyson	const int len = strlen(name);
89613951Sdyson	char *eptr;
89713992Sdyson	u_long val;
898133049Ssilby
89991362Salfred	/* Check for proper length, brackets, no leading junk */
90091362Salfred	if ((len < 3)
90114802Sdyson	|| (name[0] != '[')
90213907Sdyson	|| (name[len - 1] != ']')
903133049Ssilby	|| (!isxdigit(name[1]))) {
904133049Ssilby		return ((ng_ID_t)0);
90513907Sdyson	}
90613907Sdyson
90713951Sdyson	/* Decode number */
90876760Salfred	val = strtoul(name + 1, &eptr, 16);
90913951Sdyson	if ((eptr - name != len - 1)
91013951Sdyson	|| (val == ULONG_MAX)
91113951Sdyson	|| (val == 0)) {
91213992Sdyson		return ((ng_ID_t)0);
913133049Ssilby	}
91491362Salfred	return (ng_ID_t)val;
91591362Salfred}
91614802Sdyson
91713907Sdyson/*
918133049Ssilby * Remove a name from a node. This should only be called
919133049Ssilby * when shutting down and removing the node.
92013907Sdyson * IF we allow name changing this may be more resurrected.
92113907Sdyson */
92213951Sdysonvoid
92313951Sdysonng_unname(node_p node)
924119872Salc{
92513907Sdyson}
926119872Salc
92713907Sdyson/************************************************************************
92813907Sdyson			Hook routines
929133049Ssilby Names are not optional. Hooks are always connected, except for a
93013907Sdyson brief moment within these routines. On invalidation or during creation
93113907Sdyson they are connected to the 'dead' hook.
93213907Sdyson************************************************************************/
93313907Sdyson
93413907Sdyson/*
93513907Sdyson * Remove a hook reference
93613907Sdyson */
937112981Shsuvoid
93813907Sdysonng_unref_hook(hook_p hook)
93914802Sdyson{
94014802Sdyson	int v;
94113907Sdyson
94213992Sdyson	if (hook == &ng_deadhook) {
94313992Sdyson		return;
94413992Sdyson	}
94513992Sdyson	do {
94614037Sdyson		v = hook->hk_refs;
947133049Ssilby	} while (! atomic_cmpset_int(&hook->hk_refs, v, v - 1));
94891362Salfred
94991362Salfred	if (v == 1) { /* we were the last */
950133049Ssilby		if (_NG_HOOK_NODE(hook)) { /* it'll probably be ng_deadnode */
95113907Sdyson			_NG_NODE_UNREF((_NG_HOOK_NODE(hook)));
95213907Sdyson			hook->hk_node = NULL;
953126131Sgreen		}
954126131Sgreen		NG_FREE_HOOK(hook);
95513907Sdyson	}
95613907Sdyson}
95713907Sdyson
95813907Sdyson/*
95913907Sdyson * Add an unconnected hook to a node. Only used internally.
96013907Sdyson * Assumes node is locked. (XXX not yet true )
96113907Sdyson */
96213907Sdysonstatic int
96313907Sdysonng_add_hook(node_p node, const char *name, hook_p *hookp)
96413907Sdyson{
96576760Salfred	hook_p hook;
96613907Sdyson	int error = 0;
96713907Sdyson
96813907Sdyson	/* Check that the given name is good */
96976760Salfred	if (name == NULL) {
97013907Sdyson		TRAP_ERROR();
97114037Sdyson		return (EINVAL);
972124394Sdes	}
97316960Sdyson	if (ng_findhook(node, name) != NULL) {
974101941Srwatson		TRAP_ERROR();
97516960Sdyson		return (EEXIST);
97613907Sdyson	}
977101941Srwatson
97883366Sjulian	/* Allocate the hook and link it up */
97945311Sdt	NG_ALLOC_HOOK(hook);
98013907Sdyson	if (hook == NULL) {
98113675Sdyson		TRAP_ERROR();
982133790Ssilby		return (ENOMEM);
98316960Sdyson	}
98416960Sdyson	hook->hk_refs = 1;		/* add a reference for us to return */
985109153Sdillon	hook->hk_flags = HK_INVALID;
98616960Sdyson	hook->hk_peer = &ng_deadhook;	/* start off this way */
98716960Sdyson	hook->hk_node = node;
98891395Salfred	NG_NODE_REF(node);		/* each hook counts as a reference */
989133049Ssilby
990133049Ssilby	/* Set hook name */
991133049Ssilby	strlcpy(NG_HOOK_NAME(hook), name, NG_HOOKSIZ);
992133049Ssilby
993133049Ssilby	/*
99413675Sdyson	 * Check if the node type code has something to say about it
99513675Sdyson	 * If it fails, the unref of the hook will also unref the node.
99613675Sdyson	 */
997125364Srwatson	if (node->nd_type->newhook != NULL) {
998133049Ssilby		if ((error = (*node->nd_type->newhook)(node, hook, name))) {
99991395Salfred			NG_HOOK_UNREF(hook);	/* this frees the hook */
100076760Salfred			return (error);
100113675Sdyson		}
1002101768Srwatson	}
1003125293Srwatson	/*
1004101768Srwatson	 * The 'type' agrees so far, so go ahead and link it in.
1005133049Ssilby	 * We'll ask again later when we actually connect the hooks.
1006101768Srwatson	 */
1007101768Srwatson	LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
1008101768Srwatson	node->nd_numhooks++;
1009101768Srwatson	NG_HOOK_REF(hook);	/* one for the node */
101077676Sdillon
101113675Sdyson	if (hookp)
1012133790Ssilby		*hookp = hook;
1013133790Ssilby	return (0);
1014133790Ssilby}
1015133790Ssilby
1016133790Ssilby/*
1017133790Ssilby * Find a hook
1018133790Ssilby *
1019133790Ssilby * Node types may supply their own optimized routines for finding
1020133790Ssilby * hooks.  If none is supplied, we just do a linear search.
1021133790Ssilby * XXX Possibly we should add a reference to the hook?
1022133790Ssilby */
102317163Sdysonhook_p
1024133790Ssilbyng_findhook(node_p node, const char *name)
1025133790Ssilby{
1026133790Ssilby	hook_p hook;
1027133790Ssilby
1028133790Ssilby	if (node->nd_type->findhook != NULL)
1029133790Ssilby		return (*node->nd_type->findhook)(node, name);
1030133790Ssilby	LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
1031133790Ssilby		if (NG_HOOK_IS_VALID(hook)
1032133790Ssilby		&& (strcmp(NG_HOOK_NAME(hook), name) == 0))
1033133790Ssilby			return (hook);
1034133049Ssilby	}
1035133790Ssilby	return (NULL);
1036133049Ssilby}
103713907Sdyson
1038133790Ssilby/*
1039133790Ssilby * Destroy a hook
1040133790Ssilby *
1041133790Ssilby * As hooks are always attached, this really destroys two hooks.
1042133790Ssilby * The one given, and the one attached to it. Disconnect the hooks
1043133790Ssilby * from each other first. We reconnect the peer hook to the 'dead'
1044133790Ssilby * hook so that it can still exist after we depart. We then
1045133790Ssilby * send the peer its own destroy message. This ensures that we only
1046133790Ssilby * interact with the peer's structures when it is locked processing that
1047133790Ssilby * message. We hold a reference to the peer hook so we are guaranteed that
1048133790Ssilby * the peer hook and node are still going to exist until
104977676Sdillon * we are finished there as the hook holds a ref on the node.
1050133049Ssilby * We run this same code again on the peer hook, but that time it is already
1051124394Sdes * attached to the 'dead' hook.
105213913Sdyson *
105377676Sdillon * This routine is called at all stages of hook creation
105413675Sdyson * on error detection and must be able to handle any such stage.
105513907Sdyson */
105676760Salfredvoid
1057133049Ssilbyng_destroy_hook(hook_p hook)
1058133049Ssilby{
1059133049Ssilby	hook_p peer;
1060133049Ssilby	node_p node;
1061133049Ssilby
1062133049Ssilby	if (hook == &ng_deadhook) {	/* better safe than sorry */
106314037Sdyson		printf("ng_destroy_hook called on deadhook\n");
106413907Sdyson		return;
106513907Sdyson	}
106613907Sdyson
106716416Sdyson	/*
106816416Sdyson	 * Protect divorce process with mutex, to avoid races on
106958505Sdillon	 * simultaneous disconnect.
107058505Sdillon	 */
107158505Sdillon	mtx_lock(&ng_topo_mtx);
107213907Sdyson
107317163Sdyson	hook->hk_flags |= HK_INVALID;
1074133790Ssilby
1075127501Salc	peer = NG_HOOK_PEER(hook);
1076133049Ssilby	node = NG_HOOK_NODE(hook);
1077105009Salfred
107876760Salfred	if (peer && (peer != &ng_deadhook)) {
107913907Sdyson		/*
108013907Sdyson		 * Set the peer to point to ng_deadhook
108191362Salfred		 * from this moment on we are effectively independent it.
108214037Sdyson		 * send it an rmhook message of it's own.
108313907Sdyson		 */
108413907Sdyson		peer->hk_peer = &ng_deadhook;	/* They no longer know us */
108513907Sdyson		hook->hk_peer = &ng_deadhook;	/* Nor us, them */
108613907Sdyson		if (NG_HOOK_NODE(peer) == &ng_deadnode) {
108713907Sdyson			/*
108858505Sdillon			 * If it's already divorced from a node,
108958505Sdillon			 * just free it.
109013907Sdyson			 */
1091133049Ssilby			mtx_unlock(&ng_topo_mtx);
109213992Sdyson		} else {
109313992Sdyson			mtx_unlock(&ng_topo_mtx);
109413992Sdyson			ng_rmhook_self(peer); 	/* Send it a surprise */
109513992Sdyson		}
1096133049Ssilby		NG_HOOK_UNREF(peer);		/* account for peer link */
109791395Salfred		NG_HOOK_UNREF(hook);		/* account for peer link */
109891362Salfred	} else
109913907Sdyson		mtx_unlock(&ng_topo_mtx);
110013907Sdyson
1101133049Ssilby	mtx_assert(&ng_topo_mtx, MA_NOTOWNED);
1102133049Ssilby
110313907Sdyson	/*
110413907Sdyson	 * Remove the hook from the node's list to avoid possible recursion
110513907Sdyson	 * in case the disconnection results in node shutdown.
110614644Sdyson	 */
110714644Sdyson	if (node == &ng_deadnode) { /* happens if called from ng_con_nodes() */
110813913Sdyson		return;
110913913Sdyson	}
111013907Sdyson	LIST_REMOVE(hook, hk_hooks);
1111118230Spb	node->nd_numhooks--;
1112133049Ssilby	if (node->nd_type->disconnect) {
1113133049Ssilby		/*
111476760Salfred		 * The type handler may elect to destroy the node so don't
1115133049Ssilby		 * trust its existence after this point. (except
1116133049Ssilby		 * that we still hold a reference on it. (which we
1117133049Ssilby		 * inherrited from the hook we are destroying)
1118133049Ssilby		 */
1119133049Ssilby		(*node->nd_type->disconnect) (hook);
1120133049Ssilby	}
1121133049Ssilby
1122133049Ssilby	/*
1123133049Ssilby	 * Note that because we will point to ng_deadnode, the original node
1124133049Ssilby	 * is not decremented automatically so we do that manually.
1125133049Ssilby	 */
1126133049Ssilby	_NG_HOOK_NODE(hook) = &ng_deadnode;
1127133049Ssilby	NG_NODE_UNREF(node);	/* We no longer point to it so adjust count */
1128133049Ssilby	NG_HOOK_UNREF(hook);	/* Account for linkage (in list) to node */
1129133049Ssilby}
1130133049Ssilby
1131133049Ssilby/*
1132133049Ssilby * Take two hooks on a node and merge the connection so that the given node
1133133049Ssilby * is effectively bypassed.
113454534Stegge */
1135133049Ssilbyint
1136133049Ssilbyng_bypass(hook_p hook1, hook_p hook2)
1137133049Ssilby{
1138133049Ssilby	if (hook1->hk_node != hook2->hk_node) {
1139133049Ssilby		TRAP_ERROR();
1140133049Ssilby		return (EINVAL);
1141133049Ssilby	}
1142133049Ssilby	hook1->hk_peer->hk_peer = hook2->hk_peer;
1143133049Ssilby	hook2->hk_peer->hk_peer = hook1->hk_peer;
1144133049Ssilby
1145133049Ssilby	hook1->hk_peer = &ng_deadhook;
114654534Stegge	hook2->hk_peer = &ng_deadhook;
1147133049Ssilby
1148133049Ssilby	NG_HOOK_UNREF(hook1);
1149133049Ssilby	NG_HOOK_UNREF(hook2);
115054534Stegge
1151124394Sdes	/* XXX If we ever cache methods on hooks update them as well */
115291395Salfred	ng_destroy_hook(hook1);
1153133049Ssilby	ng_destroy_hook(hook2);
1154133049Ssilby	return (0);
1155133049Ssilby}
115691395Salfred
1157133049Ssilby/*
1158133049Ssilby * Install a new netgraph type
1159133049Ssilby */
1160133049Ssilbyint
1161133049Ssilbyng_newtype(struct ng_type *tp)
1162133049Ssilby{
1163133049Ssilby	const size_t namelen = strlen(tp->name);
1164133049Ssilby
1165133049Ssilby	/* Check version and type name fields */
1166133049Ssilby	if ((tp->version != NG_ABI_VERSION)
116754534Stegge	|| (namelen == 0)
1168124394Sdes	|| (namelen >= NG_TYPESIZ)) {
1169133049Ssilby		TRAP_ERROR();
1170133049Ssilby		if (tp->version != NG_ABI_VERSION) {
1171133049Ssilby			printf("Netgraph: Node type rejected. ABI mismatch. Suggest recompile\n");
1172133049Ssilby		}
117313675Sdyson		return (EINVAL);
1174133049Ssilby	}
117513675Sdyson
117613675Sdyson	/* Check for name collision */
117713675Sdyson	if (ng_findtype(tp->name) != NULL) {
117813675Sdyson		TRAP_ERROR();
117913675Sdyson		return (EEXIST);
118013675Sdyson	}
118113675Sdyson
118213675Sdyson
118314037Sdyson	/* Link in new type */
118413675Sdyson	mtx_lock(&ng_typelist_mtx);
118513675Sdyson	LIST_INSERT_HEAD(&ng_typelist, tp, types);
118613675Sdyson	tp->refs = 1;	/* first ref is linked list */
118716960Sdyson	mtx_unlock(&ng_typelist_mtx);
118813907Sdyson	return (0);
1189133049Ssilby}
119013675Sdyson
119113675Sdyson/*
119213907Sdyson * unlink a netgraph type
119314037Sdyson * If no examples exist
119414037Sdyson */
119529356Speterint
119614037Sdysonng_rmtype(struct ng_type *tp)
119714037Sdyson{
119814037Sdyson	/* Check for name collision */
119913675Sdyson	if (tp->refs != 1) {
1200133049Ssilby		TRAP_ERROR();
120191395Salfred		return (EBUSY);
120291362Salfred	}
120376760Salfred
120413675Sdyson	/* Unlink type */
120513675Sdyson	mtx_lock(&ng_typelist_mtx);
120613675Sdyson	LIST_REMOVE(tp, types);
120713675Sdyson	mtx_unlock(&ng_typelist_mtx);
1208133049Ssilby	return (0);
120914644Sdyson}
121077676Sdillon
121176760Salfred/*
121276760Salfred * Look for a type of the name given
121313675Sdyson */
121413675Sdysonstruct ng_type *
121513675Sdysonng_findtype(const char *typename)
121613675Sdyson{
121713675Sdyson	struct ng_type *type;
121813675Sdyson
121913675Sdyson	mtx_lock(&ng_typelist_mtx);
122013675Sdyson	LIST_FOREACH(type, &ng_typelist, types) {
122113675Sdyson		if (strcmp(type->name, typename) == 0)
122213675Sdyson			break;
122313675Sdyson	}
122413909Sdyson	mtx_unlock(&ng_typelist_mtx);
122513909Sdyson	return (type);
122613909Sdyson}
122713909Sdyson
122813907Sdyson/************************************************************************
122977676Sdillon			Composite routines
123077676Sdillon************************************************************************/
123113907Sdyson/*
123277676Sdillon * Connect two nodes using the specified hooks, using queued functions.
123313913Sdyson */
123424101Sbdestatic int
123555112Sbdeng_con_part3(node_p node, item_p item, hook_p hook)
123624101Sbde{
123714037Sdyson	int	error = 0;
123814037Sdyson
123929356Speter	/*
124014037Sdyson	 * When we run, we know that the node 'node' is locked for us.
124114177Sdyson	 * Our caller has a reference on the hook.
124214037Sdyson	 * Our caller has a reference on the node.
124313907Sdyson	 * (In this case our caller is ng_apply_item() ).
1244133049Ssilby	 * The peer hook has a reference on the hook.
124591395Salfred	 * We are all set up except for the final call to the node, and
124676760Salfred	 * the clearing of the INVALID flag.
124713675Sdyson	 */
124813675Sdyson	if (NG_HOOK_NODE(hook) == &ng_deadnode) {
124913675Sdyson		/*
125013675Sdyson		 * The node must have been freed again since we last visited
125113675Sdyson		 * here. ng_destry_hook() has this effect but nothing else does.
1252104094Sphk		 * We should just release our references and
1253102003Srwatson		 * free anything we can think of.
125413675Sdyson		 * Since we know it's been destroyed, and it's our caller
125536735Sdfr		 * that holds the references, just return.
125699009Salfred		 */
1257102003Srwatson		ERROUT(ENOENT);
125883366Sjulian	}
125913675Sdyson	if (hook->hk_node->nd_type->connect) {
1260109153Sdillon		if ((error = (*hook->hk_node->nd_type->connect) (hook))) {
1261101768Srwatson			ng_destroy_hook(hook);	/* also zaps peer */
126213675Sdyson			printf("failed in ng_con_part3()\n");
1263104269Srwatson			ERROUT(error);
1264104269Srwatson		}
1265104269Srwatson	}
1266125293Srwatson	/*
1267121970Srwatson	 *  XXX this is wrong for SMP. Possibly we need
1268121970Srwatson	 * to separate out 'create' and 'invalid' flags.
1269101768Srwatson	 * should only set flags on hooks we have locked under our node.
1270121970Srwatson	 */
1271101768Srwatson	hook->hk_flags &= ~HK_INVALID;
1272101768Srwatsondone:
1273137752Sphk	NG_FREE_ITEM(item);
127413675Sdyson	return (error);
127513675Sdyson}
127613675Sdyson
1277137752Sphkstatic int
127813675Sdysonng_con_part2(node_p node, item_p item, hook_p hook)
127913675Sdyson{
128013675Sdyson	hook_p	peer;
128113675Sdyson	int	error = 0;
128213675Sdyson
128313675Sdyson	/*
128413675Sdyson	 * When we run, we know that the node 'node' is locked for us.
1285137752Sphk	 * Our caller has a reference on the hook.
128613675Sdyson	 * Our caller has a reference on the node.
128713675Sdyson	 * (In this case our caller is ng_apply_item() ).
128814037Sdyson	 * The peer hook has a reference on the hook.
128914037Sdyson	 * our node pointer points to the 'dead' node.
129014037Sdyson	 * First check the hook name is unique.
129114037Sdyson	 * Should not happen because we checked before queueing this.
1292137752Sphk	 */
129313675Sdyson	if (ng_findhook(node, NG_HOOK_NAME(hook)) != NULL) {
129441086Struckman		TRAP_ERROR();
1295137752Sphk		ng_destroy_hook(hook); /* should destroy peer too */
1296137752Sphk		printf("failed in ng_con_part2()\n");
129741086Struckman		ERROUT(EEXIST);
129841086Struckman	}
1299104393Struckman	/*
1300137752Sphk	 * Check if the node type code has something to say about it
130113675Sdyson	 * If it fails, the unref of the hook will also unref the attached node,
130241086Struckman	 * however since that node is 'ng_deadnode' this will do nothing.
130341086Struckman	 * The peer hook will also be destroyed.
1304137752Sphk	 */
1305137752Sphk	if (node->nd_type->newhook != NULL) {
130641086Struckman		if ((error = (*node->nd_type->newhook)(node, hook,
130741086Struckman		    hook->hk_name))) {
130818863Sdyson			ng_destroy_hook(hook); /* should destroy peer too */
1309104393Struckman			printf("failed in ng_con_part2()\n");
1310137752Sphk			ERROUT(error);
131113675Sdyson		}
1312137752Sphk	}
1313137752Sphk
1314137764Sphk	/*
131513675Sdyson	 * The 'type' agrees so far, so go ahead and link it in.
1316104269Srwatson	 * We'll ask again later when we actually connect the hooks.
1317137752Sphk	 */
131813675Sdyson	hook->hk_node = node;		/* just overwrite ng_deadnode */
131913675Sdyson	NG_NODE_REF(node);		/* each hook counts as a reference */
1320104094Sphk	LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
1321101983Srwatson	node->nd_numhooks++;
132213675Sdyson	NG_HOOK_REF(hook);	/* one for the node */
132329356Speter
1324101983Srwatson	/*
132583366Sjulian	 * We now have a symmetrical situation, where both hooks have been
132613675Sdyson	 * linked to their nodes, the newhook methods have been called
1327109153Sdillon	 * And the references are all correct. The hooks are still marked
132813675Sdyson	 * as invalid, as we have not called the 'connect' methods
132929356Speter	 * yet.
1330101768Srwatson	 * We can call the local one immediately as we have the
1331101768Srwatson	 * node locked, but we need to queue the remote one.
1332101768Srwatson	 */
133313675Sdyson	if (hook->hk_node->nd_type->connect) {
133413675Sdyson		if ((error = (*hook->hk_node->nd_type->connect) (hook))) {
133591362Salfred			ng_destroy_hook(hook);	/* also zaps peer */
1336101768Srwatson			printf("failed in ng_con_part2(A)\n");
1337125293Srwatson			ERROUT(error);
1338101768Srwatson		}
1339101768Srwatson	}
1340101768Srwatson
134129356Speter	/*
134229356Speter	 * Acquire topo mutex to avoid race with ng_destroy_hook().
134329356Speter	 */
134429356Speter	mtx_lock(&ng_topo_mtx);
134529356Speter	peer = hook->hk_peer;
134613675Sdyson	if (peer == &ng_deadhook) {
134729356Speter		mtx_unlock(&ng_topo_mtx);
1348125364Srwatson		printf("failed in ng_con_part2(B)\n");
134943311Sdillon		ng_destroy_hook(hook);
135043311Sdillon		ERROUT(ENOENT);
135129356Speter	}
135213675Sdyson	mtx_unlock(&ng_topo_mtx);
135329356Speter
1354125364Srwatson	if ((error = ng_send_fn2_fwd(item, peer->hk_node, peer,
135529356Speter	    &ng_con_part3, NULL, 0))) {
135629356Speter		printf("failed in ng_con_part2(C)\n");
135729356Speter		ng_destroy_hook(hook);	/* also zaps peer */
135829356Speter		return (error);		/* item was consumed. */
135929356Speter	}
136083805Sjhb	hook->hk_flags &= ~HK_INVALID; /* need both to be able to work */
136129356Speter	return (0);			/* item was consumed. */
136213675Sdysondone:
136313675Sdyson	NG_FREE_ITEM(item);
136429356Speter	return (error);
136583805Sjhb}
136630164Speter
136713907Sdyson/*
136813675Sdyson * Connect this node with another node. We assume that this node is
1369101768Srwatson * currently locked, as we are only called from an NGM_CONNECT message.
1370101768Srwatson */
1371101768Srwatsonstatic int
137291362Salfredng_con_nodes(item_p item, node_p node, const char *name,
137329356Speter    node_p node2, const char *name2)
137429356Speter{
137513675Sdyson	int	error;
137613675Sdyson	hook_p	hook;
137798989Salfred	hook_p	hook2;
137898989Salfred
137998989Salfred	if (ng_findhook(node2, name2) != NULL) {
138098989Salfred		return(EEXIST);
138152983Speter	}
1382101983Srwatson	if ((error = ng_add_hook(node, name, &hook)))  /* gives us a ref */
138352983Speter		return (error);
138452983Speter	/* Allocate the other hook and link it up */
1385101983Srwatson	NG_ALLOC_HOOK(hook2);
138683366Sjulian	if (hook2 == NULL) {
138713675Sdyson		TRAP_ERROR();
1388109153Sdillon		ng_destroy_hook(hook);	/* XXX check ref counts so far */
1389101768Srwatson		NG_HOOK_UNREF(hook);	/* including our ref */
1390101768Srwatson		return (ENOMEM);
139152983Speter	}
1392104269Srwatson	hook2->hk_refs = 1;		/* start with a reference for us. */
1393125293Srwatson	hook2->hk_flags = HK_INVALID;
1394104269Srwatson	hook2->hk_peer = hook;		/* Link the two together */
1395101768Srwatson	hook->hk_peer = hook2;
1396101768Srwatson	NG_HOOK_REF(hook);		/* Add a ref for the peer to each*/
1397101768Srwatson	NG_HOOK_REF(hook2);
1398100527Salfred	hook2->hk_node = &ng_deadnode;
139917124Sbde	strlcpy(NG_HOOK_NAME(hook2), name2, NG_HOOKSIZ);
1400133790Ssilby
1401132436Ssilby	/*
1402132436Ssilby	 * Queue the function above.
1403132436Ssilby	 * Procesing continues in that function in the lock context of
1404132436Ssilby	 * the other node.
140513675Sdyson	 */
140634901Sphk	if ((error = ng_send_fn2_cont(item, node2, hook2,
140734901Sphk	    &ng_con_part2, NULL, 0))) {
140834901Sphk		printf("failed in ng_con_nodes(): %d\n", error);
140960404Schris		ng_destroy_hook(hook);	/* also zaps peer */
141060404Schris	}
141117124Sbde
141260404Schris	NG_HOOK_UNREF(hook);		/* Let each hook go if it wants to */
141317124Sbde	NG_HOOK_UNREF(hook2);
141417124Sbde	return (error);
141576760Salfred}
141613675Sdyson
141713675Sdyson/*
141813675Sdyson * Make a peer and connect.
141913675Sdyson * We assume that the local node is locked.
142083366Sjulian * The new node probably doesn't need a lock until
142113675Sdyson * it has a hook, because it cannot really have any work until then,
142283366Sjulian * but we should think about it a bit more.
142313675Sdyson *
1424109153Sdillon * The problem may come if the other node also fires up
142516322Sgpalmer * some hardware or a timer or some other source of activation,
142649413Sgreen * also it may already get a command msg via it's ID.
1427109153Sdillon *
142896122Salfred * We could use the same method as ng_con_nodes() but we'd have
142913675Sdyson * to add ability to remove the node when failing. (Not hard, just
143076760Salfred * make arg1 point to the node to remove).
143113675Sdyson * Unless of course we just ignore failure to connect and leave
143213675Sdyson * an unconnected node?
143376364Salfred */
143476364Salfredstatic int
143576364Salfredng_mkpeer(node_p node, const char *name, const char *name2, char *type)
143676364Salfred{
143791412Salfred	node_p	node2;
1438125293Srwatson	hook_p	hook1, hook2;
1439125293Srwatson	int	error;
144076364Salfred
144176364Salfred	if ((error = ng_make_node(type, &node2))) {
1442110816Salc		return (error);
1443118764Ssilby	}
1444118764Ssilby
1445118764Ssilby	if ((error = ng_add_hook(node, name, &hook1))) { /* gives us a ref */
144676364Salfred		ng_rmnode(node2, NULL, NULL, 0);
144776364Salfred		return (error);
144876364Salfred	}
1449127501Salc
145076364Salfred	if ((error = ng_add_hook(node2, name2, &hook2))) {
145176364Salfred		ng_rmnode(node2, NULL, NULL, 0);
145276364Salfred		ng_destroy_hook(hook1);
145376364Salfred		NG_HOOK_UNREF(hook1);
145476364Salfred		return (error);
145576364Salfred	}
145676364Salfred
145713675Sdyson	/*
145813675Sdyson	 * Actually link the two hooks together.
145913675Sdyson	 */
146013675Sdyson	hook1->hk_peer = hook2;
146113675Sdyson	hook2->hk_peer = hook1;
146213675Sdyson
146313675Sdyson	/* Each hook is referenced by the other */
1464125293Srwatson	NG_HOOK_REF(hook1);
146513907Sdyson	NG_HOOK_REF(hook2);
146676364Salfred
1467125293Srwatson	/* Give each node the opportunity to veto the pending connection */
146891968Salfred	if (hook1->hk_node->nd_type->connect) {
1469125293Srwatson		error = (*hook1->hk_node->nd_type->connect) (hook1);
1470133049Ssilby	}
1471125293Srwatson
147291968Salfred	if ((error == 0) && hook2->hk_node->nd_type->connect) {
147391968Salfred		error = (*hook2->hk_node->nd_type->connect) (hook2);
147413907Sdyson
147591968Salfred	}
147691968Salfred
147791968Salfred	/*
147891968Salfred	 * drop the references we were holding on the two hooks.
1479126131Sgreen	 */
148091968Salfred	if (error) {
148191968Salfred		ng_destroy_hook(hook2);	/* also zaps hook1 */
1482126131Sgreen		ng_rmnode(node2, NULL, NULL, 0);
1483133049Ssilby	} else {
148491968Salfred		/* As a last act, allow the hooks to be used */
1485133049Ssilby		hook1->hk_flags &= ~HK_INVALID;
148691968Salfred		hook2->hk_flags &= ~HK_INVALID;
148713675Sdyson	}
1488101768Srwatson	NG_HOOK_UNREF(hook1);
148991968Salfred	NG_HOOK_UNREF(hook2);
1490125293Srwatson	return (error);
149191968Salfred}
1492125293Srwatson
1493125293Srwatson/************************************************************************
149491968Salfred		Utility routines to send self messages
149513907Sdyson************************************************************************/
149691968Salfred
149791968Salfred/* Shut this node down as soon as everyone is clear of it */
1498133741Sjmg/* Should add arg "immediately" to jump the queue */
149991968Salfredint
1500125293Srwatsonng_rmnode_self(node_p node)
150191968Salfred{
1502125293Srwatson	int		error;
1503125293Srwatson
1504125293Srwatson	if (node == &ng_deadnode)
1505125293Srwatson		return (0);
150691968Salfred	node->nd_flags |= NGF_INVALID;
1507125293Srwatson	if (node->nd_flags & NGF_CLOSING)
1508125293Srwatson		return (0);
1509125293Srwatson
1510125293Srwatson	error = ng_send_fn(node, NULL, &ng_rmnode, NULL, 0);
1511126131Sgreen	return (error);
1512133741Sjmg}
1513133741Sjmg
1514125293Srwatsonstatic void
1515125293Srwatsonng_rmhook_part2(node_p node, hook_p hook, void *arg1, int arg2)
1516125293Srwatson{
1517125293Srwatson	ng_destroy_hook(hook);
1518125293Srwatson	return ;
1519125293Srwatson}
152091968Salfred
1521125293Srwatsonint
1522125293Srwatsonng_rmhook_self(hook_p hook)
1523125293Srwatson{
1524125293Srwatson	int		error;
1525125293Srwatson	node_p node = NG_HOOK_NODE(hook);
1526125293Srwatson
152713675Sdyson	if (node == &ng_deadnode)
152859288Sjlemon		return (0);
152972521Sjlemon
153059288Sjlemon	error = ng_send_fn(node, hook, &ng_rmhook_part2, NULL, 0);
153172521Sjlemon	return (error);
153259288Sjlemon}
153389306Salfred
153459288Sjlemon/***********************************************************************
1535109153Sdillon * Parse and verify a string of the form:  <NODE:><PATH>
1536126131Sgreen *
153772521Sjlemon * Such a string can refer to a specific node or a specific hook
153872521Sjlemon * on a specific node, depending on how you look at it. In the
153972521Sjlemon * latter case, the PATH component must not end in a dot.
154072521Sjlemon *
154172521Sjlemon * Both <NODE:> and <PATH> are optional. The <PATH> is a string
154272521Sjlemon * of hook names separated by dots. This breaks out the original
1543126131Sgreen * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1544101382Sdes * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1545126131Sgreen * the final hook component of <PATH>, if any, otherwise NULL.
1546118929Sjmg *
1547126131Sgreen * This returns -1 if the path is malformed. The char ** are optional.
1548126131Sgreen ***********************************************************************/
154972521Sjlemonint
155072521Sjlemonng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1551126131Sgreen{
1552133741Sjmg	char	*node, *path, *hook;
155372521Sjlemon	int	k;
155478292Sjlemon
1555133741Sjmg	/*
155691372Salfred	 * Extract absolute NODE, if any
155759288Sjlemon	 */
155859288Sjlemon	for (path = addr; *path && *path != ':'; path++);
155959288Sjlemon	if (*path) {
156059288Sjlemon		node = addr;	/* Here's the NODE */
156159288Sjlemon		*path++ = '\0';	/* Here's the PATH */
156259288Sjlemon
1563121018Sjmg		/* Node name must not be empty */
156459288Sjlemon		if (!*node)
1565126131Sgreen			return -1;
1566121018Sjmg
1567126131Sgreen		/* A name of "." is OK; otherwise '.' not allowed */
1568126131Sgreen		if (strcmp(node, ".") != 0) {
1569121018Sjmg			for (k = 0; node[k]; k++)
1570126131Sgreen				if (node[k] == '.')
1571121018Sjmg					return -1;
1572121018Sjmg		}
1573133741Sjmg	} else {
157491372Salfred		node = NULL;	/* No absolute NODE */
157559288Sjlemon		path = addr;	/* Here's the PATH */
157659288Sjlemon	}
157759288Sjlemon
157859288Sjlemon	/* Snoop for illegal characters in PATH */
157959288Sjlemon	for (k = 0; path[k]; k++)
158059288Sjlemon		if (path[k] == ':')
1581109153Sdillon			return -1;
158259288Sjlemon
1583133741Sjmg	/* Check for no repeated dots in PATH */
158459288Sjlemon	for (k = 0; path[k]; k++)
158591372Salfred		if (path[k] == '.' && path[k + 1] == '.')
158659288Sjlemon			return -1;
158759288Sjlemon
158859288Sjlemon	/* Remove extra (degenerate) dots from beginning or end of PATH */
158959288Sjlemon	if (path[0] == '.')
159059288Sjlemon		path++;
1591125364Srwatson	if (*path && path[strlen(path) - 1] == '.')
159291372Salfred		path[strlen(path) - 1] = 0;
159391372Salfred
159459288Sjlemon	/* If PATH has a dot, then we're not talking about a hook */
159559288Sjlemon	if (*path) {
1596133741Sjmg		for (hook = path, k = 0; path[k]; k++)
159791372Salfred			if (path[k] == '.') {
1598133741Sjmg				hook = NULL;
159959288Sjlemon				break;
160059288Sjlemon			}
160159288Sjlemon	} else
160259288Sjlemon		path = hook = NULL;
160359288Sjlemon
160459288Sjlemon	/* Done */
1605109153Sdillon	if (nodep)
160659288Sjlemon		*nodep = node;
160759288Sjlemon	if (pathp)
160891372Salfred		*pathp = path;
1609125364Srwatson	if (hookp)
161059288Sjlemon		*hookp = hook;
1611124394Sdes	return (0);
161291372Salfred}
161359288Sjlemon
161459288Sjlemon/*
161559288Sjlemon * Given a path, which may be absolute or relative, and a starting node,
161665855Sjlemon * return the destination node.
161759288Sjlemon */
161859288Sjlemonint
161991372Salfredng_path2noderef(node_p here, const char *address,
162059288Sjlemon				node_p *destp, hook_p *lasthook)
162159288Sjlemon{
1622	char    fullpath[NG_PATHSIZ];
1623	char   *nodename, *path, pbuf[2];
1624	node_p  node, oldnode;
1625	char   *cp;
1626	hook_p hook = NULL;
1627
1628	/* Initialize */
1629	if (destp == NULL) {
1630		TRAP_ERROR();
1631		return EINVAL;
1632	}
1633	*destp = NULL;
1634
1635	/* Make a writable copy of address for ng_path_parse() */
1636	strncpy(fullpath, address, sizeof(fullpath) - 1);
1637	fullpath[sizeof(fullpath) - 1] = '\0';
1638
1639	/* Parse out node and sequence of hooks */
1640	if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1641		TRAP_ERROR();
1642		return EINVAL;
1643	}
1644	if (path == NULL) {
1645		pbuf[0] = '.';	/* Needs to be writable */
1646		pbuf[1] = '\0';
1647		path = pbuf;
1648	}
1649
1650	/*
1651	 * For an absolute address, jump to the starting node.
1652	 * Note that this holds a reference on the node for us.
1653	 * Don't forget to drop the reference if we don't need it.
1654	 */
1655	if (nodename) {
1656		node = ng_name2noderef(here, nodename);
1657		if (node == NULL) {
1658			TRAP_ERROR();
1659			return (ENOENT);
1660		}
1661	} else {
1662		if (here == NULL) {
1663			TRAP_ERROR();
1664			return (EINVAL);
1665		}
1666		node = here;
1667		NG_NODE_REF(node);
1668	}
1669
1670	/*
1671	 * Now follow the sequence of hooks
1672	 * XXX
1673	 * We actually cannot guarantee that the sequence
1674	 * is not being demolished as we crawl along it
1675	 * without extra-ordinary locking etc.
1676	 * So this is a bit dodgy to say the least.
1677	 * We can probably hold up some things by holding
1678	 * the nodelist mutex for the time of this
1679	 * crawl if we wanted.. At least that way we wouldn't have to
1680	 * worry about the nodes disappearing, but the hooks would still
1681	 * be a problem.
1682	 */
1683	for (cp = path; node != NULL && *cp != '\0'; ) {
1684		char *segment;
1685
1686		/*
1687		 * Break out the next path segment. Replace the dot we just
1688		 * found with a NUL; "cp" points to the next segment (or the
1689		 * NUL at the end).
1690		 */
1691		for (segment = cp; *cp != '\0'; cp++) {
1692			if (*cp == '.') {
1693				*cp++ = '\0';
1694				break;
1695			}
1696		}
1697
1698		/* Empty segment */
1699		if (*segment == '\0')
1700			continue;
1701
1702		/* We have a segment, so look for a hook by that name */
1703		hook = ng_findhook(node, segment);
1704
1705		/* Can't get there from here... */
1706		if (hook == NULL
1707		    || NG_HOOK_PEER(hook) == NULL
1708		    || NG_HOOK_NOT_VALID(hook)
1709		    || NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))) {
1710			TRAP_ERROR();
1711			NG_NODE_UNREF(node);
1712#if 0
1713			printf("hooknotvalid %s %s %d %d %d %d ",
1714					path,
1715					segment,
1716					hook == NULL,
1717					NG_HOOK_PEER(hook) == NULL,
1718					NG_HOOK_NOT_VALID(hook),
1719					NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook)));
1720#endif
1721			return (ENOENT);
1722		}
1723
1724		/*
1725		 * Hop on over to the next node
1726		 * XXX
1727		 * Big race conditions here as hooks and nodes go away
1728		 * *** Idea.. store an ng_ID_t in each hook and use that
1729		 * instead of the direct hook in this crawl?
1730		 */
1731		oldnode = node;
1732		if ((node = NG_PEER_NODE(hook)))
1733			NG_NODE_REF(node);	/* XXX RACE */
1734		NG_NODE_UNREF(oldnode);	/* XXX another race */
1735		if (NG_NODE_NOT_VALID(node)) {
1736			NG_NODE_UNREF(node);	/* XXX more races */
1737			node = NULL;
1738		}
1739	}
1740
1741	/* If node somehow missing, fail here (probably this is not needed) */
1742	if (node == NULL) {
1743		TRAP_ERROR();
1744		return (ENXIO);
1745	}
1746
1747	/* Done */
1748	*destp = node;
1749	if (lasthook != NULL)
1750		*lasthook = (hook ? NG_HOOK_PEER(hook) : NULL);
1751	return (0);
1752}
1753
1754/***************************************************************\
1755* Input queue handling.
1756* All activities are submitted to the node via the input queue
1757* which implements a multiple-reader/single-writer gate.
1758* Items which cannot be handled immediately are queued.
1759*
1760* read-write queue locking inline functions			*
1761\***************************************************************/
1762
1763static __inline item_p ng_dequeue(struct ng_queue * ngq, int *rw);
1764static __inline item_p ng_acquire_read(struct ng_queue * ngq,
1765					item_p  item);
1766static __inline item_p ng_acquire_write(struct ng_queue * ngq,
1767					item_p  item);
1768static __inline void	ng_leave_read(struct ng_queue * ngq);
1769static __inline void	ng_leave_write(struct ng_queue * ngq);
1770static __inline void	ng_queue_rw(struct ng_queue * ngq,
1771					item_p  item, int rw);
1772
1773/*
1774 * Definition of the bits fields in the ng_queue flag word.
1775 * Defined here rather than in netgraph.h because no-one should fiddle
1776 * with them.
1777 *
1778 * The ordering here may be important! don't shuffle these.
1779 */
1780/*-
1781 Safety Barrier--------+ (adjustable to suit taste) (not used yet)
1782                       |
1783                       V
1784+-------+-------+-------+-------+-------+-------+-------+-------+
1785  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
1786  | |A|c|t|i|v|e| |R|e|a|d|e|r| |C|o|u|n|t| | | | | | | | | |P|A|
1787  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |O|W|
1788+-------+-------+-------+-------+-------+-------+-------+-------+
1789  \___________________________ ____________________________/ | |
1790                            V                                | |
1791                  [active reader count]                      | |
1792                                                             | |
1793            Operation Pending -------------------------------+ |
1794                                                               |
1795          Active Writer ---------------------------------------+
1796
1797
1798*/
1799#define WRITER_ACTIVE	0x00000001
1800#define OP_PENDING	0x00000002
1801#define READER_INCREMENT 0x00000004
1802#define READER_MASK	0xfffffffc	/* Not valid if WRITER_ACTIVE is set */
1803#define SAFETY_BARRIER	0x00100000	/* 128K items queued should be enough */
1804
1805/* Defines of more elaborate states on the queue */
1806/* Mask of bits a new read cares about */
1807#define NGQ_RMASK	(WRITER_ACTIVE|OP_PENDING)
1808
1809/* Mask of bits a new write cares about */
1810#define NGQ_WMASK	(NGQ_RMASK|READER_MASK)
1811
1812/* Test to decide if there is something on the queue. */
1813#define QUEUE_ACTIVE(QP) ((QP)->q_flags & OP_PENDING)
1814
1815/* How to decide what the next queued item is. */
1816#define HEAD_IS_READER(QP)  NGI_QUEUED_READER((QP)->queue)
1817#define HEAD_IS_WRITER(QP)  NGI_QUEUED_WRITER((QP)->queue) /* notused */
1818
1819/* Read the status to decide if the next item on the queue can now run. */
1820#define QUEUED_READER_CAN_PROCEED(QP)			\
1821		(((QP)->q_flags & (NGQ_RMASK & ~OP_PENDING)) == 0)
1822#define QUEUED_WRITER_CAN_PROCEED(QP)			\
1823		(((QP)->q_flags & (NGQ_WMASK & ~OP_PENDING)) == 0)
1824
1825/* Is there a chance of getting ANY work off the queue? */
1826#define NEXT_QUEUED_ITEM_CAN_PROCEED(QP)				\
1827	(QUEUE_ACTIVE(QP) && 						\
1828	((HEAD_IS_READER(QP)) ? QUEUED_READER_CAN_PROCEED(QP) :		\
1829				QUEUED_WRITER_CAN_PROCEED(QP)))
1830
1831
1832#define NGQRW_R 0
1833#define NGQRW_W 1
1834
1835/*
1836 * Taking into account the current state of the queue and node, possibly take
1837 * the next entry off the queue and return it. Return NULL if there was
1838 * nothing we could return, either because there really was nothing there, or
1839 * because the node was in a state where it cannot yet process the next item
1840 * on the queue.
1841 *
1842 * This MUST MUST MUST be called with the mutex held.
1843 */
1844static __inline item_p
1845ng_dequeue(struct ng_queue *ngq, int *rw)
1846{
1847	item_p item;
1848	u_int		add_arg;
1849
1850	mtx_assert(&ngq->q_mtx, MA_OWNED);
1851	/*
1852	 * If there is nothing queued, then just return.
1853	 * No point in continuing.
1854	 * XXXGL: assert this?
1855	 */
1856	if (!QUEUE_ACTIVE(ngq)) {
1857		CTR4(KTR_NET, "%20s: node [%x] (%p) queue empty; "
1858		    "queue flags 0x%lx", __func__,
1859		    ngq->q_node->nd_ID, ngq->q_node, ngq->q_flags);
1860		return (NULL);
1861	}
1862
1863	/*
1864	 * From here, we can assume there is a head item.
1865	 * We need to find out what it is and if it can be dequeued, given
1866	 * the current state of the node.
1867	 */
1868	if (HEAD_IS_READER(ngq)) {
1869		if (!QUEUED_READER_CAN_PROCEED(ngq)) {
1870			/*
1871			 * It's a reader but we can't use it.
1872			 * We are stalled so make sure we don't
1873			 * get called again until something changes.
1874			 */
1875			ng_worklist_remove(ngq->q_node);
1876			CTR4(KTR_NET, "%20s: node [%x] (%p) queued reader "
1877			    "can't proceed; queue flags 0x%lx", __func__,
1878			    ngq->q_node->nd_ID, ngq->q_node, ngq->q_flags);
1879			return (NULL);
1880		}
1881		/*
1882		 * Head of queue is a reader and we have no write active.
1883		 * We don't care how many readers are already active.
1884		 * Add the correct increment for the reader count.
1885		 */
1886		add_arg = READER_INCREMENT;
1887		*rw = NGQRW_R;
1888	} else if (QUEUED_WRITER_CAN_PROCEED(ngq)) {
1889		/*
1890		 * There is a pending write, no readers and no active writer.
1891		 * This means we can go ahead with the pending writer. Note
1892		 * the fact that we now have a writer, ready for when we take
1893		 * it off the queue.
1894		 *
1895		 * We don't need to worry about a possible collision with the
1896		 * fasttrack reader.
1897		 *
1898		 * The fasttrack thread may take a long time to discover that we
1899		 * are running so we would have an inconsistent state in the
1900		 * flags for a while. Since we ignore the reader count
1901		 * entirely when the WRITER_ACTIVE flag is set, this should
1902		 * not matter (in fact it is defined that way). If it tests
1903		 * the flag before this operation, the OP_PENDING flag
1904		 * will make it fail, and if it tests it later, the
1905		 * WRITER_ACTIVE flag will do the same. If it is SO slow that
1906		 * we have actually completed the operation, and neither flag
1907		 * is set by the time that it tests the flags, then it is
1908		 * actually ok for it to continue. If it completes and we've
1909		 * finished and the read pending is set it still fails.
1910		 *
1911		 * So we can just ignore it,  as long as we can ensure that the
1912		 * transition from WRITE_PENDING state to the WRITER_ACTIVE
1913		 * state is atomic.
1914		 *
1915		 * After failing, first it will be held back by the mutex, then
1916		 * when it can proceed, it will queue its request, then it
1917		 * would arrive at this function. Usually it will have to
1918		 * leave empty handed because the ACTIVE WRITER bit will be
1919		 * set.
1920		 *
1921		 * Adjust the flags for the new active writer.
1922		 */
1923		add_arg = WRITER_ACTIVE;
1924		*rw = NGQRW_W;
1925		/*
1926		 * We want to write "active writer, no readers " Now go make
1927		 * it true. In fact there may be a number in the readers
1928		 * count but we know it is not true and will be fixed soon.
1929		 * We will fix the flags for the next pending entry in a
1930		 * moment.
1931		 */
1932	} else {
1933		/*
1934		 * We can't dequeue anything.. return and say so. Probably we
1935		 * have a write pending and the readers count is non zero. If
1936		 * we got here because a reader hit us just at the wrong
1937		 * moment with the fasttrack code, and put us in a strange
1938		 * state, then it will be coming through in just a moment,
1939		 * (just as soon as we release the mutex) and keep things
1940		 * moving.
1941		 * Make sure we remove ourselves from the work queue. It
1942		 * would be a waste of effort to do all this again.
1943		 */
1944		ng_worklist_remove(ngq->q_node);
1945		CTR4(KTR_NET, "%20s: node [%x] (%p) can't dequeue anything; "
1946		    "queue flags 0x%lx", __func__,
1947		    ngq->q_node->nd_ID, ngq->q_node, ngq->q_flags);
1948		return (NULL);
1949	}
1950
1951	/*
1952	 * Now we dequeue the request (whatever it may be) and correct the
1953	 * pending flags and the next and last pointers.
1954	 */
1955	item = ngq->queue;
1956	ngq->queue = item->el_next;
1957	CTR6(KTR_NET, "%20s: node [%x] (%p) dequeued item %p with flags 0x%lx; "
1958	    "queue flags 0x%lx", __func__,
1959	    ngq->q_node->nd_ID,ngq->q_node, item, item->el_flags, ngq->q_flags);
1960	if (ngq->last == &(item->el_next)) {
1961		/*
1962		 * that was the last entry in the queue so set the 'last
1963		 * pointer up correctly and make sure the pending flag is
1964		 * clear.
1965		 */
1966		add_arg += -OP_PENDING;
1967		ngq->last = &(ngq->queue);
1968		/*
1969		 * Whatever flag was set will be cleared and
1970		 * the new acive field will be set by the add as well,
1971		 * so we don't need to change add_arg.
1972		 * But we know we don't need to be on the work list.
1973		 */
1974		atomic_add_long(&ngq->q_flags, add_arg);
1975		ng_worklist_remove(ngq->q_node);
1976	} else {
1977		/*
1978		 * Since there is still something on the queue
1979		 * we don't need to change the PENDING flag.
1980		 */
1981		atomic_add_long(&ngq->q_flags, add_arg);
1982		/*
1983		 * If we see more doable work, make sure we are
1984		 * on the work queue.
1985		 */
1986		if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq)) {
1987			ng_setisr(ngq->q_node);
1988		}
1989	}
1990	CTR6(KTR_NET, "%20s: node [%x] (%p) returning item %p as %s; "
1991	    "queue flags 0x%lx", __func__,
1992	    ngq->q_node->nd_ID, ngq->q_node, item, *rw ? "WRITER" : "READER" ,
1993	    ngq->q_flags);
1994	return (item);
1995}
1996
1997/*
1998 * Queue a packet to be picked up by someone else.
1999 * We really don't care who, but we can't or don't want to hang around
2000 * to process it ourselves. We are probably an interrupt routine..
2001 * If the queue could be run, flag the netisr handler to start.
2002 */
2003static __inline void
2004ng_queue_rw(struct ng_queue * ngq, item_p  item, int rw)
2005{
2006	mtx_assert(&ngq->q_mtx, MA_OWNED);
2007
2008	if (rw == NGQRW_W)
2009		NGI_SET_WRITER(item);
2010	else
2011		NGI_SET_READER(item);
2012	item->el_next = NULL;	/* maybe not needed */
2013	*ngq->last = item;
2014	CTR5(KTR_NET, "%20s: node [%x] (%p) queued item %p as %s", __func__,
2015	    ngq->q_node->nd_ID, ngq->q_node, item, rw ? "WRITER" : "READER" );
2016	/*
2017	 * If it was the first item in the queue then we need to
2018	 * set the last pointer and the type flags.
2019	 */
2020	if (ngq->last == &(ngq->queue)) {
2021		atomic_add_long(&ngq->q_flags, OP_PENDING);
2022		CTR3(KTR_NET, "%20s: node [%x] (%p) set OP_PENDING", __func__,
2023		    ngq->q_node->nd_ID, ngq->q_node);
2024	}
2025
2026	ngq->last = &(item->el_next);
2027	/*
2028	 * We can take the worklist lock with the node locked
2029	 * BUT NOT THE REVERSE!
2030	 */
2031	if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2032		ng_setisr(ngq->q_node);
2033}
2034
2035
2036/*
2037 * This function 'cheats' in that it first tries to 'grab' the use of the
2038 * node, without going through the mutex. We can do this becasue of the
2039 * semantics of the lock. The semantics include a clause that says that the
2040 * value of the readers count is invalid if the WRITER_ACTIVE flag is set. It
2041 * also says that the WRITER_ACTIVE flag cannot be set if the readers count
2042 * is not zero. Note that this talks about what is valid to SET the
2043 * WRITER_ACTIVE flag, because from the moment it is set, the value if the
2044 * reader count is immaterial, and not valid. The two 'pending' flags have a
2045 * similar effect, in that If they are orthogonal to the two active fields in
2046 * how they are set, but if either is set, the attempted 'grab' need to be
2047 * backed out because there is earlier work, and we maintain ordering in the
2048 * queue. The result of this is that the reader request can try obtain use of
2049 * the node with only a single atomic addition, and without any of the mutex
2050 * overhead. If this fails the operation degenerates to the same as for other
2051 * cases.
2052 *
2053 */
2054static __inline item_p
2055ng_acquire_read(struct ng_queue *ngq, item_p item)
2056{
2057	KASSERT(ngq != &ng_deadnode.nd_input_queue,
2058	    ("%s: working on deadnode", __func__));
2059
2060	/* ######### Hack alert ######### */
2061	atomic_add_long(&ngq->q_flags, READER_INCREMENT);
2062	if ((ngq->q_flags & NGQ_RMASK) == 0) {
2063		/* Successfully grabbed node */
2064		CTR4(KTR_NET, "%20s: node [%x] (%p) fast acquired item %p",
2065		    __func__, ngq->q_node->nd_ID, ngq->q_node, item);
2066		return (item);
2067	}
2068	/* undo the damage if we didn't succeed */
2069	atomic_subtract_long(&ngq->q_flags, READER_INCREMENT);
2070
2071	/* ######### End Hack alert ######### */
2072	NG_QUEUE_LOCK(ngq);
2073	/*
2074	 * Try again. Another processor (or interrupt for that matter) may
2075	 * have removed the last queued item that was stopping us from
2076	 * running, between the previous test, and the moment that we took
2077	 * the mutex. (Or maybe a writer completed.)
2078	 * Even if another fast-track reader hits during this period
2079	 * we don't care as multiple readers is OK.
2080	 */
2081	if ((ngq->q_flags & NGQ_RMASK) == 0) {
2082		atomic_add_long(&ngq->q_flags, READER_INCREMENT);
2083		NG_QUEUE_UNLOCK(ngq);
2084		CTR4(KTR_NET, "%20s: node [%x] (%p) slow acquired item %p",
2085		    __func__, ngq->q_node->nd_ID, ngq->q_node, item);
2086		return (item);
2087	}
2088
2089	/*
2090	 * and queue the request for later.
2091	 */
2092	ng_queue_rw(ngq, item, NGQRW_R);
2093	NG_QUEUE_UNLOCK(ngq);
2094
2095	return (NULL);
2096}
2097
2098static __inline item_p
2099ng_acquire_write(struct ng_queue *ngq, item_p item)
2100{
2101	KASSERT(ngq != &ng_deadnode.nd_input_queue,
2102	    ("%s: working on deadnode", __func__));
2103
2104restart:
2105	NG_QUEUE_LOCK(ngq);
2106	/*
2107	 * If there are no readers, no writer, and no pending packets, then
2108	 * we can just go ahead. In all other situations we need to queue the
2109	 * request
2110	 */
2111	if ((ngq->q_flags & NGQ_WMASK) == 0) {
2112		/* collision could happen *HERE* */
2113		atomic_add_long(&ngq->q_flags, WRITER_ACTIVE);
2114		NG_QUEUE_UNLOCK(ngq);
2115		if (ngq->q_flags & READER_MASK) {
2116			/* Collision with fast-track reader */
2117			atomic_subtract_long(&ngq->q_flags, WRITER_ACTIVE);
2118			goto restart;
2119		}
2120		CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
2121		    __func__, ngq->q_node->nd_ID, ngq->q_node, item);
2122		return (item);
2123	}
2124
2125	/*
2126	 * and queue the request for later.
2127	 */
2128	ng_queue_rw(ngq, item, NGQRW_W);
2129	NG_QUEUE_UNLOCK(ngq);
2130
2131	return (NULL);
2132}
2133
2134#if 0
2135static __inline item_p
2136ng_upgrade_write(struct ng_queue *ngq, item_p item)
2137{
2138	KASSERT(ngq != &ng_deadnode.nd_input_queue,
2139	    ("%s: working on deadnode", __func__));
2140
2141	NGI_SET_WRITER(item);
2142
2143	mtx_lock_spin(&(ngq->q_mtx));
2144
2145	/*
2146	 * There will never be no readers as we are there ourselves.
2147	 * Set the WRITER_ACTIVE flags ASAP to block out fast track readers.
2148	 * The caller we are running from will call ng_leave_read()
2149	 * soon, so we must account for that. We must leave again with the
2150	 * READER lock. If we find other readers, then
2151	 * queue the request for later. However "later" may be rignt now
2152	 * if there are no readers. We don't really care if there are queued
2153	 * items as we will bypass them anyhow.
2154	 */
2155	atomic_add_long(&ngq->q_flags, WRITER_ACTIVE - READER_INCREMENT);
2156	if (ngq->q_flags & (NGQ_WMASK & ~OP_PENDING) == WRITER_ACTIVE) {
2157		mtx_unlock_spin(&(ngq->q_mtx));
2158
2159		/* It's just us, act on the item. */
2160		/* will NOT drop writer lock when done */
2161		ng_apply_item(node, item, 0);
2162
2163		/*
2164		 * Having acted on the item, atomically
2165		 * down grade back to READER and finish up
2166	 	 */
2167		atomic_add_long(&ngq->q_flags,
2168		    READER_INCREMENT - WRITER_ACTIVE);
2169
2170		/* Our caller will call ng_leave_read() */
2171		return;
2172	}
2173	/*
2174	 * It's not just us active, so queue us AT THE HEAD.
2175	 * "Why?" I hear you ask.
2176	 * Put us at the head of the queue as we've already been
2177	 * through it once. If there is nothing else waiting,
2178	 * set the correct flags.
2179	 */
2180	if ((item->el_next = ngq->queue) == NULL) {
2181		/*
2182		 * Set up the "last" pointer.
2183		 * We are the only (and thus last) item
2184		 */
2185		ngq->last = &(item->el_next);
2186
2187		/* We've gone from, 0 to 1 item in the queue */
2188		atomic_add_long(&ngq->q_flags, OP_PENDING);
2189
2190		CTR3(KTR_NET, "%20s: node [%x] (%p) set OP_PENDING", __func__,
2191		    ngq->q_node->nd_ID, ngq->q_node);
2192	};
2193	ngq->queue = item;
2194	CTR5(KTR_NET, "%20s: node [%x] (%p) requeued item %p as WRITER",
2195	    __func__, ngq->q_node->nd_ID, ngq->q_node, item );
2196
2197	/* Reverse what we did above. That downgrades us back to reader */
2198	atomic_add_long(&ngq->q_flags, READER_INCREMENT - WRITER_ACTIVE);
2199	if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2200		ng_setisr(ngq->q_node);
2201	mtx_unlock_spin(&(ngq->q_mtx));
2202
2203	return;
2204}
2205
2206#endif
2207
2208static __inline void
2209ng_leave_read(struct ng_queue *ngq)
2210{
2211	atomic_subtract_long(&ngq->q_flags, READER_INCREMENT);
2212}
2213
2214static __inline void
2215ng_leave_write(struct ng_queue *ngq)
2216{
2217	atomic_subtract_long(&ngq->q_flags, WRITER_ACTIVE);
2218}
2219
2220static void
2221ng_flush_input_queue(struct ng_queue * ngq)
2222{
2223	item_p item;
2224
2225	NG_QUEUE_LOCK(ngq);
2226	while (ngq->queue) {
2227		item = ngq->queue;
2228		ngq->queue = item->el_next;
2229		if (ngq->last == &(item->el_next)) {
2230			ngq->last = &(ngq->queue);
2231			atomic_add_long(&ngq->q_flags, -OP_PENDING);
2232		}
2233		NG_QUEUE_UNLOCK(ngq);
2234
2235		/* If the item is supplying a callback, call it with an error */
2236		if (item->apply != NULL &&
2237		    refcount_release(&item->apply->refs)) {
2238			(*item->apply->apply)(item->apply->context, ENOENT);
2239		}
2240		NG_FREE_ITEM(item);
2241		NG_QUEUE_LOCK(ngq);
2242	}
2243	/*
2244	 * Take us off the work queue if we are there.
2245	 * We definately have no work to be done.
2246	 */
2247	ng_worklist_remove(ngq->q_node);
2248	NG_QUEUE_UNLOCK(ngq);
2249}
2250
2251/***********************************************************************
2252* Externally visible method for sending or queueing messages or data.
2253***********************************************************************/
2254
2255/*
2256 * The module code should have filled out the item correctly by this stage:
2257 * Common:
2258 *    reference to destination node.
2259 *    Reference to destination rcv hook if relevant.
2260 *    apply pointer must be or NULL or reference valid struct ng_apply_info.
2261 * Data:
2262 *    pointer to mbuf
2263 * Control_Message:
2264 *    pointer to msg.
2265 *    ID of original sender node. (return address)
2266 * Function:
2267 *    Function pointer
2268 *    void * argument
2269 *    integer argument
2270 *
2271 * The nodes have several routines and macros to help with this task:
2272 */
2273
2274int
2275ng_snd_item(item_p item, int flags)
2276{
2277	hook_p hook;
2278	node_p node;
2279	int queue, rw;
2280	struct ng_queue *ngq;
2281	int error = 0;
2282
2283	if (item == NULL) {
2284		TRAP_ERROR();
2285		return (EINVAL);	/* failed to get queue element */
2286	}
2287
2288#ifdef	NETGRAPH_DEBUG
2289	_ngi_check(item, __FILE__, __LINE__);
2290#endif
2291
2292	if (item->apply)
2293		refcount_acquire(&item->apply->refs);
2294
2295	hook = NGI_HOOK(item);
2296	node = NGI_NODE(item);
2297	ngq = &node->nd_input_queue;
2298	if (node == NULL) {
2299		TRAP_ERROR();
2300		ERROUT(EINVAL);	/* No address */
2301	}
2302
2303	queue = (flags & NG_QUEUE) ? 1 : 0;
2304
2305	switch(item->el_flags & NGQF_TYPE) {
2306	case NGQF_DATA:
2307		/*
2308		 * DATA MESSAGE
2309		 * Delivered to a node via a non-optional hook.
2310		 * Both should be present in the item even though
2311		 * the node is derivable from the hook.
2312		 * References are held on both by the item.
2313		 */
2314
2315		/* Protect nodes from sending NULL pointers
2316		 * to each other
2317		 */
2318		if (NGI_M(item) == NULL)
2319			ERROUT(EINVAL);
2320
2321		CHECK_DATA_MBUF(NGI_M(item));
2322		if (hook == NULL) {
2323			TRAP_ERROR();
2324			ERROUT(EINVAL);
2325		}
2326		if ((NG_HOOK_NOT_VALID(hook))
2327		|| (NG_NODE_NOT_VALID(NG_HOOK_NODE(hook)))) {
2328			ERROUT(ENOTCONN);
2329		}
2330		if ((hook->hk_flags & HK_QUEUE)) {
2331			queue = 1;
2332		}
2333		break;
2334	case NGQF_MESG:
2335		/*
2336		 * CONTROL MESSAGE
2337		 * Delivered to a node.
2338		 * Hook is optional.
2339		 * References are held by the item on the node and
2340		 * the hook if it is present.
2341		 */
2342		if (hook && (hook->hk_flags & HK_QUEUE)) {
2343			queue = 1;
2344		}
2345		break;
2346	case NGQF_FN:
2347	case NGQF_FN2:
2348		break;
2349	default:
2350		TRAP_ERROR();
2351		ERROUT(EINVAL);
2352	}
2353	switch(item->el_flags & NGQF_RW) {
2354	case NGQF_READER:
2355		rw = NGQRW_R;
2356		break;
2357	case NGQF_WRITER:
2358		rw = NGQRW_W;
2359		break;
2360	default:
2361		panic("%s: invalid item flags %lx", __func__, item->el_flags);
2362	}
2363
2364	/*
2365	 * If the node specifies single threading, force writer semantics.
2366	 * Similarly, the node may say one hook always produces writers.
2367	 * These are overrides.
2368	 */
2369	if ((node->nd_flags & NGF_FORCE_WRITER)
2370	    || (hook && (hook->hk_flags & HK_FORCE_WRITER)))
2371			rw = NGQRW_W;
2372
2373	if (queue) {
2374		/* Put it on the queue for that node*/
2375#ifdef	NETGRAPH_DEBUG
2376		_ngi_check(item, __FILE__, __LINE__);
2377#endif
2378		NG_QUEUE_LOCK(ngq);
2379		ng_queue_rw(ngq, item, rw);
2380		NG_QUEUE_UNLOCK(ngq);
2381
2382		if (flags & NG_PROGRESS)
2383			return (EINPROGRESS);
2384		else
2385			return (0);
2386	}
2387
2388	/*
2389	 * We already decided how we will be queueud or treated.
2390	 * Try get the appropriate operating permission.
2391	 */
2392 	if (rw == NGQRW_R)
2393		item = ng_acquire_read(ngq, item);
2394	else
2395		item = ng_acquire_write(ngq, item);
2396
2397
2398	if (item == NULL) {
2399		if (flags & NG_PROGRESS)
2400			return (EINPROGRESS);
2401		else
2402			return (0);
2403	}
2404
2405#ifdef	NETGRAPH_DEBUG
2406	_ngi_check(item, __FILE__, __LINE__);
2407#endif
2408
2409	NGI_GET_NODE(item, node); /* zaps stored node */
2410
2411	error = ng_apply_item(node, item, rw); /* drops r/w lock when done */
2412
2413	/*
2414	 * If the node goes away when we remove the reference,
2415	 * whatever we just did caused it.. whatever we do, DO NOT
2416	 * access the node again!
2417	 */
2418	if (NG_NODE_UNREF(node) == 0) {
2419		return (error);
2420	}
2421
2422	NG_QUEUE_LOCK(ngq);
2423	if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2424		ng_setisr(ngq->q_node);
2425	NG_QUEUE_UNLOCK(ngq);
2426
2427	return (error);
2428
2429done:
2430	/* Apply callback. */
2431	if (item->apply != NULL &&
2432	    refcount_release(&item->apply->refs)) {
2433		(*item->apply->apply)(item->apply->context, error);
2434	}
2435	NG_FREE_ITEM(item);
2436	return (error);
2437}
2438
2439/*
2440 * We have an item that was possibly queued somewhere.
2441 * It should contain all the information needed
2442 * to run it on the appropriate node/hook.
2443 * If there is apply pointer and we own the last reference, call apply().
2444 */
2445static int
2446ng_apply_item(node_p node, item_p item, int rw)
2447{
2448	hook_p  hook;
2449	int	error = 0;
2450	ng_rcvdata_t *rcvdata;
2451	ng_rcvmsg_t *rcvmsg;
2452	struct ng_apply_info *apply;
2453
2454	NGI_GET_HOOK(item, hook); /* clears stored hook */
2455#ifdef	NETGRAPH_DEBUG
2456	_ngi_check(item, __FILE__, __LINE__);
2457#endif
2458
2459	apply = item->apply;
2460
2461	switch (item->el_flags & NGQF_TYPE) {
2462	case NGQF_DATA:
2463		/*
2464		 * Check things are still ok as when we were queued.
2465		 */
2466		if ((hook == NULL)
2467		|| NG_HOOK_NOT_VALID(hook)
2468		|| NG_NODE_NOT_VALID(node) ) {
2469			error = EIO;
2470			NG_FREE_ITEM(item);
2471			break;
2472		}
2473		/*
2474		 * If no receive method, just silently drop it.
2475		 * Give preference to the hook over-ride method
2476		 */
2477		if ((!(rcvdata = hook->hk_rcvdata))
2478		&& (!(rcvdata = NG_HOOK_NODE(hook)->nd_type->rcvdata))) {
2479			error = 0;
2480			NG_FREE_ITEM(item);
2481			break;
2482		}
2483		error = (*rcvdata)(hook, item);
2484		break;
2485	case NGQF_MESG:
2486		if (hook) {
2487			if (NG_HOOK_NOT_VALID(hook)) {
2488				/*
2489				 * The hook has been zapped then we can't
2490				 * use it. Immediately drop its reference.
2491				 * The message may not need it.
2492				 */
2493				NG_HOOK_UNREF(hook);
2494				hook = NULL;
2495			}
2496		}
2497		/*
2498		 * Similarly, if the node is a zombie there is
2499		 * nothing we can do with it, drop everything.
2500		 */
2501		if (NG_NODE_NOT_VALID(node)) {
2502			TRAP_ERROR();
2503			error = EINVAL;
2504			NG_FREE_ITEM(item);
2505		} else {
2506			/*
2507			 * Call the appropriate message handler for the object.
2508			 * It is up to the message handler to free the message.
2509			 * If it's a generic message, handle it generically,
2510			 * otherwise call the type's message handler
2511			 * (if it exists)
2512			 * XXX (race). Remember that a queued message may
2513			 * reference a node or hook that has just been
2514			 * invalidated. It will exist as the queue code
2515			 * is holding a reference, but..
2516			 */
2517
2518			struct ng_mesg *msg = NGI_MSG(item);
2519
2520			/*
2521			 * check if the generic handler owns it.
2522			 */
2523			if ((msg->header.typecookie == NGM_GENERIC_COOKIE)
2524			&& ((msg->header.flags & NGF_RESP) == 0)) {
2525				error = ng_generic_msg(node, item, hook);
2526				break;
2527			}
2528			/*
2529			 * Now see if there is a handler (hook or node specific)
2530			 * in the target node. If none, silently discard.
2531			 */
2532			if (((!hook) || (!(rcvmsg = hook->hk_rcvmsg)))
2533			&& (!(rcvmsg = node->nd_type->rcvmsg))) {
2534				TRAP_ERROR();
2535				error = 0;
2536				NG_FREE_ITEM(item);
2537				break;
2538			}
2539			error = (*rcvmsg)(node, item, hook);
2540		}
2541		break;
2542	case NGQF_FN:
2543		/*
2544		 *  We have to implicitly trust the hook,
2545		 * as some of these are used for system purposes
2546		 * where the hook is invalid. In the case of
2547		 * the shutdown message we allow it to hit
2548		 * even if the node is invalid.
2549		 */
2550		if ((NG_NODE_NOT_VALID(node))
2551		&& (NGI_FN(item) != &ng_rmnode)) {
2552			TRAP_ERROR();
2553			error = EINVAL;
2554			NG_FREE_ITEM(item);
2555			break;
2556		}
2557		(*NGI_FN(item))(node, hook, NGI_ARG1(item), NGI_ARG2(item));
2558		NG_FREE_ITEM(item);
2559		break;
2560	case NGQF_FN2:
2561		/*
2562		 *  We have to implicitly trust the hook,
2563		 * as some of these are used for system purposes
2564		 * where the hook is invalid. In the case of
2565		 * the shutdown message we allow it to hit
2566		 * even if the node is invalid.
2567		 */
2568		if ((NG_NODE_NOT_VALID(node))
2569		&& (NGI_FN(item) != &ng_rmnode)) {
2570			TRAP_ERROR();
2571			error = EINVAL;
2572			NG_FREE_ITEM(item);
2573			break;
2574		}
2575		error = (*NGI_FN2(item))(node, item, hook);
2576		break;
2577	}
2578	/*
2579	 * We held references on some of the resources
2580	 * that we took from the item. Now that we have
2581	 * finished doing everything, drop those references.
2582	 */
2583	if (hook) {
2584		NG_HOOK_UNREF(hook);
2585	}
2586
2587 	if (rw == NGQRW_R) {
2588		ng_leave_read(&node->nd_input_queue);
2589	} else {
2590		ng_leave_write(&node->nd_input_queue);
2591	}
2592
2593	/* Apply callback. */
2594	if (apply != NULL &&
2595	    refcount_release(&apply->refs)) {
2596		(*apply->apply)(apply->context, error);
2597	}
2598
2599	return (error);
2600}
2601
2602/***********************************************************************
2603 * Implement the 'generic' control messages
2604 ***********************************************************************/
2605static int
2606ng_generic_msg(node_p here, item_p item, hook_p lasthook)
2607{
2608	int error = 0;
2609	struct ng_mesg *msg;
2610	struct ng_mesg *resp = NULL;
2611
2612	NGI_GET_MSG(item, msg);
2613	if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
2614		TRAP_ERROR();
2615		error = EINVAL;
2616		goto out;
2617	}
2618	switch (msg->header.cmd) {
2619	case NGM_SHUTDOWN:
2620		ng_rmnode(here, NULL, NULL, 0);
2621		break;
2622	case NGM_MKPEER:
2623	    {
2624		struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
2625
2626		if (msg->header.arglen != sizeof(*mkp)) {
2627			TRAP_ERROR();
2628			error = EINVAL;
2629			break;
2630		}
2631		mkp->type[sizeof(mkp->type) - 1] = '\0';
2632		mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
2633		mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
2634		error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
2635		break;
2636	    }
2637	case NGM_CONNECT:
2638	    {
2639		struct ngm_connect *const con =
2640			(struct ngm_connect *) msg->data;
2641		node_p node2;
2642
2643		if (msg->header.arglen != sizeof(*con)) {
2644			TRAP_ERROR();
2645			error = EINVAL;
2646			break;
2647		}
2648		con->path[sizeof(con->path) - 1] = '\0';
2649		con->ourhook[sizeof(con->ourhook) - 1] = '\0';
2650		con->peerhook[sizeof(con->peerhook) - 1] = '\0';
2651		/* Don't forget we get a reference.. */
2652		error = ng_path2noderef(here, con->path, &node2, NULL);
2653		if (error)
2654			break;
2655		error = ng_con_nodes(item, here, con->ourhook,
2656		    node2, con->peerhook);
2657		NG_NODE_UNREF(node2);
2658		break;
2659	    }
2660	case NGM_NAME:
2661	    {
2662		struct ngm_name *const nam = (struct ngm_name *) msg->data;
2663
2664		if (msg->header.arglen != sizeof(*nam)) {
2665			TRAP_ERROR();
2666			error = EINVAL;
2667			break;
2668		}
2669		nam->name[sizeof(nam->name) - 1] = '\0';
2670		error = ng_name_node(here, nam->name);
2671		break;
2672	    }
2673	case NGM_RMHOOK:
2674	    {
2675		struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
2676		hook_p hook;
2677
2678		if (msg->header.arglen != sizeof(*rmh)) {
2679			TRAP_ERROR();
2680			error = EINVAL;
2681			break;
2682		}
2683		rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
2684		if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
2685			ng_destroy_hook(hook);
2686		break;
2687	    }
2688	case NGM_NODEINFO:
2689	    {
2690		struct nodeinfo *ni;
2691
2692		NG_MKRESPONSE(resp, msg, sizeof(*ni), M_NOWAIT);
2693		if (resp == NULL) {
2694			error = ENOMEM;
2695			break;
2696		}
2697
2698		/* Fill in node info */
2699		ni = (struct nodeinfo *) resp->data;
2700		if (NG_NODE_HAS_NAME(here))
2701			strcpy(ni->name, NG_NODE_NAME(here));
2702		strcpy(ni->type, here->nd_type->name);
2703		ni->id = ng_node2ID(here);
2704		ni->hooks = here->nd_numhooks;
2705		break;
2706	    }
2707	case NGM_LISTHOOKS:
2708	    {
2709		const int nhooks = here->nd_numhooks;
2710		struct hooklist *hl;
2711		struct nodeinfo *ni;
2712		hook_p hook;
2713
2714		/* Get response struct */
2715		NG_MKRESPONSE(resp, msg, sizeof(*hl)
2716		    + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
2717		if (resp == NULL) {
2718			error = ENOMEM;
2719			break;
2720		}
2721		hl = (struct hooklist *) resp->data;
2722		ni = &hl->nodeinfo;
2723
2724		/* Fill in node info */
2725		if (NG_NODE_HAS_NAME(here))
2726			strcpy(ni->name, NG_NODE_NAME(here));
2727		strcpy(ni->type, here->nd_type->name);
2728		ni->id = ng_node2ID(here);
2729
2730		/* Cycle through the linked list of hooks */
2731		ni->hooks = 0;
2732		LIST_FOREACH(hook, &here->nd_hooks, hk_hooks) {
2733			struct linkinfo *const link = &hl->link[ni->hooks];
2734
2735			if (ni->hooks >= nhooks) {
2736				log(LOG_ERR, "%s: number of %s changed\n",
2737				    __func__, "hooks");
2738				break;
2739			}
2740			if (NG_HOOK_NOT_VALID(hook))
2741				continue;
2742			strcpy(link->ourhook, NG_HOOK_NAME(hook));
2743			strcpy(link->peerhook, NG_PEER_HOOK_NAME(hook));
2744			if (NG_PEER_NODE_NAME(hook)[0] != '\0')
2745				strcpy(link->nodeinfo.name,
2746				    NG_PEER_NODE_NAME(hook));
2747			strcpy(link->nodeinfo.type,
2748			   NG_PEER_NODE(hook)->nd_type->name);
2749			link->nodeinfo.id = ng_node2ID(NG_PEER_NODE(hook));
2750			link->nodeinfo.hooks = NG_PEER_NODE(hook)->nd_numhooks;
2751			ni->hooks++;
2752		}
2753		break;
2754	    }
2755
2756	case NGM_LISTNAMES:
2757	case NGM_LISTNODES:
2758	    {
2759		const int unnamed = (msg->header.cmd == NGM_LISTNODES);
2760		struct namelist *nl;
2761		node_p node;
2762		int num = 0;
2763
2764		mtx_lock(&ng_nodelist_mtx);
2765		/* Count number of nodes */
2766		LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
2767			if (NG_NODE_IS_VALID(node)
2768			&& (unnamed || NG_NODE_HAS_NAME(node))) {
2769				num++;
2770			}
2771		}
2772		mtx_unlock(&ng_nodelist_mtx);
2773
2774		/* Get response struct */
2775		NG_MKRESPONSE(resp, msg, sizeof(*nl)
2776		    + (num * sizeof(struct nodeinfo)), M_NOWAIT);
2777		if (resp == NULL) {
2778			error = ENOMEM;
2779			break;
2780		}
2781		nl = (struct namelist *) resp->data;
2782
2783		/* Cycle through the linked list of nodes */
2784		nl->numnames = 0;
2785		mtx_lock(&ng_nodelist_mtx);
2786		LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
2787			struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
2788
2789			if (NG_NODE_NOT_VALID(node))
2790				continue;
2791			if (!unnamed && (! NG_NODE_HAS_NAME(node)))
2792				continue;
2793			if (nl->numnames >= num) {
2794				log(LOG_ERR, "%s: number of %s changed\n",
2795				    __func__, "nodes");
2796				break;
2797			}
2798			if (NG_NODE_HAS_NAME(node))
2799				strcpy(np->name, NG_NODE_NAME(node));
2800			strcpy(np->type, node->nd_type->name);
2801			np->id = ng_node2ID(node);
2802			np->hooks = node->nd_numhooks;
2803			nl->numnames++;
2804		}
2805		mtx_unlock(&ng_nodelist_mtx);
2806		break;
2807	    }
2808
2809	case NGM_LISTTYPES:
2810	    {
2811		struct typelist *tl;
2812		struct ng_type *type;
2813		int num = 0;
2814
2815		mtx_lock(&ng_typelist_mtx);
2816		/* Count number of types */
2817		LIST_FOREACH(type, &ng_typelist, types) {
2818			num++;
2819		}
2820		mtx_unlock(&ng_typelist_mtx);
2821
2822		/* Get response struct */
2823		NG_MKRESPONSE(resp, msg, sizeof(*tl)
2824		    + (num * sizeof(struct typeinfo)), M_NOWAIT);
2825		if (resp == NULL) {
2826			error = ENOMEM;
2827			break;
2828		}
2829		tl = (struct typelist *) resp->data;
2830
2831		/* Cycle through the linked list of types */
2832		tl->numtypes = 0;
2833		mtx_lock(&ng_typelist_mtx);
2834		LIST_FOREACH(type, &ng_typelist, types) {
2835			struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
2836
2837			if (tl->numtypes >= num) {
2838				log(LOG_ERR, "%s: number of %s changed\n",
2839				    __func__, "types");
2840				break;
2841			}
2842			strcpy(tp->type_name, type->name);
2843			tp->numnodes = type->refs - 1; /* don't count list */
2844			tl->numtypes++;
2845		}
2846		mtx_unlock(&ng_typelist_mtx);
2847		break;
2848	    }
2849
2850	case NGM_BINARY2ASCII:
2851	    {
2852		int bufSize = 20 * 1024;	/* XXX hard coded constant */
2853		const struct ng_parse_type *argstype;
2854		const struct ng_cmdlist *c;
2855		struct ng_mesg *binary, *ascii;
2856
2857		/* Data area must contain a valid netgraph message */
2858		binary = (struct ng_mesg *)msg->data;
2859		if (msg->header.arglen < sizeof(struct ng_mesg) ||
2860		    (msg->header.arglen - sizeof(struct ng_mesg) <
2861		    binary->header.arglen)) {
2862			TRAP_ERROR();
2863			error = EINVAL;
2864			break;
2865		}
2866
2867		/* Get a response message with lots of room */
2868		NG_MKRESPONSE(resp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
2869		if (resp == NULL) {
2870			error = ENOMEM;
2871			break;
2872		}
2873		ascii = (struct ng_mesg *)resp->data;
2874
2875		/* Copy binary message header to response message payload */
2876		bcopy(binary, ascii, sizeof(*binary));
2877
2878		/* Find command by matching typecookie and command number */
2879		for (c = here->nd_type->cmdlist;
2880		    c != NULL && c->name != NULL; c++) {
2881			if (binary->header.typecookie == c->cookie
2882			    && binary->header.cmd == c->cmd)
2883				break;
2884		}
2885		if (c == NULL || c->name == NULL) {
2886			for (c = ng_generic_cmds; c->name != NULL; c++) {
2887				if (binary->header.typecookie == c->cookie
2888				    && binary->header.cmd == c->cmd)
2889					break;
2890			}
2891			if (c->name == NULL) {
2892				NG_FREE_MSG(resp);
2893				error = ENOSYS;
2894				break;
2895			}
2896		}
2897
2898		/* Convert command name to ASCII */
2899		snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
2900		    "%s", c->name);
2901
2902		/* Convert command arguments to ASCII */
2903		argstype = (binary->header.flags & NGF_RESP) ?
2904		    c->respType : c->mesgType;
2905		if (argstype == NULL) {
2906			*ascii->data = '\0';
2907		} else {
2908			if ((error = ng_unparse(argstype,
2909			    (u_char *)binary->data,
2910			    ascii->data, bufSize)) != 0) {
2911				NG_FREE_MSG(resp);
2912				break;
2913			}
2914		}
2915
2916		/* Return the result as struct ng_mesg plus ASCII string */
2917		bufSize = strlen(ascii->data) + 1;
2918		ascii->header.arglen = bufSize;
2919		resp->header.arglen = sizeof(*ascii) + bufSize;
2920		break;
2921	    }
2922
2923	case NGM_ASCII2BINARY:
2924	    {
2925		int bufSize = 2000;	/* XXX hard coded constant */
2926		const struct ng_cmdlist *c;
2927		const struct ng_parse_type *argstype;
2928		struct ng_mesg *ascii, *binary;
2929		int off = 0;
2930
2931		/* Data area must contain at least a struct ng_mesg + '\0' */
2932		ascii = (struct ng_mesg *)msg->data;
2933		if ((msg->header.arglen < sizeof(*ascii) + 1) ||
2934		    (ascii->header.arglen < 1) ||
2935		    (msg->header.arglen < sizeof(*ascii) +
2936		    ascii->header.arglen)) {
2937			TRAP_ERROR();
2938			error = EINVAL;
2939			break;
2940		}
2941		ascii->data[ascii->header.arglen - 1] = '\0';
2942
2943		/* Get a response message with lots of room */
2944		NG_MKRESPONSE(resp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
2945		if (resp == NULL) {
2946			error = ENOMEM;
2947			break;
2948		}
2949		binary = (struct ng_mesg *)resp->data;
2950
2951		/* Copy ASCII message header to response message payload */
2952		bcopy(ascii, binary, sizeof(*ascii));
2953
2954		/* Find command by matching ASCII command string */
2955		for (c = here->nd_type->cmdlist;
2956		    c != NULL && c->name != NULL; c++) {
2957			if (strcmp(ascii->header.cmdstr, c->name) == 0)
2958				break;
2959		}
2960		if (c == NULL || c->name == NULL) {
2961			for (c = ng_generic_cmds; c->name != NULL; c++) {
2962				if (strcmp(ascii->header.cmdstr, c->name) == 0)
2963					break;
2964			}
2965			if (c->name == NULL) {
2966				NG_FREE_MSG(resp);
2967				error = ENOSYS;
2968				break;
2969			}
2970		}
2971
2972		/* Convert command name to binary */
2973		binary->header.cmd = c->cmd;
2974		binary->header.typecookie = c->cookie;
2975
2976		/* Convert command arguments to binary */
2977		argstype = (binary->header.flags & NGF_RESP) ?
2978		    c->respType : c->mesgType;
2979		if (argstype == NULL) {
2980			bufSize = 0;
2981		} else {
2982			if ((error = ng_parse(argstype, ascii->data,
2983			    &off, (u_char *)binary->data, &bufSize)) != 0) {
2984				NG_FREE_MSG(resp);
2985				break;
2986			}
2987		}
2988
2989		/* Return the result */
2990		binary->header.arglen = bufSize;
2991		resp->header.arglen = sizeof(*binary) + bufSize;
2992		break;
2993	    }
2994
2995	case NGM_TEXT_CONFIG:
2996	case NGM_TEXT_STATUS:
2997		/*
2998		 * This one is tricky as it passes the command down to the
2999		 * actual node, even though it is a generic type command.
3000		 * This means we must assume that the item/msg is already freed
3001		 * when control passes back to us.
3002		 */
3003		if (here->nd_type->rcvmsg != NULL) {
3004			NGI_MSG(item) = msg; /* put it back as we found it */
3005			return((*here->nd_type->rcvmsg)(here, item, lasthook));
3006		}
3007		/* Fall through if rcvmsg not supported */
3008	default:
3009		TRAP_ERROR();
3010		error = EINVAL;
3011	}
3012	/*
3013	 * Sometimes a generic message may be statically allocated
3014	 * to avoid problems with allocating when in tight memeory situations.
3015	 * Don't free it if it is so.
3016	 * I break them appart here, because erros may cause a free if the item
3017	 * in which case we'd be doing it twice.
3018	 * they are kept together above, to simplify freeing.
3019	 */
3020out:
3021	NG_RESPOND_MSG(error, here, item, resp);
3022	if (msg)
3023		NG_FREE_MSG(msg);
3024	return (error);
3025}
3026
3027/************************************************************************
3028			Queue element get/free routines
3029************************************************************************/
3030
3031uma_zone_t			ng_qzone;
3032static int			maxalloc = 512;	/* limit the damage of a leak */
3033
3034TUNABLE_INT("net.graph.maxalloc", &maxalloc);
3035SYSCTL_INT(_net_graph, OID_AUTO, maxalloc, CTLFLAG_RDTUN, &maxalloc,
3036    0, "Maximum number of queue items to allocate");
3037
3038#ifdef	NETGRAPH_DEBUG
3039static TAILQ_HEAD(, ng_item) ng_itemlist = TAILQ_HEAD_INITIALIZER(ng_itemlist);
3040static int			allocated;	/* number of items malloc'd */
3041#endif
3042
3043/*
3044 * Get a queue entry.
3045 * This is usually called when a packet first enters netgraph.
3046 * By definition, this is usually from an interrupt, or from a user.
3047 * Users are not so important, but try be quick for the times that it's
3048 * an interrupt.
3049 */
3050static __inline item_p
3051ng_getqblk(int flags)
3052{
3053	item_p item = NULL;
3054	int wait;
3055
3056	wait = (flags & NG_WAITOK) ? M_WAITOK : M_NOWAIT;
3057
3058	item = uma_zalloc(ng_qzone, wait | M_ZERO);
3059
3060#ifdef	NETGRAPH_DEBUG
3061	if (item) {
3062			mtx_lock(&ngq_mtx);
3063			TAILQ_INSERT_TAIL(&ng_itemlist, item, all);
3064			allocated++;
3065			mtx_unlock(&ngq_mtx);
3066	}
3067#endif
3068
3069	return (item);
3070}
3071
3072/*
3073 * Release a queue entry
3074 */
3075void
3076ng_free_item(item_p item)
3077{
3078	/*
3079	 * The item may hold resources on it's own. We need to free
3080	 * these before we can free the item. What they are depends upon
3081	 * what kind of item it is. it is important that nodes zero
3082	 * out pointers to resources that they remove from the item
3083	 * or we release them again here.
3084	 */
3085	switch (item->el_flags & NGQF_TYPE) {
3086	case NGQF_DATA:
3087		/* If we have an mbuf still attached.. */
3088		NG_FREE_M(_NGI_M(item));
3089		break;
3090	case NGQF_MESG:
3091		_NGI_RETADDR(item) = 0;
3092		NG_FREE_MSG(_NGI_MSG(item));
3093		break;
3094	case NGQF_FN:
3095	case NGQF_FN2:
3096		/* nothing to free really, */
3097		_NGI_FN(item) = NULL;
3098		_NGI_ARG1(item) = NULL;
3099		_NGI_ARG2(item) = 0;
3100		break;
3101	}
3102	/* If we still have a node or hook referenced... */
3103	_NGI_CLR_NODE(item);
3104	_NGI_CLR_HOOK(item);
3105
3106#ifdef	NETGRAPH_DEBUG
3107	mtx_lock(&ngq_mtx);
3108	TAILQ_REMOVE(&ng_itemlist, item, all);
3109	allocated--;
3110	mtx_unlock(&ngq_mtx);
3111#endif
3112	uma_zfree(ng_qzone, item);
3113}
3114
3115/************************************************************************
3116			Module routines
3117************************************************************************/
3118
3119/*
3120 * Handle the loading/unloading of a netgraph node type module
3121 */
3122int
3123ng_mod_event(module_t mod, int event, void *data)
3124{
3125	struct ng_type *const type = data;
3126	int s, error = 0;
3127
3128	switch (event) {
3129	case MOD_LOAD:
3130
3131		/* Register new netgraph node type */
3132		s = splnet();
3133		if ((error = ng_newtype(type)) != 0) {
3134			splx(s);
3135			break;
3136		}
3137
3138		/* Call type specific code */
3139		if (type->mod_event != NULL)
3140			if ((error = (*type->mod_event)(mod, event, data))) {
3141				mtx_lock(&ng_typelist_mtx);
3142				type->refs--;	/* undo it */
3143				LIST_REMOVE(type, types);
3144				mtx_unlock(&ng_typelist_mtx);
3145			}
3146		splx(s);
3147		break;
3148
3149	case MOD_UNLOAD:
3150		s = splnet();
3151		if (type->refs > 1) {		/* make sure no nodes exist! */
3152			error = EBUSY;
3153		} else {
3154			if (type->refs == 0) {
3155				/* failed load, nothing to undo */
3156				splx(s);
3157				break;
3158			}
3159			if (type->mod_event != NULL) {	/* check with type */
3160				error = (*type->mod_event)(mod, event, data);
3161				if (error != 0) {	/* type refuses.. */
3162					splx(s);
3163					break;
3164				}
3165			}
3166			mtx_lock(&ng_typelist_mtx);
3167			LIST_REMOVE(type, types);
3168			mtx_unlock(&ng_typelist_mtx);
3169		}
3170		splx(s);
3171		break;
3172
3173	default:
3174		if (type->mod_event != NULL)
3175			error = (*type->mod_event)(mod, event, data);
3176		else
3177			error = EOPNOTSUPP;		/* XXX ? */
3178		break;
3179	}
3180	return (error);
3181}
3182
3183/*
3184 * Handle loading and unloading for this code.
3185 * The only thing we need to link into is the NETISR strucure.
3186 */
3187static int
3188ngb_mod_event(module_t mod, int event, void *data)
3189{
3190	int error = 0;
3191
3192	switch (event) {
3193	case MOD_LOAD:
3194		/* Initialize everything. */
3195		NG_WORKLIST_LOCK_INIT();
3196		mtx_init(&ng_typelist_mtx, "netgraph types mutex", NULL,
3197		    MTX_DEF);
3198		mtx_init(&ng_nodelist_mtx, "netgraph nodelist mutex", NULL,
3199		    MTX_DEF);
3200		mtx_init(&ng_idhash_mtx, "netgraph idhash mutex", NULL,
3201		    MTX_DEF);
3202		mtx_init(&ng_topo_mtx, "netgraph topology mutex", NULL,
3203		    MTX_DEF);
3204#ifdef	NETGRAPH_DEBUG
3205		mtx_init(&ngq_mtx, "netgraph item list mutex", NULL,
3206		    MTX_DEF);
3207#endif
3208		ng_qzone = uma_zcreate("NetGraph items", sizeof(struct ng_item),
3209		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
3210		uma_zone_set_max(ng_qzone, maxalloc);
3211		netisr_register(NETISR_NETGRAPH, (netisr_t *)ngintr, NULL,
3212		    NETISR_MPSAFE);
3213		break;
3214	case MOD_UNLOAD:
3215		/* You can't unload it because an interface may be using it. */
3216		error = EBUSY;
3217		break;
3218	default:
3219		error = EOPNOTSUPP;
3220		break;
3221	}
3222	return (error);
3223}
3224
3225static moduledata_t netgraph_mod = {
3226	"netgraph",
3227	ngb_mod_event,
3228	(NULL)
3229};
3230DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_NETGRAPH, SI_ORDER_MIDDLE);
3231SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
3232SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
3233SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
3234
3235#ifdef	NETGRAPH_DEBUG
3236void
3237dumphook (hook_p hook, char *file, int line)
3238{
3239	printf("hook: name %s, %d refs, Last touched:\n",
3240		_NG_HOOK_NAME(hook), hook->hk_refs);
3241	printf("	Last active @ %s, line %d\n",
3242		hook->lastfile, hook->lastline);
3243	if (line) {
3244		printf(" problem discovered at file %s, line %d\n", file, line);
3245	}
3246}
3247
3248void
3249dumpnode(node_p node, char *file, int line)
3250{
3251	printf("node: ID [%x]: type '%s', %d hooks, flags 0x%x, %d refs, %s:\n",
3252		_NG_NODE_ID(node), node->nd_type->name,
3253		node->nd_numhooks, node->nd_flags,
3254		node->nd_refs, node->nd_name);
3255	printf("	Last active @ %s, line %d\n",
3256		node->lastfile, node->lastline);
3257	if (line) {
3258		printf(" problem discovered at file %s, line %d\n", file, line);
3259	}
3260}
3261
3262void
3263dumpitem(item_p item, char *file, int line)
3264{
3265	printf(" ACTIVE item, last used at %s, line %d",
3266		item->lastfile, item->lastline);
3267	switch(item->el_flags & NGQF_TYPE) {
3268	case NGQF_DATA:
3269		printf(" - [data]\n");
3270		break;
3271	case NGQF_MESG:
3272		printf(" - retaddr[%d]:\n", _NGI_RETADDR(item));
3273		break;
3274	case NGQF_FN:
3275	case NGQF_FN2:
3276		printf(" - fn@%p (%p, %p, %p, %d (%x))\n",
3277			item->body.fn.fn_fn,
3278			_NGI_NODE(item),
3279			_NGI_HOOK(item),
3280			item->body.fn.fn_arg1,
3281			item->body.fn.fn_arg2,
3282			item->body.fn.fn_arg2);
3283		break;
3284	}
3285	if (line) {
3286		printf(" problem discovered at file %s, line %d\n", file, line);
3287		if (_NGI_NODE(item)) {
3288			printf("node %p ([%x])\n",
3289				_NGI_NODE(item), ng_node2ID(_NGI_NODE(item)));
3290		}
3291	}
3292}
3293
3294static void
3295ng_dumpitems(void)
3296{
3297	item_p item;
3298	int i = 1;
3299	TAILQ_FOREACH(item, &ng_itemlist, all) {
3300		printf("[%d] ", i++);
3301		dumpitem(item, NULL, 0);
3302	}
3303}
3304
3305static void
3306ng_dumpnodes(void)
3307{
3308	node_p node;
3309	int i = 1;
3310	mtx_lock(&ng_nodelist_mtx);
3311	SLIST_FOREACH(node, &ng_allnodes, nd_all) {
3312		printf("[%d] ", i++);
3313		dumpnode(node, NULL, 0);
3314	}
3315	mtx_unlock(&ng_nodelist_mtx);
3316}
3317
3318static void
3319ng_dumphooks(void)
3320{
3321	hook_p hook;
3322	int i = 1;
3323	mtx_lock(&ng_nodelist_mtx);
3324	SLIST_FOREACH(hook, &ng_allhooks, hk_all) {
3325		printf("[%d] ", i++);
3326		dumphook(hook, NULL, 0);
3327	}
3328	mtx_unlock(&ng_nodelist_mtx);
3329}
3330
3331static int
3332sysctl_debug_ng_dump_items(SYSCTL_HANDLER_ARGS)
3333{
3334	int error;
3335	int val;
3336	int i;
3337
3338	val = allocated;
3339	i = 1;
3340	error = sysctl_handle_int(oidp, &val, 0, req);
3341	if (error != 0 || req->newptr == NULL)
3342		return (error);
3343	if (val == 42) {
3344		ng_dumpitems();
3345		ng_dumpnodes();
3346		ng_dumphooks();
3347	}
3348	return (0);
3349}
3350
3351SYSCTL_PROC(_debug, OID_AUTO, ng_dump_items, CTLTYPE_INT | CTLFLAG_RW,
3352    0, sizeof(int), sysctl_debug_ng_dump_items, "I", "Number of allocated items");
3353#endif	/* NETGRAPH_DEBUG */
3354
3355
3356/***********************************************************************
3357* Worklist routines
3358**********************************************************************/
3359/* NETISR thread enters here */
3360/*
3361 * Pick a node off the list of nodes with work,
3362 * try get an item to process off it.
3363 * If there are no more, remove the node from the list.
3364 */
3365static void
3366ngintr(void)
3367{
3368	item_p item;
3369	node_p  node = NULL;
3370
3371	for (;;) {
3372		NG_WORKLIST_LOCK();
3373		node = TAILQ_FIRST(&ng_worklist);
3374		if (!node) {
3375			NG_WORKLIST_UNLOCK();
3376			break;
3377		}
3378		node->nd_flags &= ~NGF_WORKQ;
3379		TAILQ_REMOVE(&ng_worklist, node, nd_work);
3380		NG_WORKLIST_UNLOCK();
3381		CTR3(KTR_NET, "%20s: node [%x] (%p) taken off worklist",
3382		    __func__, node->nd_ID, node);
3383		/*
3384		 * We have the node. We also take over the reference
3385		 * that the list had on it.
3386		 * Now process as much as you can, until it won't
3387		 * let you have another item off the queue.
3388		 * All this time, keep the reference
3389		 * that lets us be sure that the node still exists.
3390		 * Let the reference go at the last minute.
3391		 * ng_dequeue will put us back on the worklist
3392		 * if there is more too do. This may be of use if there
3393		 * are Multiple Processors and multiple Net threads in the
3394		 * future.
3395		 */
3396		for (;;) {
3397			int rw;
3398
3399			NG_QUEUE_LOCK(&node->nd_input_queue);
3400			item = ng_dequeue(&node->nd_input_queue, &rw);
3401			if (item == NULL) {
3402				NG_QUEUE_UNLOCK(&node->nd_input_queue);
3403				break; /* go look for another node */
3404			} else {
3405				NG_QUEUE_UNLOCK(&node->nd_input_queue);
3406				NGI_GET_NODE(item, node); /* zaps stored node */
3407				ng_apply_item(node, item, rw);
3408				NG_NODE_UNREF(node);
3409			}
3410		}
3411		NG_NODE_UNREF(node);
3412	}
3413}
3414
3415static void
3416ng_worklist_remove(node_p node)
3417{
3418	mtx_assert(&node->nd_input_queue.q_mtx, MA_OWNED);
3419
3420	NG_WORKLIST_LOCK();
3421	if (node->nd_flags & NGF_WORKQ) {
3422		node->nd_flags &= ~NGF_WORKQ;
3423		TAILQ_REMOVE(&ng_worklist, node, nd_work);
3424		NG_WORKLIST_UNLOCK();
3425		NG_NODE_UNREF(node);
3426		CTR3(KTR_NET, "%20s: node [%x] (%p) removed from worklist",
3427		    __func__, node->nd_ID, node);
3428	} else {
3429		NG_WORKLIST_UNLOCK();
3430	}
3431}
3432
3433/*
3434 * XXX
3435 * It's posible that a debugging NG_NODE_REF may need
3436 * to be outside the mutex zone
3437 */
3438static void
3439ng_setisr(node_p node)
3440{
3441
3442	mtx_assert(&node->nd_input_queue.q_mtx, MA_OWNED);
3443
3444	if ((node->nd_flags & NGF_WORKQ) == 0) {
3445		/*
3446		 * If we are not already on the work queue,
3447		 * then put us on.
3448		 */
3449		node->nd_flags |= NGF_WORKQ;
3450		NG_WORKLIST_LOCK();
3451		TAILQ_INSERT_TAIL(&ng_worklist, node, nd_work);
3452		NG_WORKLIST_UNLOCK();
3453		NG_NODE_REF(node); /* XXX fafe in mutex? */
3454		CTR3(KTR_NET, "%20s: node [%x] (%p) put on worklist", __func__,
3455		    node->nd_ID, node);
3456	} else
3457		CTR3(KTR_NET, "%20s: node [%x] (%p) already on worklist",
3458		    __func__, node->nd_ID, node);
3459	schednetisr(NETISR_NETGRAPH);
3460}
3461
3462
3463/***********************************************************************
3464* Externally useable functions to set up a queue item ready for sending
3465***********************************************************************/
3466
3467#ifdef	NETGRAPH_DEBUG
3468#define	ITEM_DEBUG_CHECKS						\
3469	do {								\
3470		if (NGI_NODE(item) ) {					\
3471			printf("item already has node");		\
3472			kdb_enter("has node");				\
3473			NGI_CLR_NODE(item);				\
3474		}							\
3475		if (NGI_HOOK(item) ) {					\
3476			printf("item already has hook");		\
3477			kdb_enter("has hook");				\
3478			NGI_CLR_HOOK(item);				\
3479		}							\
3480	} while (0)
3481#else
3482#define ITEM_DEBUG_CHECKS
3483#endif
3484
3485/*
3486 * Put mbuf into the item.
3487 * Hook and node references will be removed when the item is dequeued.
3488 * (or equivalent)
3489 * (XXX) Unsafe because no reference held by peer on remote node.
3490 * remote node might go away in this timescale.
3491 * We know the hooks can't go away because that would require getting
3492 * a writer item on both nodes and we must have at least a  reader
3493 * here to be able to do this.
3494 * Note that the hook loaded is the REMOTE hook.
3495 *
3496 * This is possibly in the critical path for new data.
3497 */
3498item_p
3499ng_package_data(struct mbuf *m, int flags)
3500{
3501	item_p item;
3502
3503	if ((item = ng_getqblk(flags)) == NULL) {
3504		NG_FREE_M(m);
3505		return (NULL);
3506	}
3507	ITEM_DEBUG_CHECKS;
3508	item->el_flags = NGQF_DATA | NGQF_READER;
3509	item->el_next = NULL;
3510	NGI_M(item) = m;
3511	return (item);
3512}
3513
3514/*
3515 * Allocate a queue item and put items into it..
3516 * Evaluate the address as this will be needed to queue it and
3517 * to work out what some of the fields should be.
3518 * Hook and node references will be removed when the item is dequeued.
3519 * (or equivalent)
3520 */
3521item_p
3522ng_package_msg(struct ng_mesg *msg, int flags)
3523{
3524	item_p item;
3525
3526	if ((item = ng_getqblk(flags)) == NULL) {
3527		NG_FREE_MSG(msg);
3528		return (NULL);
3529	}
3530	ITEM_DEBUG_CHECKS;
3531	/* Messages items count as writers unless explicitly exempted. */
3532	if (msg->header.cmd & NGM_READONLY)
3533		item->el_flags = NGQF_MESG | NGQF_READER;
3534	else
3535		item->el_flags = NGQF_MESG | NGQF_WRITER;
3536	item->el_next = NULL;
3537	/*
3538	 * Set the current lasthook into the queue item
3539	 */
3540	NGI_MSG(item) = msg;
3541	NGI_RETADDR(item) = 0;
3542	return (item);
3543}
3544
3545
3546
3547#define SET_RETADDR(item, here, retaddr)				\
3548	do {	/* Data or fn items don't have retaddrs */		\
3549		if ((item->el_flags & NGQF_TYPE) == NGQF_MESG) {	\
3550			if (retaddr) {					\
3551				NGI_RETADDR(item) = retaddr;		\
3552			} else {					\
3553				/*					\
3554				 * The old return address should be ok.	\
3555				 * If there isn't one, use the address	\
3556				 * here.				\
3557				 */					\
3558				if (NGI_RETADDR(item) == 0) {		\
3559					NGI_RETADDR(item)		\
3560						= ng_node2ID(here);	\
3561				}					\
3562			}						\
3563		}							\
3564	} while (0)
3565
3566int
3567ng_address_hook(node_p here, item_p item, hook_p hook, ng_ID_t retaddr)
3568{
3569	hook_p peer;
3570	node_p peernode;
3571	ITEM_DEBUG_CHECKS;
3572	/*
3573	 * Quick sanity check..
3574	 * Since a hook holds a reference on it's node, once we know
3575	 * that the peer is still connected (even if invalid,) we know
3576	 * that the peer node is present, though maybe invalid.
3577	 */
3578	if ((hook == NULL)
3579	|| NG_HOOK_NOT_VALID(hook)
3580	|| (NG_HOOK_PEER(hook) == NULL)
3581	|| NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))
3582	|| NG_NODE_NOT_VALID(NG_PEER_NODE(hook))) {
3583		NG_FREE_ITEM(item);
3584		TRAP_ERROR();
3585		return (ENETDOWN);
3586	}
3587
3588	/*
3589	 * Transfer our interest to the other (peer) end.
3590	 */
3591	peer = NG_HOOK_PEER(hook);
3592	NG_HOOK_REF(peer);
3593	NGI_SET_HOOK(item, peer);
3594	peernode = NG_PEER_NODE(hook);
3595	NG_NODE_REF(peernode);
3596	NGI_SET_NODE(item, peernode);
3597	SET_RETADDR(item, here, retaddr);
3598	return (0);
3599}
3600
3601int
3602ng_address_path(node_p here, item_p item, char *address, ng_ID_t retaddr)
3603{
3604	node_p	dest = NULL;
3605	hook_p	hook = NULL;
3606	int	error;
3607
3608	ITEM_DEBUG_CHECKS;
3609	/*
3610	 * Note that ng_path2noderef increments the reference count
3611	 * on the node for us if it finds one. So we don't have to.
3612	 */
3613	error = ng_path2noderef(here, address, &dest, &hook);
3614	if (error) {
3615		NG_FREE_ITEM(item);
3616		return (error);
3617	}
3618	NGI_SET_NODE(item, dest);
3619	if ( hook) {
3620		NG_HOOK_REF(hook);	/* don't let it go while on the queue */
3621		NGI_SET_HOOK(item, hook);
3622	}
3623	SET_RETADDR(item, here, retaddr);
3624	return (0);
3625}
3626
3627int
3628ng_address_ID(node_p here, item_p item, ng_ID_t ID, ng_ID_t retaddr)
3629{
3630	node_p dest;
3631
3632	ITEM_DEBUG_CHECKS;
3633	/*
3634	 * Find the target node.
3635	 */
3636	dest = ng_ID2noderef(ID); /* GETS REFERENCE! */
3637	if (dest == NULL) {
3638		NG_FREE_ITEM(item);
3639		TRAP_ERROR();
3640		return(EINVAL);
3641	}
3642	/* Fill out the contents */
3643	NGI_SET_NODE(item, dest);
3644	NGI_CLR_HOOK(item);
3645	SET_RETADDR(item, here, retaddr);
3646	return (0);
3647}
3648
3649/*
3650 * special case to send a message to self (e.g. destroy node)
3651 * Possibly indicate an arrival hook too.
3652 * Useful for removing that hook :-)
3653 */
3654item_p
3655ng_package_msg_self(node_p here, hook_p hook, struct ng_mesg *msg)
3656{
3657	item_p item;
3658
3659	/*
3660	 * Find the target node.
3661	 * If there is a HOOK argument, then use that in preference
3662	 * to the address.
3663	 */
3664	if ((item = ng_getqblk(NG_NOFLAGS)) == NULL) {
3665		NG_FREE_MSG(msg);
3666		return (NULL);
3667	}
3668
3669	/* Fill out the contents */
3670	item->el_flags = NGQF_MESG | NGQF_WRITER;
3671	item->el_next = NULL;
3672	NG_NODE_REF(here);
3673	NGI_SET_NODE(item, here);
3674	if (hook) {
3675		NG_HOOK_REF(hook);
3676		NGI_SET_HOOK(item, hook);
3677	}
3678	NGI_MSG(item) = msg;
3679	NGI_RETADDR(item) = ng_node2ID(here);
3680	return (item);
3681}
3682
3683/*
3684 * Send ng_item_fn function call to the specified node.
3685 */
3686
3687int
3688ng_send_fn1(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2,
3689	int flags)
3690{
3691	item_p item;
3692
3693	if ((item = ng_getqblk(flags)) == NULL) {
3694		return (ENOMEM);
3695	}
3696	item->el_flags = NGQF_FN | NGQF_WRITER;
3697	NG_NODE_REF(node); /* and one for the item */
3698	NGI_SET_NODE(item, node);
3699	if (hook) {
3700		NG_HOOK_REF(hook);
3701		NGI_SET_HOOK(item, hook);
3702	}
3703	NGI_FN(item) = fn;
3704	NGI_ARG1(item) = arg1;
3705	NGI_ARG2(item) = arg2;
3706	return(ng_snd_item(item, flags));
3707}
3708
3709/*
3710 * Send ng_item_fn2 function call to the specified.
3711 */
3712
3713int
3714ng_send_fn21(node_p node, hook_p hook, ng_item_fn2 *fn, void * arg1, int arg2,
3715	int flags)
3716{
3717	item_p item;
3718
3719	if ((item = ng_getqblk(flags)) == NULL) {
3720		return (ENOMEM);
3721	}
3722	item->el_flags = NGQF_FN2 | NGQF_WRITER;
3723	NG_NODE_REF(node); /* and one for the item */
3724	NGI_SET_NODE(item, node);
3725	if (hook) {
3726		NG_HOOK_REF(hook);
3727		NGI_SET_HOOK(item, hook);
3728	}
3729	NGI_FN2(item) = fn;
3730	NGI_ARG1(item) = arg1;
3731	NGI_ARG2(item) = arg2;
3732	return(ng_snd_item(item, flags));
3733}
3734
3735/*
3736 * Send ng_item_fn2 function call to the specified node
3737 * with copying apply pointer from specified item.
3738 * Passed item left untouched.
3739 */
3740
3741int
3742ng_send_fn21_cont(item_p pitem, node_p node, hook_p hook,
3743    ng_item_fn2 *fn, void * arg1, int arg2, int flags)
3744{
3745	item_p item;
3746
3747	if ((item = ng_getqblk(flags)) == NULL) {
3748		return (ENOMEM);
3749	}
3750	item->el_flags = NGQF_FN2 | NGQF_WRITER;
3751	NG_NODE_REF(node); /* and one for the item */
3752	NGI_SET_NODE(item, node);
3753	if (hook) {
3754		NG_HOOK_REF(hook);
3755		NGI_SET_HOOK(item, hook);
3756	}
3757	NGI_FN2(item) = fn;
3758	NGI_ARG1(item) = arg1;
3759	NGI_ARG2(item) = arg2;
3760	item->apply = pitem->apply;
3761	return(ng_snd_item(item, flags));
3762}
3763
3764/*
3765 * Send ng_item_fn2 function call to the specified node
3766 * reusing item including apply pointer.
3767 * Passed item is consumed.
3768 */
3769
3770int
3771ng_send_fn21_fwd(item_p item, node_p node, hook_p hook,
3772    ng_item_fn2 *fn, void * arg1, int arg2, int flags)
3773{
3774	item->el_flags = NGQF_FN2 | NGQF_WRITER;
3775	NG_NODE_REF(node); /* and one for the item */
3776	NGI_SET_NODE(item, node);
3777	if (hook) {
3778		NG_HOOK_REF(hook);
3779		NGI_SET_HOOK(item, hook);
3780	}
3781	NGI_FN2(item) = fn;
3782	NGI_ARG1(item) = arg1;
3783	NGI_ARG2(item) = arg2;
3784	return(ng_snd_item(item, flags));
3785}
3786
3787/*
3788 * Official timeout routines for Netgraph nodes.
3789 */
3790static void
3791ng_callout_trampoline(void *arg)
3792{
3793	item_p item = arg;
3794
3795	ng_snd_item(item, 0);
3796}
3797
3798
3799int
3800ng_callout(struct callout *c, node_p node, hook_p hook, int ticks,
3801    ng_item_fn *fn, void * arg1, int arg2)
3802{
3803	item_p item, oitem;
3804
3805	if ((item = ng_getqblk(NG_NOFLAGS)) == NULL)
3806		return (ENOMEM);
3807
3808	item->el_flags = NGQF_FN | NGQF_WRITER;
3809	NG_NODE_REF(node);		/* and one for the item */
3810	NGI_SET_NODE(item, node);
3811	if (hook) {
3812		NG_HOOK_REF(hook);
3813		NGI_SET_HOOK(item, hook);
3814	}
3815	NGI_FN(item) = fn;
3816	NGI_ARG1(item) = arg1;
3817	NGI_ARG2(item) = arg2;
3818	oitem = c->c_arg;
3819	if (callout_reset(c, ticks, &ng_callout_trampoline, item) == 1 &&
3820	    oitem != NULL)
3821		NG_FREE_ITEM(oitem);
3822	return (0);
3823}
3824
3825/* A special modified version of untimeout() */
3826int
3827ng_uncallout(struct callout *c, node_p node)
3828{
3829	item_p item;
3830	int rval;
3831
3832	KASSERT(c != NULL, ("ng_uncallout: NULL callout"));
3833	KASSERT(node != NULL, ("ng_uncallout: NULL node"));
3834
3835	rval = callout_stop(c);
3836	item = c->c_arg;
3837	/* Do an extra check */
3838	if ((rval > 0) && (c->c_func == &ng_callout_trampoline) &&
3839	    (NGI_NODE(item) == node)) {
3840		/*
3841		 * We successfully removed it from the queue before it ran
3842		 * So now we need to unreference everything that was
3843		 * given extra references. (NG_FREE_ITEM does this).
3844		 */
3845		NG_FREE_ITEM(item);
3846	}
3847	c->c_arg = NULL;
3848
3849	return (rval);
3850}
3851
3852/*
3853 * Set the address, if none given, give the node here.
3854 */
3855void
3856ng_replace_retaddr(node_p here, item_p item, ng_ID_t retaddr)
3857{
3858	if (retaddr) {
3859		NGI_RETADDR(item) = retaddr;
3860	} else {
3861		/*
3862		 * The old return address should be ok.
3863		 * If there isn't one, use the address here.
3864		 */
3865		NGI_RETADDR(item) = ng_node2ID(here);
3866	}
3867}
3868
3869#define TESTING
3870#ifdef TESTING
3871/* just test all the macros */
3872void
3873ng_macro_test(item_p item);
3874void
3875ng_macro_test(item_p item)
3876{
3877	node_p node = NULL;
3878	hook_p hook = NULL;
3879	struct mbuf *m;
3880	struct ng_mesg *msg;
3881	ng_ID_t retaddr;
3882	int	error;
3883
3884	NGI_GET_M(item, m);
3885	NGI_GET_MSG(item, msg);
3886	retaddr = NGI_RETADDR(item);
3887	NG_SEND_DATA(error, hook, m, NULL);
3888	NG_SEND_DATA_ONLY(error, hook, m);
3889	NG_FWD_NEW_DATA(error, item, hook, m);
3890	NG_FWD_ITEM_HOOK(error, item, hook);
3891	NG_SEND_MSG_HOOK(error, node, msg, hook, retaddr);
3892	NG_SEND_MSG_ID(error, node, msg, retaddr, retaddr);
3893	NG_SEND_MSG_PATH(error, node, msg, ".:", retaddr);
3894	NG_FWD_MSG_HOOK(error, node, item, hook, retaddr);
3895}
3896#endif /* TESTING */
3897
3898