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