6 * Copyright (c) 1996-1999 Whistle Communications, Inc.
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.
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
38 * Authors: Julian Elischer <julian@freebsd.org>
39 * Archie Cobbs <archie@freebsd.org>
41 * $FreeBSD: src/sys/netgraph/ng_base.c,v 1.159 2008/04/19 05:30:49 mav Exp $
42 * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
46 * This file implements the base netgraph code.
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>
56 #include <sys/limits.h>
57 #include <sys/malloc.h>
59 #include <sys/msgport2.h>
60 #include <sys/mutex2.h>
61 #include <sys/queue.h>
62 #include <sys/sysctl.h>
63 #include <sys/syslog.h>
64 #include <sys/refcount.h>
66 #include <sys/taskqueue.h>
67 #include <machine/cpu.h>
69 #include <net/netisr.h>
71 #include <netgraph7/ng_message.h>
72 #include <netgraph7/netgraph.h>
73 #include <netgraph7/ng_parse.h>
75 MODULE_VERSION(netgraph, NG_ABI_VERSION);
77 /* Mutex to protect topology events. */
78 static struct mtx ng_topo_mtx;
81 static struct mtx ng_nodelist_mtx; /* protects global node/hook lists */
82 static struct mtx ngq_mtx; /* protects the queue item list */
84 static SLIST_HEAD(, ng_node) ng_allnodes;
85 static LIST_HEAD(, ng_node) ng_freenodes; /* in debug, we never free() them */
86 static SLIST_HEAD(, ng_hook) ng_allhooks;
87 static LIST_HEAD(, ng_hook) ng_freehooks; /* in debug, we never free() them */
89 static void ng_dumpitems(void);
90 static void ng_dumpnodes(void);
91 static void ng_dumphooks(void);
93 #endif /* NETGRAPH_DEBUG */
95 * DEAD versions of the structures.
96 * In order to avoid races, it is sometimes neccesary to point
97 * at SOMETHING even though theoretically, the current entity is
98 * INVALID. Use these to avoid these races.
100 struct ng_type ng_deadtype = {
104 NULL, /* constructor */
111 NULL, /* disconnect */
115 struct ng_node ng_deadnode = {
122 LIST_HEAD_INITIALIZER(ng_deadnode.hooks),
123 {}, /* all_nodes list entry */
124 {}, /* id hashtable list entry */
127 {}, /* should never use! (should hang) */
128 {}, /* workqueue entry */
129 STAILQ_HEAD_INITIALIZER(ng_deadnode.nd_input_queue.queue),
132 #ifdef NETGRAPH_DEBUG
137 #endif /* NETGRAPH_DEBUG */
140 struct ng_hook ng_deadhook = {
143 HK_INVALID | HK_DEAD,
144 0, /* undefined data link type */
145 &ng_deadhook, /* Peer is self */
146 &ng_deadnode, /* attached to deadnode */
148 NULL, /* override rcvmsg() */
149 NULL, /* override rcvdata() */
150 1, /* refs always >= 1 */
151 #ifdef NETGRAPH_DEBUG
156 #endif /* NETGRAPH_DEBUG */
160 * END DEAD STRUCTURES
162 /* List nodes with unallocated work */
163 static STAILQ_HEAD(, ng_node) ng_worklist = STAILQ_HEAD_INITIALIZER(ng_worklist);
164 static struct mtx ng_worklist_mtx; /* MUST LOCK NODE FIRST */
166 /* List of installed types */
167 static LIST_HEAD(, ng_type) ng_typelist;
168 static struct mtx ng_typelist_mtx;
170 /* Hash related definitions */
171 /* XXX Don't need to initialise them because it's a LIST */
172 #define NG_ID_HASH_SIZE 128 /* most systems wont need even this many */
173 static LIST_HEAD(, ng_node) ng_ID_hash[NG_ID_HASH_SIZE];
174 static struct mtx ng_idhash_mtx;
175 /* Method to find a node.. used twice so do it here */
176 #define NG_IDHASH_FN(ID) ((ID) % (NG_ID_HASH_SIZE))
177 #define NG_IDHASH_FIND(ID, node) \
179 KKASSERT(mtx_owned(&ng_idhash_mtx)); \
180 LIST_FOREACH(node, &ng_ID_hash[NG_IDHASH_FN(ID)], \
182 if (NG_NODE_IS_VALID(node) \
183 && (NG_NODE_ID(node) == ID)) { \
189 #define NG_NAME_HASH_SIZE 128 /* most systems wont need even this many */
190 static LIST_HEAD(, ng_node) ng_name_hash[NG_NAME_HASH_SIZE];
191 static struct mtx ng_namehash_mtx;
192 #define NG_NAMEHASH(NAME, HASH) \
196 for (c = (const u_char*)(NAME); *c; c++)\
198 (HASH) = h % (NG_NAME_HASH_SIZE); \
202 /* Internal functions */
203 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
204 static int ng_generic_msg(node_p here, item_p item, hook_p lasthook);
205 static ng_ID_t ng_decodeidname(const char *name);
206 static int ngb_mod_event(module_t mod, int event, void *data);
207 static void ng_worklist_add(node_p node);
208 static void ngtask(void *, int);
209 static int ng_apply_item(node_p node, item_p item, int rw);
210 static void ng_flush_input_queue(node_p node);
211 static node_p ng_ID2noderef(ng_ID_t ID);
212 static int ng_con_nodes(item_p item, node_p node, const char *name,
213 node_p node2, const char *name2);
214 static int ng_con_part2(node_p node, item_p item, hook_p hook);
215 static int ng_con_part3(node_p node, item_p item, hook_p hook);
216 static int ng_mkpeer(node_p node, const char *name,
217 const char *name2, char *type);
218 static boolean_t bzero_ctor(void *obj, void *private, int ocflags);
220 /* Imported, these used to be externally visible, some may go back. */
221 void ng_destroy_hook(hook_p hook);
222 node_p ng_name2noderef(node_p node, const char *name);
223 int ng_path2noderef(node_p here, const char *path,
224 node_p *dest, hook_p *lasthook);
225 int ng_make_node(const char *type, node_p *nodepp);
226 int ng_path_parse(char *addr, char **node, char **path, char **hook);
227 void ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3);
228 void ng_unname(node_p node);
231 /* Our own netgraph malloc type */
232 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
233 MALLOC_DEFINE(M_NETGRAPH_HOOK, "netgraph_hook", "netgraph hook structures");
234 MALLOC_DEFINE(M_NETGRAPH_NODE, "netgraph_node", "netgraph node structures");
235 MALLOC_DEFINE(M_NETGRAPH_ITEM, "netgraph_item", "netgraph item structures");
236 MALLOC_DEFINE(M_NETGRAPH_MSG, "netgraph_msg", "netgraph name storage");
238 /* Should not be visible outside this file */
240 #define _NG_ALLOC_HOOK(hook) \
241 hook = kmalloc(sizeof(*hook), M_NETGRAPH_HOOK, \
242 M_WAITOK | M_NULLOK | M_ZERO)
243 #define _NG_ALLOC_NODE(node) \
244 node = kmalloc(sizeof(*node), M_NETGRAPH_NODE, \
245 M_WAITOK | M_NULLOK | M_ZERO)
247 #define NG_QUEUE_LOCK_INIT(n) \
248 mtx_init(&(n)->q_mtx)
249 #define NG_QUEUE_LOCK(n) \
250 mtx_lock(&(n)->q_mtx)
251 #define NG_QUEUE_UNLOCK(n) \
252 mtx_unlock(&(n)->q_mtx)
253 #define NG_WORKLIST_LOCK_INIT() \
254 mtx_init(&ng_worklist_mtx)
255 #define NG_WORKLIST_LOCK() \
256 mtx_lock(&ng_worklist_mtx)
257 #define NG_WORKLIST_UNLOCK() \
258 mtx_unlock(&ng_worklist_mtx)
260 #ifdef NETGRAPH_DEBUG /*----------------------------------------------*/
263 * In an attempt to help track reference count screwups
264 * we do not free objects back to the malloc system, but keep them
265 * in a local cache where we can examine them and keep information safely
266 * after they have been freed.
267 * We use this scheme for nodes and hooks, and to some extent for items.
269 static __inline hook_p
273 SLIST_ENTRY(ng_hook) temp;
274 mtx_lock(&ng_nodelist_mtx);
275 hook = LIST_FIRST(&ng_freehooks);
277 LIST_REMOVE(hook, hk_hooks);
278 bcopy(&hook->hk_all, &temp, sizeof(temp));
279 bzero(hook, sizeof(struct ng_hook));
280 bcopy(&temp, &hook->hk_all, sizeof(temp));
281 mtx_unlock(&ng_nodelist_mtx);
282 hook->hk_magic = HK_MAGIC;
284 mtx_unlock(&ng_nodelist_mtx);
285 _NG_ALLOC_HOOK(hook);
287 hook->hk_magic = HK_MAGIC;
288 mtx_lock(&ng_nodelist_mtx);
289 SLIST_INSERT_HEAD(&ng_allhooks, hook, hk_all);
290 mtx_unlock(&ng_nodelist_mtx);
296 static __inline node_p
300 SLIST_ENTRY(ng_node) temp;
301 mtx_lock(&ng_nodelist_mtx);
302 node = LIST_FIRST(&ng_freenodes);
304 LIST_REMOVE(node, nd_nodes);
305 bcopy(&node->nd_all, &temp, sizeof(temp));
306 bzero(node, sizeof(struct ng_node));
307 bcopy(&temp, &node->nd_all, sizeof(temp));
308 mtx_unlock(&ng_nodelist_mtx);
309 node->nd_magic = ND_MAGIC;
311 mtx_unlock(&ng_nodelist_mtx);
312 _NG_ALLOC_NODE(node);
314 node->nd_magic = ND_MAGIC;
315 mtx_lock(&ng_nodelist_mtx);
316 SLIST_INSERT_HEAD(&ng_allnodes, node, nd_all);
317 mtx_unlock(&ng_nodelist_mtx);
323 #define NG_ALLOC_HOOK(hook) do { (hook) = ng_alloc_hook(); } while (0)
324 #define NG_ALLOC_NODE(node) do { (node) = ng_alloc_node(); } while (0)
327 #define NG_FREE_HOOK(hook) \
329 mtx_lock(&ng_nodelist_mtx); \
330 LIST_INSERT_HEAD(&ng_freehooks, hook, hk_hooks); \
331 hook->hk_magic = 0; \
332 mtx_unlock(&ng_nodelist_mtx); \
335 #define NG_FREE_NODE(node) \
337 mtx_lock(&ng_nodelist_mtx); \
338 LIST_INSERT_HEAD(&ng_freenodes, node, nd_nodes); \
339 node->nd_magic = 0; \
340 mtx_unlock(&ng_nodelist_mtx); \
343 #else /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
345 #define NG_ALLOC_HOOK(hook) _NG_ALLOC_HOOK(hook)
346 #define NG_ALLOC_NODE(node) _NG_ALLOC_NODE(node)
348 #define NG_FREE_HOOK(hook) do { kfree((hook), M_NETGRAPH_HOOK); } while (0)
349 #define NG_FREE_NODE(node) do { kfree((node), M_NETGRAPH_NODE); } while (0)
351 #endif /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
353 /* Set this to kdb_enter("X") to catch all errors as they occur */
358 static ng_ID_t nextID = 1;
361 #define CHECK_DATA_MBUF(m) do { \
366 for (total = 0, n = (m); n != NULL; n = n->m_next) { \
368 if (n->m_nextpkt != NULL) \
369 panic("%s: m_nextpkt", __func__); \
372 if ((m)->m_pkthdr.len != total) { \
373 panic("%s: %d != %d", \
374 __func__, (m)->m_pkthdr.len, total); \
378 #define CHECK_DATA_MBUF(m)
381 #define ERROUT(x) do { error = (x); goto done; } while (0)
383 /************************************************************************
384 Parse type definitions for generic messages
385 ************************************************************************/
387 /* Handy structure parse type defining macro */
388 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
389 static const struct ng_parse_struct_field \
390 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
391 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
392 &ng_parse_struct_type, \
393 &ng_ ## lo ## _type_fields \
396 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
397 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
398 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
399 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
400 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
401 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
402 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
404 /* Get length of an array when the length is stored as a 32 bit
405 value immediately preceding the array -- as with struct namelist
406 and struct typelist. */
408 ng_generic_list_getLength(const struct ng_parse_type *type,
409 const u_char *start, const u_char *buf)
411 return *((const u_int32_t *)(buf - 4));
414 /* Get length of the array of struct linkinfo inside a struct hooklist */
416 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
417 const u_char *start, const u_char *buf)
419 const struct hooklist *hl = (const struct hooklist *)start;
421 return hl->nodeinfo.hooks;
424 /* Array type for a variable length array of struct namelist */
425 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
426 &ng_generic_nodeinfo_type,
427 &ng_generic_list_getLength
429 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
430 &ng_parse_array_type,
431 &ng_nodeinfoarray_type_info
434 /* Array type for a variable length array of struct typelist */
435 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
436 &ng_generic_typeinfo_type,
437 &ng_generic_list_getLength
439 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
440 &ng_parse_array_type,
441 &ng_typeinfoarray_type_info
444 /* Array type for array of struct linkinfo in struct hooklist */
445 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
446 &ng_generic_linkinfo_type,
447 &ng_generic_linkinfo_getLength
449 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
450 &ng_parse_array_type,
451 &ng_generic_linkinfo_array_type_info
454 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
455 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
456 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
457 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
458 (&ng_generic_nodeinfoarray_type));
460 /* List of commands and how to convert arguments to/from ASCII */
461 static const struct ng_cmdlist ng_generic_cmds[] = {
473 &ng_generic_mkpeer_type,
480 &ng_generic_connect_type,
487 &ng_generic_name_type,
494 &ng_generic_rmhook_type,
502 &ng_generic_nodeinfo_type
509 &ng_generic_hooklist_type
516 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
523 &ng_generic_listnodes_type
530 &ng_generic_typeinfo_type
537 &ng_parse_string_type
544 &ng_parse_string_type
550 &ng_parse_ng_mesg_type,
551 &ng_parse_ng_mesg_type
557 &ng_parse_ng_mesg_type,
558 &ng_parse_ng_mesg_type
563 /************************************************************************
565 ************************************************************************/
568 * Instantiate a node of the requested type
571 ng_make_node(const char *typename, node_p *nodepp)
573 struct ng_type *type;
576 /* Check that the type makes sense */
577 if (typename == NULL) {
582 /* Locate the node type. If we fail we return. Do not try to load
585 if ((type = ng_findtype(typename)) == NULL)
589 * If we have a constructor, then make the node and
590 * call the constructor to do type specific initialisation.
592 if (type->constructor != NULL) {
593 if ((error = ng_make_node_common(type, nodepp)) == 0) {
594 if ((error = ((*type->constructor)(*nodepp)) != 0)) {
595 NG_NODE_UNREF(*nodepp);
600 * Node has no constructor. We cannot ask for one
601 * to be made. It must be brought into existence by
602 * some external agency. The external agency should
603 * call ng_make_node_common() directly to get the
604 * netgraph part initialised.
613 * Generic node creation. Called by node initialisation for externally
614 * instantiated nodes (e.g. hardware, sockets, etc ).
615 * The returned node has a reference count of 1.
618 ng_make_node_common(struct ng_type *type, node_p *nodepp)
622 /* Require the node type to have been already installed */
623 if (ng_findtype(type->name) == NULL) {
628 /* Make a node and try attach it to the type */
634 node->nd_type = type;
635 NG_NODE_REF(node); /* note reference */
638 NG_QUEUE_LOCK_INIT(&node->nd_input_queue);
639 STAILQ_INIT(&node->nd_input_queue.queue);
640 node->nd_input_queue.q_flags = 0;
642 /* Initialize hook list for new node */
643 LIST_INIT(&node->nd_hooks);
645 /* Link us into the name hash. */
646 mtx_lock(&ng_namehash_mtx);
647 LIST_INSERT_HEAD(&ng_name_hash[0], node, nd_nodes);
648 mtx_unlock(&ng_namehash_mtx);
650 /* get an ID and put us in the hash chain */
651 mtx_lock(&ng_idhash_mtx);
652 for (;;) { /* wrap protection, even if silly */
654 node->nd_ID = nextID++; /* 137/second for 1 year before wrap */
656 /* Is there a problem with the new number? */
657 NG_IDHASH_FIND(node->nd_ID, node2); /* already taken? */
658 if ((node->nd_ID != 0) && (node2 == NULL)) {
662 LIST_INSERT_HEAD(&ng_ID_hash[NG_IDHASH_FN(node->nd_ID)],
664 mtx_unlock(&ng_idhash_mtx);
672 * Forceably start the shutdown process on a node. Either call
673 * its shutdown method, or do the default shutdown if there is
674 * no type-specific method.
676 * We can only be called from a shutdown message, so we know we have
677 * a writer lock, and therefore exclusive access. It also means
678 * that we should not be on the work queue, but we check anyhow.
680 * Persistent node types must have a type-specific method which
681 * allocates a new node in which case, this one is irretrievably going away,
682 * or cleans up anything it needs, and just makes the node valid again,
683 * in which case we allow the node to survive.
685 * XXX We need to think of how to tell a persistent node that we
686 * REALLY need to go away because the hardware has gone or we
687 * are rebooting.... etc.
690 ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3)
694 /* Check if it's already shutting down */
695 if ((node->nd_flags & NGF_CLOSING) != 0)
698 if (node == &ng_deadnode) {
699 printf ("shutdown called on deadnode\n");
703 /* Add an extra reference so it doesn't go away during this */
707 * Mark it invalid so any newcomers know not to try use it
708 * Also add our own mark so we can't recurse
709 * note that NGF_INVALID does not do this as it's also set during
712 node->nd_flags |= NGF_INVALID|NGF_CLOSING;
714 /* If node has its pre-shutdown method, then call it first*/
715 if (node->nd_type && node->nd_type->close)
716 (*node->nd_type->close)(node);
718 /* Notify all remaining connected nodes to disconnect */
719 while ((hook = LIST_FIRST(&node->nd_hooks)) != NULL)
720 ng_destroy_hook(hook);
723 * Drain the input queue forceably.
724 * it has no hooks so what's it going to do, bleed on someone?
725 * Theoretically we came here from a queue entry that was added
726 * Just before the queue was closed, so it should be empty anyway.
727 * Also removes us from worklist if needed.
729 ng_flush_input_queue(node);
731 /* Ask the type if it has anything to do in this case */
732 if (node->nd_type && node->nd_type->shutdown) {
733 (*node->nd_type->shutdown)(node);
734 if (NG_NODE_IS_VALID(node)) {
736 * Well, blow me down if the node code hasn't declared
737 * that it doesn't want to die.
738 * Presumably it is a persistant node.
739 * If we REALLY want it to go away,
740 * e.g. hardware going away,
741 * Our caller should set NGF_REALLY_DIE in nd_flags.
743 node->nd_flags &= ~(NGF_INVALID|NGF_CLOSING);
744 NG_NODE_UNREF(node); /* Assume they still have theirs */
747 } else { /* do the default thing */
751 ng_unname(node); /* basically a NOP these days */
754 * Remove extra reference, possibly the last
755 * Possible other holders of references may include
756 * timeout callouts, but theoretically the node's supposed to
757 * have cancelled them. Possibly hardware dependencies may
758 * force a driver to 'linger' with a reference.
764 * Remove a reference to the node, possibly the last.
765 * deadnode always acts as it it were the last.
768 ng_unref_node(node_p node)
772 if (node == &ng_deadnode) {
776 v = atomic_fetchadd_int(&node->nd_refs, -1);
778 if (v == 1) { /* we were the last */
780 mtx_lock(&ng_namehash_mtx);
781 node->nd_type->refs--; /* XXX maybe should get types lock? */
782 LIST_REMOVE(node, nd_nodes);
783 mtx_unlock(&ng_namehash_mtx);
785 mtx_lock(&ng_idhash_mtx);
786 LIST_REMOVE(node, nd_idnodes);
787 mtx_unlock(&ng_idhash_mtx);
789 mtx_uninit(&node->nd_input_queue.q_mtx);
795 /************************************************************************
797 ************************************************************************/
799 ng_ID2noderef(ng_ID_t ID)
802 mtx_lock(&ng_idhash_mtx);
803 NG_IDHASH_FIND(ID, node);
806 mtx_unlock(&ng_idhash_mtx);
811 ng_node2ID(node_p node)
813 return (node ? NG_NODE_ID(node) : 0);
816 /************************************************************************
818 ************************************************************************/
821 * Assign a node a name. Once assigned, the name cannot be changed.
824 ng_name_node(node_p node, const char *name)
829 /* Check the name is valid */
830 for (i = 0; i < NG_NODESIZ; i++) {
831 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
834 if (i == 0 || name[i] != '\0') {
838 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
843 /* Check the name isn't already being used */
844 if ((node2 = ng_name2noderef(node, name)) != NULL) {
845 NG_NODE_UNREF(node2);
851 strlcpy(NG_NODE_NAME(node), name, NG_NODESIZ);
853 /* Update name hash. */
854 NG_NAMEHASH(name, hash);
855 mtx_lock(&ng_namehash_mtx);
856 LIST_REMOVE(node, nd_nodes);
857 LIST_INSERT_HEAD(&ng_name_hash[hash], node, nd_nodes);
858 mtx_unlock(&ng_namehash_mtx);
864 * Find a node by absolute name. The name should NOT end with ':'
865 * The name "." means "this node" and "[xxx]" means "the node
866 * with ID (ie, at address) xxx".
868 * Returns the node if found, else NULL.
869 * Eventually should add something faster than a sequential search.
870 * Note it acquires a reference on the node so you can be sure it's still
874 ng_name2noderef(node_p here, const char *name)
880 /* "." means "this node" */
881 if (strcmp(name, ".") == 0) {
886 /* Check for name-by-ID */
887 if ((temp = ng_decodeidname(name)) != 0) {
888 return (ng_ID2noderef(temp));
891 /* Find node by name */
892 NG_NAMEHASH(name, hash);
893 mtx_lock(&ng_namehash_mtx);
894 LIST_FOREACH(node, &ng_name_hash[hash], nd_nodes) {
895 if (NG_NODE_IS_VALID(node) &&
896 (strcmp(NG_NODE_NAME(node), name) == 0)) {
902 mtx_unlock(&ng_namehash_mtx);
907 * Decode an ID name, eg. "[f03034de]". Returns 0 if the
908 * string is not valid, otherwise returns the value.
911 ng_decodeidname(const char *name)
913 const int len = strlen(name);
917 /* Check for proper length, brackets, no leading junk */
920 || (name[len - 1] != ']')
921 || (!isxdigit(name[1]))) {
926 val = strtoul(name + 1, &eptr, 16);
927 if ((eptr - name != len - 1)
928 || (val == ULONG_MAX)
936 * Remove a name from a node. This should only be called
937 * when shutting down and removing the node.
938 * IF we allow name changing this may be more resurrected.
941 ng_unname(node_p node)
945 /************************************************************************
947 Names are not optional. Hooks are always connected, except for a
948 brief moment within these routines. On invalidation or during creation
949 they are connected to the 'dead' hook.
950 ************************************************************************/
953 * Remove a hook reference
956 ng_unref_hook(hook_p hook)
960 if (hook == &ng_deadhook) {
964 v = atomic_fetchadd_int(&hook->hk_refs, -1);
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)));
974 * Add an unconnected hook to a node. Only used internally.
975 * Assumes node is locked. (XXX not yet true )
978 ng_add_hook(node_p node, const char *name, hook_p *hookp)
983 /* Check that the given name is good */
988 if (ng_findhook(node, name) != NULL) {
993 /* Allocate the hook and link it up */
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 */
1006 strlcpy(NG_HOOK_NAME(hook), name, NG_HOOKSIZ);
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.
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 */
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.
1022 LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
1023 node->nd_numhooks++;
1024 NG_HOOK_REF(hook); /* one for the node */
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?
1039 ng_findhook(node_p node, const char *name)
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))
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.
1068 * This routine is called at all stages of hook creation
1069 * on error detection and must be able to handle any such stage.
1072 ng_destroy_hook(hook_p hook)
1077 if (hook == &ng_deadhook) { /* better safe than sorry */
1078 printf("ng_destroy_hook called on deadhook\n");
1083 * Protect divorce process with mutex, to avoid races on
1084 * simultaneous disconnect.
1086 mtx_lock(&ng_topo_mtx);
1088 hook->hk_flags |= HK_INVALID;
1090 peer = NG_HOOK_PEER(hook);
1091 node = NG_HOOK_NODE(hook);
1093 if (peer && (peer != &ng_deadhook)) {
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.
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) {
1103 * If it's already divorced from a node,
1106 mtx_unlock(&ng_topo_mtx);
1108 mtx_unlock(&ng_topo_mtx);
1109 ng_rmhook_self(peer); /* Send it a surprise */
1111 NG_HOOK_UNREF(peer); /* account for peer link */
1112 NG_HOOK_UNREF(hook); /* account for peer link */
1114 mtx_unlock(&ng_topo_mtx);
1116 KKASSERT(mtx_notowned(&ng_topo_mtx));
1119 * Remove the hook from the node's list to avoid possible recursion
1120 * in case the disconnection results in node shutdown.
1122 if (node == &ng_deadnode) { /* happens if called from ng_con_nodes() */
1125 LIST_REMOVE(hook, hk_hooks);
1126 node->nd_numhooks--;
1127 if (node->nd_type->disconnect) {
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)
1134 (*node->nd_type->disconnect) (hook);
1138 * Note that because we will point to ng_deadnode, the original node
1139 * is not decremented automatically so we do that manually.
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 */
1147 * Take two hooks on a node and merge the connection so that the given node
1148 * is effectively bypassed.
1151 ng_bypass(hook_p hook1, hook_p hook2)
1153 if (hook1->hk_node != hook2->hk_node) {
1157 hook1->hk_peer->hk_peer = hook2->hk_peer;
1158 hook2->hk_peer->hk_peer = hook1->hk_peer;
1160 hook1->hk_peer = &ng_deadhook;
1161 hook2->hk_peer = &ng_deadhook;
1163 NG_HOOK_UNREF(hook1);
1164 NG_HOOK_UNREF(hook2);
1166 /* XXX If we ever cache methods on hooks update them as well */
1167 ng_destroy_hook(hook1);
1168 ng_destroy_hook(hook2);
1173 * Install a new netgraph type
1176 ng_newtype(struct ng_type *tp)
1178 const size_t namelen = strlen(tp->name);
1180 /* Check version and type name fields */
1181 if ((tp->version != NG_ABI_VERSION)
1183 || (namelen >= NG_TYPESIZ)) {
1185 if (tp->version != NG_ABI_VERSION) {
1186 printf("Netgraph: Node type rejected. ABI mismatch. Suggest recompile\n");
1191 /* Check for name collision */
1192 if (ng_findtype(tp->name) != NULL) {
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);
1207 * unlink a netgraph type
1208 * If no examples exist
1211 ng_rmtype(struct ng_type *tp)
1213 /* Check for name collision */
1214 if (tp->refs != 1) {
1220 mtx_lock(&ng_typelist_mtx);
1221 LIST_REMOVE(tp, types);
1222 mtx_unlock(&ng_typelist_mtx);
1227 * Look for a type of the name given
1230 ng_findtype(const char *typename)
1232 struct ng_type *type;
1234 mtx_lock(&ng_typelist_mtx);
1235 LIST_FOREACH(type, &ng_typelist, types) {
1236 if (strcmp(type->name, typename) == 0)
1239 mtx_unlock(&ng_typelist_mtx);
1243 /************************************************************************
1245 ************************************************************************/
1247 * Connect two nodes using the specified hooks, using queued functions.
1250 ng_con_part3(node_p node, item_p item, hook_p hook)
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.
1263 if (NG_HOOK_NODE(hook) == &ng_deadnode) {
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.
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");
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.
1286 hook->hk_flags &= ~HK_INVALID;
1293 ng_con_part2(node_p node, item_p item, hook_p hook)
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.
1308 if (ng_findhook(node, NG_HOOK_NAME(hook)) != NULL) {
1310 ng_destroy_hook(hook); /* should destroy peer too */
1311 printf("failed in ng_con_part2()\n");
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.
1320 if (node->nd_type->newhook != NULL) {
1321 if ((error = (*node->nd_type->newhook)(node, hook,
1323 ng_destroy_hook(hook); /* should destroy peer too */
1324 printf("failed in ng_con_part2()\n");
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.
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 */
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
1345 * We can call the local one immediately as we have the
1346 * node locked, but we need to queue the remote one.
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");
1357 * Acquire topo mutex to avoid race with ng_destroy_hook().
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);
1367 mtx_unlock(&ng_topo_mtx);
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. */
1375 hook->hk_flags &= ~HK_INVALID; /* need both to be able to work */
1376 return (0); /* item was consumed. */
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.
1387 ng_con_nodes(item_p item, node_p node, const char *name,
1388 node_p node2, const char *name2)
1394 if (ng_findhook(node2, name2) != NULL) {
1397 if ((error = ng_add_hook(node, name, &hook))) /* gives us a ref */
1399 /* Allocate the other hook and link it up */
1400 NG_ALLOC_HOOK(hook2);
1401 if (hook2 == NULL) {
1403 ng_destroy_hook(hook); /* XXX check ref counts so far */
1404 NG_HOOK_UNREF(hook); /* including our ref */
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*/
1413 hook2->hk_node = &ng_deadnode;
1414 strlcpy(NG_HOOK_NAME(hook2), name2, NG_HOOKSIZ);
1417 * Queue the function above.
1418 * Procesing continues in that function in the lock context of
1421 if ((error = ng_send_fn2(node2, hook2, item, &ng_con_part2, NULL, 0,
1423 printf("failed in ng_con_nodes(): %d\n", error);
1424 ng_destroy_hook(hook); /* also zaps peer */
1427 NG_HOOK_UNREF(hook); /* Let each hook go if it wants to */
1428 NG_HOOK_UNREF(hook2);
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.
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.
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?
1450 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
1453 hook_p hook1, hook2;
1456 if ((error = ng_make_node(type, &node2))) {
1460 if ((error = ng_add_hook(node, name, &hook1))) { /* gives us a ref */
1461 ng_rmnode(node2, NULL, NULL, 0);
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);
1473 * Actually link the two hooks together.
1475 hook1->hk_peer = hook2;
1476 hook2->hk_peer = hook1;
1478 /* Each hook is referenced by the other */
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);
1487 if ((error == 0) && hook2->hk_node->nd_type->connect) {
1488 error = (*hook2->hk_node->nd_type->connect) (hook2);
1493 * drop the references we were holding on the two hooks.
1496 ng_destroy_hook(hook2); /* also zaps hook1 */
1497 ng_rmnode(node2, NULL, NULL, 0);
1499 /* As a last act, allow the hooks to be used */
1500 hook1->hk_flags &= ~HK_INVALID;
1501 hook2->hk_flags &= ~HK_INVALID;
1503 NG_HOOK_UNREF(hook1);
1504 NG_HOOK_UNREF(hook2);
1508 /************************************************************************
1509 Utility routines to send self messages
1510 ************************************************************************/
1512 /* Shut this node down as soon as everyone is clear of it */
1513 /* Should add arg "immediately" to jump the queue */
1515 ng_rmnode_self(node_p node)
1519 if (node == &ng_deadnode)
1521 node->nd_flags |= NGF_INVALID;
1522 if (node->nd_flags & NGF_CLOSING)
1525 error = ng_send_fn(node, NULL, &ng_rmnode, NULL, 0);
1530 ng_rmhook_part2(node_p node, hook_p hook, void *arg1, int arg2)
1532 ng_destroy_hook(hook);
1537 ng_rmhook_self(hook_p hook)
1540 node_p node = NG_HOOK_NODE(hook);
1542 if (node == &ng_deadnode)
1545 error = ng_send_fn(node, hook, &ng_rmhook_part2, NULL, 0);
1549 /***********************************************************************
1550 * Parse and verify a string of the form: <NODE:><PATH>
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.
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.
1562 * This returns -1 if the path is malformed. The char ** are optional.
1563 ***********************************************************************/
1565 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1567 char *node, *path, *hook;
1571 * Extract absolute NODE, if any
1573 for (path = addr; *path && *path != ':'; path++);
1575 node = addr; /* Here's the NODE */
1576 *path++ = '\0'; /* Here's the PATH */
1578 /* Node name must not be empty */
1582 /* A name of "." is OK; otherwise '.' not allowed */
1583 if (strcmp(node, ".") != 0) {
1584 for (k = 0; node[k]; k++)
1589 node = NULL; /* No absolute NODE */
1590 path = addr; /* Here's the PATH */
1593 /* Snoop for illegal characters in PATH */
1594 for (k = 0; path[k]; k++)
1598 /* Check for no repeated dots in PATH */
1599 for (k = 0; path[k]; k++)
1600 if (path[k] == '.' && path[k + 1] == '.')
1603 /* Remove extra (degenerate) dots from beginning or end of PATH */
1606 if (*path && path[strlen(path) - 1] == '.')
1607 path[strlen(path) - 1] = 0;
1609 /* If PATH has a dot, then we're not talking about a hook */
1611 for (hook = path, k = 0; path[k]; k++)
1612 if (path[k] == '.') {
1630 * Given a path, which may be absolute or relative, and a starting node,
1631 * return the destination node.
1634 ng_path2noderef(node_p here, const char *address,
1635 node_p *destp, hook_p *lasthook)
1637 char fullpath[NG_PATHSIZ];
1638 char *nodename, *path, pbuf[2];
1639 node_p node, oldnode;
1644 if (destp == NULL) {
1650 /* Make a writable copy of address for ng_path_parse() */
1651 strncpy(fullpath, address, sizeof(fullpath) - 1);
1652 fullpath[sizeof(fullpath) - 1] = '\0';
1654 /* Parse out node and sequence of hooks */
1655 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1660 pbuf[0] = '.'; /* Needs to be writable */
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.
1671 node = ng_name2noderef(here, nodename);
1686 * Now follow the sequence of hooks
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
1698 for (cp = path; node != NULL && *cp != '\0'; ) {
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
1706 for (segment = cp; *cp != '\0'; cp++) {
1714 if (*segment == '\0')
1717 /* We have a segment, so look for a hook by that name */
1718 hook = ng_findhook(node, segment);
1720 /* Can't get there from here... */
1722 || NG_HOOK_PEER(hook) == NULL
1723 || NG_HOOK_NOT_VALID(hook)
1724 || NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))) {
1726 NG_NODE_UNREF(node);
1728 printf("hooknotvalid %s %s %d %d %d %d ",
1732 NG_HOOK_PEER(hook) == NULL,
1733 NG_HOOK_NOT_VALID(hook),
1734 NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook)));
1740 * Hop on over to the next node
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?
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 */
1756 /* If node somehow missing, fail here (probably this is not needed) */
1764 if (lasthook != NULL)
1765 *lasthook = (hook ? NG_HOOK_PEER(hook) : NULL);
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.
1775 * read-write queue locking inline functions *
1776 \***************************************************************/
1778 static __inline void ng_queue_rw(node_p node, item_p item, int rw);
1779 static __inline item_p ng_dequeue(node_p node, int *rw);
1780 static __inline item_p ng_acquire_read(node_p node, item_p item);
1781 static __inline item_p ng_acquire_write(node_p node, item_p item);
1782 static __inline void ng_leave_read(node_p node);
1783 static __inline void ng_leave_write(node_p node);
1786 * Definition of the bits fields in the ng_queue flag word.
1787 * Defined here rather than in netgraph.h because no-one should fiddle
1790 * The ordering here may be important! don't shuffle these.
1793 Safety Barrier--------+ (adjustable to suit taste) (not used yet)
1796 +-------+-------+-------+-------+-------+-------+-------+-------+
1797 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
1798 | |A|c|t|i|v|e| |R|e|a|d|e|r| |C|o|u|n|t| | | | | | | | | |P|A|
1799 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |O|W|
1800 +-------+-------+-------+-------+-------+-------+-------+-------+
1801 \___________________________ ____________________________/ | |
1803 [active reader count] | |
1805 Operation Pending -------------------------------+ |
1807 Active Writer ---------------------------------------+
1809 Node queue has such semantics:
1810 - All flags modifications are atomic.
1811 - Reader count can be incremented only if there is no writer or pending flags.
1812 As soon as this can't be done with single operation, it is implemented with
1813 spin loop and atomic_cmpset().
1814 - Writer flag can be set only if there is no any bits set.
1815 It is implemented with atomic_cmpset().
1816 - Pending flag can be set any time, but to avoid collision on queue processing
1817 all queue fields are protected by the mutex.
1818 - Queue processing thread reads queue holding the mutex, but releases it while
1819 processing. When queue is empty pending flag is removed.
1822 #define WRITER_ACTIVE 0x00000001
1823 #define OP_PENDING 0x00000002
1824 #define READER_INCREMENT 0x00000004
1825 #define READER_MASK 0xfffffffc /* Not valid if WRITER_ACTIVE is set */
1826 #define SAFETY_BARRIER 0x00100000 /* 128K items queued should be enough */
1828 /* Defines of more elaborate states on the queue */
1829 /* Mask of bits a new read cares about */
1830 #define NGQ_RMASK (WRITER_ACTIVE|OP_PENDING)
1832 /* Mask of bits a new write cares about */
1833 #define NGQ_WMASK (NGQ_RMASK|READER_MASK)
1835 /* Test to decide if there is something on the queue. */
1836 #define QUEUE_ACTIVE(QP) ((QP)->q_flags & OP_PENDING)
1838 /* How to decide what the next queued item is. */
1839 #define HEAD_IS_READER(QP) NGI_QUEUED_READER(STAILQ_FIRST(&(QP)->queue))
1840 #define HEAD_IS_WRITER(QP) NGI_QUEUED_WRITER(STAILQ_FIRST(&(QP)->queue)) /* notused */
1842 /* Read the status to decide if the next item on the queue can now run. */
1843 #define QUEUED_READER_CAN_PROCEED(QP) \
1844 (((QP)->q_flags & (NGQ_RMASK & ~OP_PENDING)) == 0)
1845 #define QUEUED_WRITER_CAN_PROCEED(QP) \
1846 (((QP)->q_flags & (NGQ_WMASK & ~OP_PENDING)) == 0)
1848 /* Is there a chance of getting ANY work off the queue? */
1849 #define NEXT_QUEUED_ITEM_CAN_PROCEED(QP) \
1850 ((HEAD_IS_READER(QP)) ? QUEUED_READER_CAN_PROCEED(QP) : \
1851 QUEUED_WRITER_CAN_PROCEED(QP))
1856 #define NGQ2_WORKQ 0x00000001
1859 * Taking into account the current state of the queue and node, possibly take
1860 * the next entry off the queue and return it. Return NULL if there was
1861 * nothing we could return, either because there really was nothing there, or
1862 * because the node was in a state where it cannot yet process the next item
1865 static __inline item_p
1866 ng_dequeue(node_p node, int *rw)
1869 struct ng_queue *ngq = &node->nd_input_queue;
1871 /* This MUST be called with the mutex held. */
1872 KKASSERT(mtx_owned(&ngq->q_mtx));
1874 /* If there is nothing queued, then just return. */
1875 if (!QUEUE_ACTIVE(ngq)) {
1876 CTR4(KTR_NET, "%20s: node [%x] (%p) queue empty; "
1877 "queue flags 0x%lx", __func__,
1878 node->nd_ID, node, ngq->q_flags);
1883 * From here, we can assume there is a head item.
1884 * We need to find out what it is and if it can be dequeued, given
1885 * the current state of the node.
1887 if (HEAD_IS_READER(ngq)) {
1889 long t = ngq->q_flags;
1890 if (t & WRITER_ACTIVE) {
1891 /* There is writer, reader can't proceed. */
1892 CTR4(KTR_NET, "%20s: node [%x] (%p) queued reader "
1893 "can't proceed; queue flags 0x%lx", __func__,
1894 node->nd_ID, node, t);
1897 if (atomic_cmpset_acq_int(&ngq->q_flags, t,
1898 t + READER_INCREMENT))
1902 /* We have got reader lock for the node. */
1904 } else if (atomic_cmpset_acq_int(&ngq->q_flags, OP_PENDING,
1905 OP_PENDING + WRITER_ACTIVE)) {
1906 /* We have got writer lock for the node. */
1909 /* There is somebody other, writer can't proceed. */
1910 CTR4(KTR_NET, "%20s: node [%x] (%p) queued writer "
1911 "can't proceed; queue flags 0x%lx", __func__,
1912 node->nd_ID, node, ngq->q_flags);
1917 * Now we dequeue the request (whatever it may be) and correct the
1918 * pending flags and the next and last pointers.
1920 item = STAILQ_FIRST(&ngq->queue);
1921 STAILQ_REMOVE_HEAD(&ngq->queue, el_next);
1922 if (STAILQ_EMPTY(&ngq->queue))
1923 atomic_clear_int(&ngq->q_flags, OP_PENDING);
1924 CTR6(KTR_NET, "%20s: node [%x] (%p) returning item %p as %s; "
1925 "queue flags 0x%lx", __func__,
1926 node->nd_ID, node, item, *rw ? "WRITER" : "READER" ,
1932 * Queue a packet to be picked up later by someone else.
1933 * If the queue could be run now, add node to the queue handler's worklist.
1935 static __inline void
1936 ng_queue_rw(node_p node, item_p item, int rw)
1938 struct ng_queue *ngq = &node->nd_input_queue;
1940 NGI_SET_WRITER(item);
1942 NGI_SET_READER(item);
1945 /* Set OP_PENDING flag and enqueue the item. */
1946 atomic_set_int(&ngq->q_flags, OP_PENDING);
1947 STAILQ_INSERT_TAIL(&ngq->queue, item, el_next);
1949 CTR5(KTR_NET, "%20s: node [%x] (%p) queued item %p as %s", __func__,
1950 node->nd_ID, node, item, rw ? "WRITER" : "READER" );
1953 * We can take the worklist lock with the node locked
1954 * BUT NOT THE REVERSE!
1956 if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
1957 ng_worklist_add(node);
1958 NG_QUEUE_UNLOCK(ngq);
1961 /* Acquire reader lock on node. If node is busy, queue the packet. */
1962 static __inline item_p
1963 ng_acquire_read(node_p node, item_p item)
1965 KASSERT(node != &ng_deadnode,
1966 ("%s: working on deadnode", __func__));
1968 /* Reader needs node without writer and pending items. */
1970 long t = node->nd_input_queue.q_flags;
1972 break; /* Node is not ready for reader. */
1973 if (atomic_cmpset_acq_int(&node->nd_input_queue.q_flags,
1974 t, t + READER_INCREMENT)) {
1975 /* Successfully grabbed node */
1976 CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
1977 __func__, node->nd_ID, node, item);
1983 /* Queue the request for later. */
1984 ng_queue_rw(node, item, NGQRW_R);
1989 /* Acquire writer lock on node. If node is busy, queue the packet. */
1990 static __inline item_p
1991 ng_acquire_write(node_p node, item_p item)
1993 KASSERT(node != &ng_deadnode,
1994 ("%s: working on deadnode", __func__));
1996 /* Writer needs completely idle node. */
1997 if (atomic_cmpset_acq_int(&node->nd_input_queue.q_flags,
1998 0, WRITER_ACTIVE)) {
1999 /* Successfully grabbed node */
2000 CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
2001 __func__, node->nd_ID, node, item);
2005 /* Queue the request for later. */
2006 ng_queue_rw(node, item, NGQRW_W);
2012 static __inline item_p
2013 ng_upgrade_write(node_p node, item_p item)
2015 struct ng_queue *ngq = &node->nd_input_queue;
2016 KASSERT(node != &ng_deadnode,
2017 ("%s: working on deadnode", __func__));
2019 NGI_SET_WRITER(item);
2024 * There will never be no readers as we are there ourselves.
2025 * Set the WRITER_ACTIVE flags ASAP to block out fast track readers.
2026 * The caller we are running from will call ng_leave_read()
2027 * soon, so we must account for that. We must leave again with the
2028 * READER lock. If we find other readers, then
2029 * queue the request for later. However "later" may be rignt now
2030 * if there are no readers. We don't really care if there are queued
2031 * items as we will bypass them anyhow.
2033 atomic_add_int(&ngq->q_flags, WRITER_ACTIVE - READER_INCREMENT);
2034 if ((ngq->q_flags & (NGQ_WMASK & ~OP_PENDING)) == WRITER_ACTIVE) {
2035 NG_QUEUE_UNLOCK(ngq);
2037 /* It's just us, act on the item. */
2038 /* will NOT drop writer lock when done */
2039 ng_apply_item(node, item, 0);
2042 * Having acted on the item, atomically
2043 * down grade back to READER and finish up
2045 atomic_add_int(&ngq->q_flags,
2046 READER_INCREMENT - WRITER_ACTIVE);
2048 /* Our caller will call ng_leave_read() */
2052 * It's not just us active, so queue us AT THE HEAD.
2053 * "Why?" I hear you ask.
2054 * Put us at the head of the queue as we've already been
2055 * through it once. If there is nothing else waiting,
2056 * set the correct flags.
2058 if (STAILQ_EMPTY(&ngq->queue)) {
2059 /* We've gone from, 0 to 1 item in the queue */
2060 atomic_set_int(&ngq->q_flags, OP_PENDING);
2062 CTR3(KTR_NET, "%20s: node [%x] (%p) set OP_PENDING", __func__,
2065 STAILQ_INSERT_HEAD(&ngq->queue, item, el_next);
2066 CTR4(KTR_NET, "%20s: node [%x] (%p) requeued item %p as WRITER",
2067 __func__, node->nd_ID, node, item );
2069 /* Reverse what we did above. That downgrades us back to reader */
2070 atomic_add_int(&ngq->q_flags, READER_INCREMENT - WRITER_ACTIVE);
2071 if (QUEUE_ACTIVE(ngq) && NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2072 ng_worklist_add(node);
2073 NG_QUEUE_UNLOCK(ngq);
2079 /* Release reader lock. */
2080 static __inline void
2081 ng_leave_read(node_p node)
2083 atomic_subtract_rel_int(&node->nd_input_queue.q_flags, READER_INCREMENT);
2086 /* Release writer lock. */
2087 static __inline void
2088 ng_leave_write(node_p node)
2090 atomic_clear_rel_int(&node->nd_input_queue.q_flags, WRITER_ACTIVE);
2093 /* Purge node queue. Called on node shutdown. */
2095 ng_flush_input_queue(node_p node)
2097 struct ng_queue *ngq = &node->nd_input_queue;
2101 while ((item = STAILQ_FIRST(&ngq->queue)) != NULL) {
2102 STAILQ_REMOVE_HEAD(&ngq->queue, el_next);
2103 if (STAILQ_EMPTY(&ngq->queue))
2104 atomic_clear_int(&ngq->q_flags, OP_PENDING);
2105 NG_QUEUE_UNLOCK(ngq);
2107 /* If the item is supplying a callback, call it with an error */
2108 if (item->apply != NULL) {
2109 if (item->depth == 1)
2110 item->apply->error = ENOENT;
2111 if (refcount_release(&item->apply->refs)) {
2112 (*item->apply->apply)(item->apply->context,
2113 item->apply->error);
2119 NG_QUEUE_UNLOCK(ngq);
2122 /***********************************************************************
2123 * Externally visible method for sending or queueing messages or data.
2124 ***********************************************************************/
2127 * The module code should have filled out the item correctly by this stage:
2129 * reference to destination node.
2130 * Reference to destination rcv hook if relevant.
2131 * apply pointer must be or NULL or reference valid struct ng_apply_info.
2136 * ID of original sender node. (return address)
2142 * The nodes have several routines and macros to help with this task:
2146 ng_snd_item(item_p item, int flags)
2151 struct ng_queue *ngq;
2154 /* We are sending item, so it must be present! */
2155 KASSERT(item != NULL, ("ng_snd_item: item is NULL"));
2157 #ifdef NETGRAPH_DEBUG
2158 _ngi_check(item, __FILE__, __LINE__);
2161 /* Item was sent once more, postpone apply() call. */
2163 refcount_acquire(&item->apply->refs);
2165 node = NGI_NODE(item);
2166 /* Node is never optional. */
2167 KASSERT(node != NULL, ("ng_snd_item: node is NULL"));
2169 hook = NGI_HOOK(item);
2170 /* Valid hook and mbuf are mandatory for data. */
2171 if ((item->el_flags & NGQF_TYPE) == NGQF_DATA) {
2172 KASSERT(hook != NULL, ("ng_snd_item: hook for data is NULL"));
2173 if (NGI_M(item) == NULL)
2175 CHECK_DATA_MBUF(NGI_M(item));
2179 * If the item or the node specifies single threading, force
2180 * writer semantics. Similarly, the node may say one hook always
2181 * produces writers. These are overrides.
2183 if (((item->el_flags & NGQF_RW) == NGQF_WRITER) ||
2184 (node->nd_flags & NGF_FORCE_WRITER) ||
2185 (hook && (hook->hk_flags & HK_FORCE_WRITER))) {
2192 * If sender or receiver requests queued delivery or stack usage
2193 * level is dangerous - enqueue message.
2195 if ((flags & NG_QUEUE) || (hook && (hook->hk_flags & HK_QUEUE))) {
2199 #ifdef GET_STACK_USAGE
2201 * Most of netgraph nodes have small stack consumption and
2202 * for them 25% of free stack space is more than enough.
2203 * Nodes/hooks with higher stack usage should be marked as
2204 * HI_STACK. For them 50% of stack will be guaranteed then.
2205 * XXX: Values 25% and 50% are completely empirical.
2208 GET_STACK_USAGE(st, su);
2210 if ((sl * 4 < st) ||
2211 ((sl * 2 < st) && ((node->nd_flags & NGF_HI_STACK) ||
2212 (hook && (hook->hk_flags & HK_HI_STACK))))) {
2220 /* Put it on the queue for that node*/
2221 ng_queue_rw(node, item, rw);
2222 return ((flags & NG_PROGRESS) ? EINPROGRESS : 0);
2226 * We already decided how we will be queueud or treated.
2227 * Try get the appropriate operating permission.
2230 item = ng_acquire_read(node, item);
2232 item = ng_acquire_write(node, item);
2234 /* Item was queued while trying to get permission. */
2236 return ((flags & NG_PROGRESS) ? EINPROGRESS : 0);
2238 NGI_GET_NODE(item, node); /* zaps stored node */
2241 error = ng_apply_item(node, item, rw); /* drops r/w lock when done */
2243 /* If something is waiting on queue and ready, schedule it. */
2244 ngq = &node->nd_input_queue;
2245 if (QUEUE_ACTIVE(ngq)) {
2247 if (QUEUE_ACTIVE(ngq) && NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2248 ng_worklist_add(node);
2249 NG_QUEUE_UNLOCK(ngq);
2253 * Node may go away as soon as we remove the reference.
2254 * Whatever we do, DO NOT access the node again!
2256 NG_NODE_UNREF(node);
2261 /* If was not sent, apply callback here. */
2262 if (item->apply != NULL) {
2263 if (item->depth == 0 && error != 0)
2264 item->apply->error = error;
2265 if (refcount_release(&item->apply->refs)) {
2266 (*item->apply->apply)(item->apply->context,
2267 item->apply->error);
2276 * We have an item that was possibly queued somewhere.
2277 * It should contain all the information needed
2278 * to run it on the appropriate node/hook.
2279 * If there is apply pointer and we own the last reference, call apply().
2282 ng_apply_item(node_p node, item_p item, int rw)
2285 ng_rcvdata_t *rcvdata;
2286 ng_rcvmsg_t *rcvmsg;
2287 struct ng_apply_info *apply;
2288 int error = 0, depth;
2290 /* Node and item are never optional. */
2291 KASSERT(node != NULL, ("ng_apply_item: node is NULL"));
2292 KASSERT(item != NULL, ("ng_apply_item: item is NULL"));
2294 NGI_GET_HOOK(item, hook); /* clears stored hook */
2295 #ifdef NETGRAPH_DEBUG
2296 _ngi_check(item, __FILE__, __LINE__);
2299 apply = item->apply;
2300 depth = item->depth;
2302 switch (item->el_flags & NGQF_TYPE) {
2305 * Check things are still ok as when we were queued.
2307 KASSERT(hook != NULL, ("ng_apply_item: hook for data is NULL"));
2308 if (NG_HOOK_NOT_VALID(hook) ||
2309 NG_NODE_NOT_VALID(node)) {
2315 * If no receive method, just silently drop it.
2316 * Give preference to the hook over-ride method
2318 if ((!(rcvdata = hook->hk_rcvdata))
2319 && (!(rcvdata = NG_HOOK_NODE(hook)->nd_type->rcvdata))) {
2324 error = (*rcvdata)(hook, item);
2327 if (hook && NG_HOOK_NOT_VALID(hook)) {
2329 * The hook has been zapped then we can't use it.
2330 * Immediately drop its reference.
2331 * The message may not need it.
2333 NG_HOOK_UNREF(hook);
2337 * Similarly, if the node is a zombie there is
2338 * nothing we can do with it, drop everything.
2340 if (NG_NODE_NOT_VALID(node)) {
2347 * Call the appropriate message handler for the object.
2348 * It is up to the message handler to free the message.
2349 * If it's a generic message, handle it generically,
2350 * otherwise call the type's message handler (if it exists).
2351 * XXX (race). Remember that a queued message may
2352 * reference a node or hook that has just been
2353 * invalidated. It will exist as the queue code
2354 * is holding a reference, but..
2356 if ((NGI_MSG(item)->header.typecookie == NGM_GENERIC_COOKIE) &&
2357 ((NGI_MSG(item)->header.flags & NGF_RESP) == 0)) {
2358 error = ng_generic_msg(node, item, hook);
2361 if (((!hook) || (!(rcvmsg = hook->hk_rcvmsg))) &&
2362 (!(rcvmsg = node->nd_type->rcvmsg))) {
2368 error = (*rcvmsg)(node, item, hook);
2373 * We have to implicitly trust the hook,
2374 * as some of these are used for system purposes
2375 * where the hook is invalid. In the case of
2376 * the shutdown message we allow it to hit
2377 * even if the node is invalid.
2379 if ((NG_NODE_NOT_VALID(node))
2380 && (NGI_FN(item) != &ng_rmnode)) {
2386 if ((item->el_flags & NGQF_TYPE) == NGQF_FN) {
2387 (*NGI_FN(item))(node, hook, NGI_ARG1(item),
2390 } else /* it is NGQF_FN2 */
2391 error = (*NGI_FN2(item))(node, item, hook);
2395 * We held references on some of the resources
2396 * that we took from the item. Now that we have
2397 * finished doing everything, drop those references.
2400 NG_HOOK_UNREF(hook);
2403 ng_leave_read(node);
2405 ng_leave_write(node);
2407 /* Apply callback. */
2408 if (apply != NULL) {
2409 if (depth == 1 && error != 0)
2410 apply->error = error;
2411 if (refcount_release(&apply->refs))
2412 (*apply->apply)(apply->context, apply->error);
2418 /***********************************************************************
2419 * Implement the 'generic' control messages
2420 ***********************************************************************/
2422 ng_generic_msg(node_p here, item_p item, hook_p lasthook)
2425 struct ng_mesg *msg;
2426 struct ng_mesg *resp = NULL;
2428 NGI_GET_MSG(item, msg);
2429 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
2434 switch (msg->header.cmd) {
2436 ng_rmnode(here, NULL, NULL, 0);
2440 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
2442 if (msg->header.arglen != sizeof(*mkp)) {
2447 mkp->type[sizeof(mkp->type) - 1] = '\0';
2448 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
2449 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
2450 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
2455 struct ngm_connect *const con =
2456 (struct ngm_connect *) msg->data;
2459 if (msg->header.arglen != sizeof(*con)) {
2464 con->path[sizeof(con->path) - 1] = '\0';
2465 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
2466 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
2467 /* Don't forget we get a reference.. */
2468 error = ng_path2noderef(here, con->path, &node2, NULL);
2471 error = ng_con_nodes(item, here, con->ourhook,
2472 node2, con->peerhook);
2473 NG_NODE_UNREF(node2);
2478 struct ngm_name *const nam = (struct ngm_name *) msg->data;
2480 if (msg->header.arglen != sizeof(*nam)) {
2485 nam->name[sizeof(nam->name) - 1] = '\0';
2486 error = ng_name_node(here, nam->name);
2491 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
2494 if (msg->header.arglen != sizeof(*rmh)) {
2499 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
2500 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
2501 ng_destroy_hook(hook);
2506 struct nodeinfo *ni;
2508 NG_MKRESPONSE(resp, msg, sizeof(*ni), M_WAITOK | M_NULLOK);
2514 /* Fill in node info */
2515 ni = (struct nodeinfo *) resp->data;
2516 if (NG_NODE_HAS_NAME(here))
2517 strcpy(ni->name, NG_NODE_NAME(here));
2518 strcpy(ni->type, here->nd_type->name);
2519 ni->id = ng_node2ID(here);
2520 ni->hooks = here->nd_numhooks;
2525 const int nhooks = here->nd_numhooks;
2526 struct hooklist *hl;
2527 struct nodeinfo *ni;
2530 /* Get response struct */
2531 NG_MKRESPONSE(resp, msg, sizeof(*hl)
2532 + (nhooks * sizeof(struct linkinfo)), M_WAITOK | M_NULLOK);
2537 hl = (struct hooklist *) resp->data;
2540 /* Fill in node info */
2541 if (NG_NODE_HAS_NAME(here))
2542 strcpy(ni->name, NG_NODE_NAME(here));
2543 strcpy(ni->type, here->nd_type->name);
2544 ni->id = ng_node2ID(here);
2546 /* Cycle through the linked list of hooks */
2548 LIST_FOREACH(hook, &here->nd_hooks, hk_hooks) {
2549 struct linkinfo *const link = &hl->link[ni->hooks];
2551 if (ni->hooks >= nhooks) {
2552 log(LOG_ERR, "%s: number of %s changed\n",
2556 if (NG_HOOK_NOT_VALID(hook))
2558 strcpy(link->ourhook, NG_HOOK_NAME(hook));
2559 strcpy(link->peerhook, NG_PEER_HOOK_NAME(hook));
2560 if (NG_PEER_NODE_NAME(hook)[0] != '\0')
2561 strcpy(link->nodeinfo.name,
2562 NG_PEER_NODE_NAME(hook));
2563 strcpy(link->nodeinfo.type,
2564 NG_PEER_NODE(hook)->nd_type->name);
2565 link->nodeinfo.id = ng_node2ID(NG_PEER_NODE(hook));
2566 link->nodeinfo.hooks = NG_PEER_NODE(hook)->nd_numhooks;
2575 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
2576 struct namelist *nl;
2580 mtx_lock(&ng_namehash_mtx);
2581 /* Count number of nodes */
2582 for (i = 0; i < NG_NAME_HASH_SIZE; i++) {
2583 LIST_FOREACH(node, &ng_name_hash[i], nd_nodes) {
2584 if (NG_NODE_IS_VALID(node) &&
2585 (unnamed || NG_NODE_HAS_NAME(node))) {
2590 mtx_unlock(&ng_namehash_mtx);
2592 /* Get response struct */
2593 NG_MKRESPONSE(resp, msg, sizeof(*nl)
2594 + (num * sizeof(struct nodeinfo)), M_WAITOK | M_NULLOK);
2599 nl = (struct namelist *) resp->data;
2601 /* Cycle through the linked list of nodes */
2603 mtx_lock(&ng_namehash_mtx);
2604 for (i = 0; i < NG_NAME_HASH_SIZE; i++) {
2605 LIST_FOREACH(node, &ng_name_hash[i], nd_nodes) {
2606 struct nodeinfo *const np =
2607 &nl->nodeinfo[nl->numnames];
2609 if (NG_NODE_NOT_VALID(node))
2611 if (!unnamed && (! NG_NODE_HAS_NAME(node)))
2613 if (nl->numnames >= num) {
2614 log(LOG_ERR, "%s: number of nodes changed\n",
2618 if (NG_NODE_HAS_NAME(node))
2619 strcpy(np->name, NG_NODE_NAME(node));
2620 strcpy(np->type, node->nd_type->name);
2621 np->id = ng_node2ID(node);
2622 np->hooks = node->nd_numhooks;
2626 mtx_unlock(&ng_namehash_mtx);
2632 struct typelist *tl;
2633 struct ng_type *type;
2636 mtx_lock(&ng_typelist_mtx);
2637 /* Count number of types */
2638 LIST_FOREACH(type, &ng_typelist, types) {
2641 mtx_unlock(&ng_typelist_mtx);
2643 /* Get response struct */
2644 NG_MKRESPONSE(resp, msg, sizeof(*tl)
2645 + (num * sizeof(struct typeinfo)), M_WAITOK | M_NULLOK);
2650 tl = (struct typelist *) resp->data;
2652 /* Cycle through the linked list of types */
2654 mtx_lock(&ng_typelist_mtx);
2655 LIST_FOREACH(type, &ng_typelist, types) {
2656 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
2658 if (tl->numtypes >= num) {
2659 log(LOG_ERR, "%s: number of %s changed\n",
2663 strcpy(tp->type_name, type->name);
2664 tp->numnodes = type->refs - 1; /* don't count list */
2667 mtx_unlock(&ng_typelist_mtx);
2671 case NGM_BINARY2ASCII:
2673 int bufSize = 20 * 1024; /* XXX hard coded constant */
2674 const struct ng_parse_type *argstype;
2675 const struct ng_cmdlist *c;
2676 struct ng_mesg *binary, *ascii;
2678 /* Data area must contain a valid netgraph message */
2679 binary = (struct ng_mesg *)msg->data;
2680 if (msg->header.arglen < sizeof(struct ng_mesg) ||
2681 (msg->header.arglen - sizeof(struct ng_mesg) <
2682 binary->header.arglen)) {
2688 /* Get a response message with lots of room */
2689 NG_MKRESPONSE(resp, msg, sizeof(*ascii) + bufSize, M_WAITOK | M_NULLOK);
2694 ascii = (struct ng_mesg *)resp->data;
2696 /* Copy binary message header to response message payload */
2697 bcopy(binary, ascii, sizeof(*binary));
2699 /* Find command by matching typecookie and command number */
2700 for (c = here->nd_type->cmdlist;
2701 c != NULL && c->name != NULL; c++) {
2702 if (binary->header.typecookie == c->cookie
2703 && binary->header.cmd == c->cmd)
2706 if (c == NULL || c->name == NULL) {
2707 for (c = ng_generic_cmds; c->name != NULL; c++) {
2708 if (binary->header.typecookie == c->cookie
2709 && binary->header.cmd == c->cmd)
2712 if (c->name == NULL) {
2719 /* Convert command name to ASCII */
2720 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
2723 /* Convert command arguments to ASCII */
2724 argstype = (binary->header.flags & NGF_RESP) ?
2725 c->respType : c->mesgType;
2726 if (argstype == NULL) {
2727 *ascii->data = '\0';
2729 if ((error = ng_unparse(argstype,
2730 (u_char *)binary->data,
2731 ascii->data, bufSize)) != 0) {
2737 /* Return the result as struct ng_mesg plus ASCII string */
2738 bufSize = strlen(ascii->data) + 1;
2739 ascii->header.arglen = bufSize;
2740 resp->header.arglen = sizeof(*ascii) + bufSize;
2744 case NGM_ASCII2BINARY:
2746 int bufSize = 2000; /* XXX hard coded constant */
2747 const struct ng_cmdlist *c;
2748 const struct ng_parse_type *argstype;
2749 struct ng_mesg *ascii, *binary;
2752 /* Data area must contain at least a struct ng_mesg + '\0' */
2753 ascii = (struct ng_mesg *)msg->data;
2754 if ((msg->header.arglen < sizeof(*ascii) + 1) ||
2755 (ascii->header.arglen < 1) ||
2756 (msg->header.arglen < sizeof(*ascii) +
2757 ascii->header.arglen)) {
2762 ascii->data[ascii->header.arglen - 1] = '\0';
2764 /* Get a response message with lots of room */
2765 NG_MKRESPONSE(resp, msg, sizeof(*binary) + bufSize, M_WAITOK | M_NULLOK);
2770 binary = (struct ng_mesg *)resp->data;
2772 /* Copy ASCII message header to response message payload */
2773 bcopy(ascii, binary, sizeof(*ascii));
2775 /* Find command by matching ASCII command string */
2776 for (c = here->nd_type->cmdlist;
2777 c != NULL && c->name != NULL; c++) {
2778 if (strcmp(ascii->header.cmdstr, c->name) == 0)
2781 if (c == NULL || c->name == NULL) {
2782 for (c = ng_generic_cmds; c->name != NULL; c++) {
2783 if (strcmp(ascii->header.cmdstr, c->name) == 0)
2786 if (c->name == NULL) {
2793 /* Convert command name to binary */
2794 binary->header.cmd = c->cmd;
2795 binary->header.typecookie = c->cookie;
2797 /* Convert command arguments to binary */
2798 argstype = (binary->header.flags & NGF_RESP) ?
2799 c->respType : c->mesgType;
2800 if (argstype == NULL) {
2803 if ((error = ng_parse(argstype, ascii->data,
2804 &off, (u_char *)binary->data, &bufSize)) != 0) {
2810 /* Return the result */
2811 binary->header.arglen = bufSize;
2812 resp->header.arglen = sizeof(*binary) + bufSize;
2816 case NGM_TEXT_CONFIG:
2817 case NGM_TEXT_STATUS:
2819 * This one is tricky as it passes the command down to the
2820 * actual node, even though it is a generic type command.
2821 * This means we must assume that the item/msg is already freed
2822 * when control passes back to us.
2824 if (here->nd_type->rcvmsg != NULL) {
2825 NGI_MSG(item) = msg; /* put it back as we found it */
2826 return((*here->nd_type->rcvmsg)(here, item, lasthook));
2828 /* Fall through if rcvmsg not supported */
2834 * Sometimes a generic message may be statically allocated
2835 * to avoid problems with allocating when in tight memeory situations.
2836 * Don't free it if it is so.
2837 * I break them appart here, because erros may cause a free if the item
2838 * in which case we'd be doing it twice.
2839 * they are kept together above, to simplify freeing.
2842 NG_RESPOND_MSG(error, here, item, resp);
2848 /************************************************************************
2849 Queue element get/free routines
2850 ************************************************************************/
2852 uma_zone_t ng_qzone;
2853 uma_zone_t ng_qdzone;
2854 static int maxalloc = 4096;/* limit the damage of a leak */
2855 static int maxdata = 512; /* limit the damage of a DoS */
2857 TUNABLE_INT("net.graph.maxalloc", &maxalloc);
2858 SYSCTL_INT(_net_graph, OID_AUTO, maxalloc, CTLFLAG_RDTUN, &maxalloc,
2859 0, "Maximum number of non-data queue items to allocate");
2860 TUNABLE_INT("net.graph.maxdata", &maxdata);
2861 SYSCTL_INT(_net_graph, OID_AUTO, maxdata, CTLFLAG_RDTUN, &maxdata,
2862 0, "Maximum number of data queue items to allocate");
2864 #ifdef NETGRAPH_DEBUG
2865 static TAILQ_HEAD(, ng_item) ng_itemlist = TAILQ_HEAD_INITIALIZER(ng_itemlist);
2866 static int allocated; /* number of items malloc'd */
2870 * Get a queue entry.
2871 * This is usually called when a packet first enters netgraph.
2872 * By definition, this is usually from an interrupt, or from a user.
2873 * Users are not so important, but try be quick for the times that it's
2876 static __inline item_p
2877 ng_alloc_item(int type, int flags)
2881 KASSERT(((type & ~NGQF_TYPE) == 0),
2882 ("%s: incorrect item type: %d", __func__, type));
2884 item = uma_zalloc((type == NGQF_DATA)?ng_qdzone:ng_qzone,
2885 (flags & NG_WAITOK) ? M_WAITOK : M_NOWAIT );
2888 item->el_flags = type;
2889 #ifdef NETGRAPH_DEBUG
2891 TAILQ_INSERT_TAIL(&ng_itemlist, item, all);
2893 mtx_unlock(&ngq_mtx);
2901 * Release a queue entry
2904 ng_free_item(item_p item)
2907 * The item may hold resources on it's own. We need to free
2908 * these before we can free the item. What they are depends upon
2909 * what kind of item it is. it is important that nodes zero
2910 * out pointers to resources that they remove from the item
2911 * or we release them again here.
2913 switch (item->el_flags & NGQF_TYPE) {
2915 /* If we have an mbuf still attached.. */
2916 NG_FREE_M(_NGI_M(item));
2919 _NGI_RETADDR(item) = 0;
2920 NG_FREE_MSG(_NGI_MSG(item));
2924 /* nothing to free really, */
2925 _NGI_FN(item) = NULL;
2926 _NGI_ARG1(item) = NULL;
2927 _NGI_ARG2(item) = 0;
2930 /* If we still have a node or hook referenced... */
2931 _NGI_CLR_NODE(item);
2932 _NGI_CLR_HOOK(item);
2934 #ifdef NETGRAPH_DEBUG
2936 TAILQ_REMOVE(&ng_itemlist, item, all);
2938 mtx_unlock(&ngq_mtx);
2940 uma_zfree(((item->el_flags & NGQF_TYPE) == NGQF_DATA)?
2941 ng_qdzone:ng_qzone, item);
2945 * Change type of the queue entry.
2946 * Possibly reallocates it from another UMA zone.
2948 static __inline item_p
2949 ng_realloc_item(item_p pitem, int type, int flags)
2954 KASSERT((pitem != NULL), ("%s: can't reallocate NULL", __func__));
2955 KASSERT(((type & ~NGQF_TYPE) == 0),
2956 ("%s: incorrect item type: %d", __func__, type));
2958 from = ((pitem->el_flags & NGQF_TYPE) == NGQF_DATA);
2959 to = (type == NGQF_DATA);
2961 /* If reallocation is required do it and copy item. */
2962 if ((item = ng_alloc_item(type, flags)) == NULL) {
2963 ng_free_item(pitem);
2967 ng_free_item(pitem);
2970 item->el_flags = (item->el_flags & ~NGQF_TYPE) | type;
2975 /************************************************************************
2977 ************************************************************************/
2980 * Handle the loading/unloading of a netgraph node type module
2983 ng_mod_event(module_t mod, int event, void *data)
2985 struct ng_type *const type = data;
2991 /* Register new netgraph node type */
2993 if ((error = ng_newtype(type)) != 0) {
2998 /* Call type specific code */
2999 if (type->mod_event != NULL)
3000 if ((error = (*type->mod_event)(mod, event, data))) {
3001 mtx_lock(&ng_typelist_mtx);
3002 type->refs--; /* undo it */
3003 LIST_REMOVE(type, types);
3004 mtx_unlock(&ng_typelist_mtx);
3011 if (type->refs > 1) { /* make sure no nodes exist! */
3014 if (type->refs == 0) {
3015 /* failed load, nothing to undo */
3019 if (type->mod_event != NULL) { /* check with type */
3020 error = (*type->mod_event)(mod, event, data);
3021 if (error != 0) { /* type refuses.. */
3026 mtx_lock(&ng_typelist_mtx);
3027 LIST_REMOVE(type, types);
3028 mtx_unlock(&ng_typelist_mtx);
3034 if (type->mod_event != NULL)
3035 error = (*type->mod_event)(mod, event, data);
3037 error = EOPNOTSUPP; /* XXX ? */
3044 * Handle loading and unloading for this code.
3045 * The only thing we need to link into is the NETISR strucure.
3048 ngb_mod_event(module_t mod, int event, void *data)
3054 /* Initialize everything. */
3055 NG_WORKLIST_LOCK_INIT();
3056 mtx_init(&ng_typelist_mtx);
3057 mtx_init(&ng_idhash_mtx);
3058 mtx_init(&ng_namehash_mtx);
3059 mtx_init(&ng_topo_mtx);
3060 #ifdef NETGRAPH_DEBUG
3061 mtx_init(&ng_nodelist_mtx);
3064 ng_qzone = uma_zcreate("NetGraph items", sizeof(struct ng_item),
3065 NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
3066 uma_zone_set_max(ng_qzone, maxalloc);
3067 ng_qdzone = uma_zcreate("NetGraph data items", sizeof(struct ng_item),
3068 NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
3069 uma_zone_set_max(ng_qdzone, maxdata);
3072 /* You can't unload it because an interface may be using it. */
3082 static moduledata_t netgraph_mod = {
3087 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_NETGRAPH, SI_ORDER_MIDDLE);
3088 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
3089 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
3090 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
3092 #ifdef NETGRAPH_DEBUG
3094 dumphook (hook_p hook, char *file, int line)
3096 printf("hook: name %s, %d refs, Last touched:\n",
3097 _NG_HOOK_NAME(hook), hook->hk_refs);
3098 printf(" Last active @ %s, line %d\n",
3099 hook->lastfile, hook->lastline);
3101 printf(" problem discovered at file %s, line %d\n", file, line);
3106 dumpnode(node_p node, char *file, int line)
3108 printf("node: ID [%x]: type '%s', %d hooks, flags 0x%x, %d refs, %s:\n",
3109 _NG_NODE_ID(node), node->nd_type->name,
3110 node->nd_numhooks, node->nd_flags,
3111 node->nd_refs, node->nd_name);
3112 printf(" Last active @ %s, line %d\n",
3113 node->lastfile, node->lastline);
3115 printf(" problem discovered at file %s, line %d\n", file, line);
3120 dumpitem(item_p item, char *file, int line)
3122 printf(" ACTIVE item, last used at %s, line %d",
3123 item->lastfile, item->lastline);
3124 switch(item->el_flags & NGQF_TYPE) {
3126 printf(" - [data]\n");
3129 printf(" - retaddr[%d]:\n", _NGI_RETADDR(item));
3132 printf(" - fn@%p (%p, %p, %p, %d (%x))\n",
3136 item->body.fn.fn_arg1,
3137 item->body.fn.fn_arg2,
3138 item->body.fn.fn_arg2);
3141 printf(" - fn2@%p (%p, %p, %p, %d (%x))\n",
3145 item->body.fn.fn_arg1,
3146 item->body.fn.fn_arg2,
3147 item->body.fn.fn_arg2);
3151 printf(" problem discovered at file %s, line %d\n", file, line);
3152 if (_NGI_NODE(item)) {
3153 printf("node %p ([%x])\n",
3154 _NGI_NODE(item), ng_node2ID(_NGI_NODE(item)));
3164 TAILQ_FOREACH(item, &ng_itemlist, all) {
3165 printf("[%d] ", i++);
3166 dumpitem(item, NULL, 0);
3175 mtx_lock(&ng_nodelist_mtx);
3176 SLIST_FOREACH(node, &ng_allnodes, nd_all) {
3177 printf("[%d] ", i++);
3178 dumpnode(node, NULL, 0);
3180 mtx_unlock(&ng_nodelist_mtx);
3188 mtx_lock(&ng_nodelist_mtx);
3189 SLIST_FOREACH(hook, &ng_allhooks, hk_all) {
3190 printf("[%d] ", i++);
3191 dumphook(hook, NULL, 0);
3193 mtx_unlock(&ng_nodelist_mtx);
3197 sysctl_debug_ng_dump_items(SYSCTL_HANDLER_ARGS)
3203 error = sysctl_handle_int(oidp, &val, 0, req);
3204 if (error != 0 || req->newptr == NULL)
3214 SYSCTL_PROC(_debug, OID_AUTO, ng_dump_items, CTLTYPE_INT | CTLFLAG_RW,
3215 0, sizeof(int), sysctl_debug_ng_dump_items, "I", "Number of allocated items");
3216 #endif /* NETGRAPH_DEBUG */
3219 /***********************************************************************
3221 **********************************************************************/
3222 /* NETGRAPH taskqueue routine
3224 * Pick a node off the list of nodes with work,
3225 * try get an item to process off it.
3226 * If there are no more, remove the node from the list.
3228 * This routine used to be a netisr but because no actual packets are
3229 * really sent to it, it has been converted to a taskqueue.
3232 ngtask(void *context, int pending)
3237 /* Get node from the worklist. */
3239 node = STAILQ_FIRST(&ng_worklist);
3241 NG_WORKLIST_UNLOCK();
3244 STAILQ_REMOVE_HEAD(&ng_worklist, nd_input_queue.q_work);
3245 NG_WORKLIST_UNLOCK();
3246 CTR3(KTR_NET, "%20s: node [%x] (%p) taken off worklist",
3247 __func__, node->nd_ID, node);
3249 * We have the node. We also take over the reference
3250 * that the list had on it.
3251 * Now process as much as you can, until it won't
3252 * let you have another item off the queue.
3253 * All this time, keep the reference
3254 * that lets us be sure that the node still exists.
3255 * Let the reference go at the last minute.
3261 NG_QUEUE_LOCK(&node->nd_input_queue);
3262 item = ng_dequeue(node, &rw);
3264 node->nd_input_queue.q_flags2 &= ~NGQ2_WORKQ;
3265 NG_QUEUE_UNLOCK(&node->nd_input_queue);
3266 break; /* go look for another node */
3268 NG_QUEUE_UNLOCK(&node->nd_input_queue);
3269 NGI_GET_NODE(item, node); /* zaps stored node */
3270 ng_apply_item(node, item, rw);
3271 NG_NODE_UNREF(node);
3274 NG_NODE_UNREF(node);
3280 * It's posible that a debugging NG_NODE_REF may need
3281 * to be outside the mutex zone
3284 ng_worklist_add(node_p node)
3287 KKASSERT(mtx_owned(&node->nd_input_queue.q_mtx));
3289 if ((node->nd_input_queue.q_flags2 & NGQ2_WORKQ) == 0) {
3290 static struct task ng_task;
3293 * If we are not already on the work queue,
3296 node->nd_input_queue.q_flags2 |= NGQ2_WORKQ;
3297 NG_NODE_REF(node); /* XXX fafe in mutex? */
3299 STAILQ_INSERT_TAIL(&ng_worklist, node, nd_input_queue.q_work);
3300 NG_WORKLIST_UNLOCK();
3301 TASK_INIT(&ng_task, 0, ngtask, NULL);
3302 taskqueue_enqueue(taskqueue_swi, &ng_task);
3303 CTR3(KTR_NET, "%20s: node [%x] (%p) put on worklist", __func__,
3306 CTR3(KTR_NET, "%20s: node [%x] (%p) already on worklist",
3307 __func__, node->nd_ID, node);
3312 /***********************************************************************
3313 * Externally useable functions to set up a queue item ready for sending
3314 ***********************************************************************/
3316 #ifdef NETGRAPH_DEBUG
3317 #define ITEM_DEBUG_CHECKS \
3319 if (NGI_NODE(item) ) { \
3320 printf("item already has node"); \
3321 kdb_enter(KDB_WHY_NETGRAPH, "has node"); \
3322 NGI_CLR_NODE(item); \
3324 if (NGI_HOOK(item) ) { \
3325 printf("item already has hook"); \
3326 kdb_enter(KDB_WHY_NETGRAPH, "has hook"); \
3327 NGI_CLR_HOOK(item); \
3331 #define ITEM_DEBUG_CHECKS
3335 * Put mbuf into the item.
3336 * Hook and node references will be removed when the item is dequeued.
3338 * (XXX) Unsafe because no reference held by peer on remote node.
3339 * remote node might go away in this timescale.
3340 * We know the hooks can't go away because that would require getting
3341 * a writer item on both nodes and we must have at least a reader
3342 * here to be able to do this.
3343 * Note that the hook loaded is the REMOTE hook.
3345 * This is possibly in the critical path for new data.
3348 ng_package_data(struct mbuf *m, int flags)
3352 if ((item = ng_alloc_item(NGQF_DATA, flags)) == NULL) {
3357 item->el_flags |= NGQF_READER;
3363 * Allocate a queue item and put items into it..
3364 * Evaluate the address as this will be needed to queue it and
3365 * to work out what some of the fields should be.
3366 * Hook and node references will be removed when the item is dequeued.
3370 ng_package_msg(struct ng_mesg *msg, int flags)
3374 if ((item = ng_alloc_item(NGQF_MESG, flags)) == NULL) {
3379 /* Messages items count as writers unless explicitly exempted. */
3380 if (msg->header.cmd & NGM_READONLY)
3381 item->el_flags |= NGQF_READER;
3383 item->el_flags |= NGQF_WRITER;
3385 * Set the current lasthook into the queue item
3387 NGI_MSG(item) = msg;
3388 NGI_RETADDR(item) = 0;
3394 #define SET_RETADDR(item, here, retaddr) \
3395 do { /* Data or fn items don't have retaddrs */ \
3396 if ((item->el_flags & NGQF_TYPE) == NGQF_MESG) { \
3398 NGI_RETADDR(item) = retaddr; \
3401 * The old return address should be ok. \
3402 * If there isn't one, use the address \
3405 if (NGI_RETADDR(item) == 0) { \
3407 = ng_node2ID(here); \
3414 ng_address_hook(node_p here, item_p item, hook_p hook, ng_ID_t retaddr)
3420 * Quick sanity check..
3421 * Since a hook holds a reference on it's node, once we know
3422 * that the peer is still connected (even if invalid,) we know
3423 * that the peer node is present, though maybe invalid.
3425 if ((hook == NULL) ||
3426 NG_HOOK_NOT_VALID(hook) ||
3427 NG_HOOK_NOT_VALID(peer = NG_HOOK_PEER(hook)) ||
3428 NG_NODE_NOT_VALID(peernode = NG_PEER_NODE(hook))) {
3435 * Transfer our interest to the other (peer) end.
3438 NG_NODE_REF(peernode);
3439 NGI_SET_HOOK(item, peer);
3440 NGI_SET_NODE(item, peernode);
3441 SET_RETADDR(item, here, retaddr);
3446 ng_address_path(node_p here, item_p item, char *address, ng_ID_t retaddr)
3454 * Note that ng_path2noderef increments the reference count
3455 * on the node for us if it finds one. So we don't have to.
3457 error = ng_path2noderef(here, address, &dest, &hook);
3462 NGI_SET_NODE(item, dest);
3464 NG_HOOK_REF(hook); /* don't let it go while on the queue */
3465 NGI_SET_HOOK(item, hook);
3467 SET_RETADDR(item, here, retaddr);
3472 ng_address_ID(node_p here, item_p item, ng_ID_t ID, ng_ID_t retaddr)
3478 * Find the target node.
3480 dest = ng_ID2noderef(ID); /* GETS REFERENCE! */
3486 /* Fill out the contents */
3487 NGI_SET_NODE(item, dest);
3489 SET_RETADDR(item, here, retaddr);
3494 * special case to send a message to self (e.g. destroy node)
3495 * Possibly indicate an arrival hook too.
3496 * Useful for removing that hook :-)
3499 ng_package_msg_self(node_p here, hook_p hook, struct ng_mesg *msg)
3504 * Find the target node.
3505 * If there is a HOOK argument, then use that in preference
3508 if ((item = ng_alloc_item(NGQF_MESG, NG_NOFLAGS)) == NULL) {
3513 /* Fill out the contents */
3514 item->el_flags |= NGQF_WRITER;
3516 NGI_SET_NODE(item, here);
3519 NGI_SET_HOOK(item, hook);
3521 NGI_MSG(item) = msg;
3522 NGI_RETADDR(item) = ng_node2ID(here);
3527 * Send ng_item_fn function call to the specified node.
3531 ng_send_fn(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2)
3534 return ng_send_fn1(node, hook, fn, arg1, arg2, NG_NOFLAGS);
3538 ng_send_fn1(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2,
3543 if ((item = ng_alloc_item(NGQF_FN, flags)) == NULL) {
3546 item->el_flags |= NGQF_WRITER;
3547 NG_NODE_REF(node); /* and one for the item */
3548 NGI_SET_NODE(item, node);
3551 NGI_SET_HOOK(item, hook);
3554 NGI_ARG1(item) = arg1;
3555 NGI_ARG2(item) = arg2;
3556 return(ng_snd_item(item, flags));
3560 * Send ng_item_fn2 function call to the specified node.
3562 * If an optional pitem parameter is supplied, its apply
3563 * callback will be copied to the new item. If also NG_REUSE_ITEM
3564 * flag is set, no new item will be allocated, but pitem will
3568 ng_send_fn2(node_p node, hook_p hook, item_p pitem, ng_item_fn2 *fn, void *arg1,
3569 int arg2, int flags)
3573 KASSERT((pitem != NULL || (flags & NG_REUSE_ITEM) == 0),
3574 ("%s: NG_REUSE_ITEM but no pitem", __func__));
3577 * Allocate a new item if no supplied or
3578 * if we can't use supplied one.
3580 if (pitem == NULL || (flags & NG_REUSE_ITEM) == 0) {
3581 if ((item = ng_alloc_item(NGQF_FN2, flags)) == NULL)
3584 item->apply = pitem->apply;
3586 if ((item = ng_realloc_item(pitem, NGQF_FN2, flags)) == NULL)
3590 item->el_flags = (item->el_flags & ~NGQF_RW) | NGQF_WRITER;
3591 NG_NODE_REF(node); /* and one for the item */
3592 NGI_SET_NODE(item, node);
3595 NGI_SET_HOOK(item, hook);
3598 NGI_ARG1(item) = arg1;
3599 NGI_ARG2(item) = arg2;
3600 return(ng_snd_item(item, flags));
3604 * Official timeout routines for Netgraph nodes.
3607 ng_callout_trampoline(void *arg)
3611 ng_snd_item(item, 0);
3616 ng_callout(struct callout *c, node_p node, hook_p hook, int ticks,
3617 ng_item_fn *fn, void * arg1, int arg2)
3621 if ((item = ng_alloc_item(NGQF_FN, NG_NOFLAGS)) == NULL)
3624 item->el_flags |= NGQF_WRITER;
3625 NG_NODE_REF(node); /* and one for the item */
3626 NGI_SET_NODE(item, node);
3629 NGI_SET_HOOK(item, hook);
3632 NGI_ARG1(item) = arg1;
3633 NGI_ARG2(item) = arg2;
3635 callout_reset(c, ticks, &ng_callout_trampoline, item);
3639 /* A special modified version of untimeout() */
3641 ng_uncallout(struct callout *c, node_p node)
3646 KASSERT(c != NULL, ("ng_uncallout: NULL callout"));
3647 KASSERT(node != NULL, ("ng_uncallout: NULL node"));
3649 rval = callout_stop(c);
3651 /* Do an extra check */
3652 if ((rval > 0) && (c->c_func == &ng_callout_trampoline) &&
3653 (NGI_NODE(item) == node)) {
3655 * We successfully removed it from the queue before it ran
3656 * So now we need to unreference everything that was
3657 * given extra references. (NG_FREE_ITEM does this).
3667 * Set the address, if none given, give the node here.
3670 ng_replace_retaddr(node_p here, item_p item, ng_ID_t retaddr)
3673 NGI_RETADDR(item) = retaddr;
3676 * The old return address should be ok.
3677 * If there isn't one, use the address here.
3679 NGI_RETADDR(item) = ng_node2ID(here);
3684 bzero_ctor(void *obj, void *private, int ocflags)
3686 struct ng_item *i = obj;
3688 bzero(i, sizeof(struct ng_item));
3694 /* just test all the macros */
3696 ng_macro_test(item_p item);
3698 ng_macro_test(item_p item)
3703 struct ng_mesg *msg;
3708 NGI_GET_MSG(item, msg);
3709 retaddr = NGI_RETADDR(item);
3710 NG_SEND_DATA(error, hook, m, NULL);
3711 NG_SEND_DATA_ONLY(error, hook, m);
3712 NG_FWD_NEW_DATA(error, item, hook, m);
3713 NG_FWD_ITEM_HOOK(error, item, hook);
3714 NG_SEND_MSG_HOOK(error, node, msg, hook, retaddr);
3715 NG_SEND_MSG_ID(error, node, msg, retaddr, retaddr);
3716 NG_SEND_MSG_PATH(error, node, msg, ".:", retaddr);
3717 NG_FWD_MSG_HOOK(error, node, item, hook, retaddr);
3719 #endif /* TESTING */