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/kernel.h>
55 #include <sys/limits.h>
56 #include <sys/malloc.h>
58 #include <sys/msgport2.h>
59 #include <sys/mutex2.h>
60 #include <sys/queue.h>
61 #include <sys/sysctl.h>
62 #include <sys/syslog.h>
63 #include <sys/refcount.h>
65 #include <sys/taskqueue.h>
66 #include <machine/cpu.h>
68 #include <net/netisr.h>
70 #include <netgraph7/ng_message.h>
71 #include <netgraph7/netgraph.h>
72 #include <netgraph7/ng_parse.h>
74 MODULE_VERSION(netgraph, NG_ABI_VERSION);
76 /* Mutex to protect topology events. */
77 static struct mtx ng_topo_mtx;
80 * DEAD versions of the structures.
81 * In order to avoid races, it is sometimes neccesary to point
82 * at SOMETHING even though theoretically, the current entity is
83 * INVALID. Use these to avoid these races.
85 struct ng_type ng_deadtype = {
89 NULL, /* constructor */
96 NULL, /* disconnect */
100 struct ng_node ng_deadnode = {
107 LIST_HEAD_INITIALIZER(ng_deadnode.hooks),
108 {}, /* all_nodes list entry */
109 {}, /* id hashtable list entry */
112 {}, /* should never use! (should hang) */
113 {}, /* workqueue entry */
114 STAILQ_HEAD_INITIALIZER(ng_deadnode.nd_input_queue.queue),
119 struct ng_hook ng_deadhook = {
122 HK_INVALID | HK_DEAD,
123 0, /* undefined data link type */
124 &ng_deadhook, /* Peer is self */
125 &ng_deadnode, /* attached to deadnode */
127 NULL, /* override rcvmsg() */
128 NULL, /* override rcvdata() */
129 1, /* refs always >= 1 */
133 * END DEAD STRUCTURES
135 /* List nodes with unallocated work */
136 static STAILQ_HEAD(, ng_node) ng_worklist = STAILQ_HEAD_INITIALIZER(ng_worklist);
137 static struct mtx ng_worklist_mtx; /* MUST LOCK NODE FIRST */
139 /* List of installed types */
140 static LIST_HEAD(, ng_type) ng_typelist;
141 static struct mtx ng_typelist_mtx;
143 /* Hash related definitions */
144 /* XXX Don't need to initialise them because it's a LIST */
145 #define NG_ID_HASH_SIZE 128 /* most systems wont need even this many */
146 static LIST_HEAD(, ng_node) ng_ID_hash[NG_ID_HASH_SIZE];
147 static struct mtx ng_idhash_mtx;
148 /* Method to find a node.. used twice so do it here */
149 #define NG_IDHASH_FN(ID) ((ID) % (NG_ID_HASH_SIZE))
150 #define NG_IDHASH_FIND(ID, node) \
152 KKASSERT(mtx_owned(&ng_idhash_mtx)); \
153 LIST_FOREACH(node, &ng_ID_hash[NG_IDHASH_FN(ID)], \
155 if (NG_NODE_IS_VALID(node) \
156 && (NG_NODE_ID(node) == ID)) { \
162 #define NG_NAME_HASH_SIZE 128 /* most systems wont need even this many */
163 static LIST_HEAD(, ng_node) ng_name_hash[NG_NAME_HASH_SIZE];
164 static struct mtx ng_namehash_mtx;
165 #define NG_NAMEHASH(NAME, HASH) \
169 for (c = (const u_char*)(NAME); *c; c++)\
171 (HASH) = h % (NG_NAME_HASH_SIZE); \
175 /* Internal functions */
176 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
177 static int ng_generic_msg(node_p here, item_p item, hook_p lasthook);
178 static ng_ID_t ng_decodeidname(const char *name);
179 static int ngb_mod_event(module_t mod, int event, void *data);
180 static void ng_worklist_add(node_p node);
181 static void ngtask(void *, int);
182 static int ng_apply_item(node_p node, item_p item, int rw);
183 static void ng_flush_input_queue(node_p node);
184 static node_p ng_ID2noderef(ng_ID_t ID);
185 static int ng_con_nodes(item_p item, node_p node, const char *name,
186 node_p node2, const char *name2);
187 static int ng_con_part2(node_p node, item_p item, hook_p hook);
188 static int ng_con_part3(node_p node, item_p item, hook_p hook);
189 static int ng_mkpeer(node_p node, const char *name,
190 const char *name2, char *type);
191 static boolean_t bzero_ctor(void *obj, void *private, int ocflags);
193 /* Imported, these used to be externally visible, some may go back. */
194 void ng_destroy_hook(hook_p hook);
195 node_p ng_name2noderef(node_p node, const char *name);
196 int ng_path2noderef(node_p here, const char *path,
197 node_p *dest, hook_p *lasthook);
198 int ng_make_node(const char *type, node_p *nodepp);
199 int ng_path_parse(char *addr, char **node, char **path, char **hook);
200 void ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3);
201 void ng_unname(node_p node);
204 /* Our own netgraph malloc type */
205 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
206 MALLOC_DEFINE(M_NETGRAPH_HOOK, "netgraph_hook", "netgraph hook structures");
207 MALLOC_DEFINE(M_NETGRAPH_NODE, "netgraph_node", "netgraph node structures");
208 MALLOC_DEFINE(M_NETGRAPH_ITEM, "netgraph_item", "netgraph item structures");
209 MALLOC_DEFINE(M_NETGRAPH_MSG, "netgraph_msg", "netgraph name storage");
211 /* Should not be visible outside this file */
213 #define NG_QUEUE_LOCK_INIT(n) \
214 mtx_init(&(n)->q_mtx)
215 #define NG_QUEUE_LOCK(n) \
216 mtx_lock(&(n)->q_mtx)
217 #define NG_QUEUE_UNLOCK(n) \
218 mtx_unlock(&(n)->q_mtx)
219 #define NG_WORKLIST_LOCK_INIT() \
220 mtx_init(&ng_worklist_mtx)
221 #define NG_WORKLIST_LOCK() \
222 mtx_lock(&ng_worklist_mtx)
223 #define NG_WORKLIST_UNLOCK() \
224 mtx_unlock(&ng_worklist_mtx)
226 #define NG_FREE_HOOK(hook) do { kfree((hook), M_NETGRAPH_HOOK); } while (0)
227 #define NG_FREE_NODE(node) do { kfree((node), M_NETGRAPH_NODE); } while (0)
229 /* Set this to kdb_enter("X") to catch all errors as they occur */
234 static ng_ID_t nextID = 1;
237 #define CHECK_DATA_MBUF(m) do { \
242 for (total = 0, n = (m); n != NULL; n = n->m_next) { \
244 if (n->m_nextpkt != NULL) \
245 panic("%s: m_nextpkt", __func__); \
248 if ((m)->m_pkthdr.len != total) { \
249 panic("%s: %d != %d", \
250 __func__, (m)->m_pkthdr.len, total); \
254 #define CHECK_DATA_MBUF(m)
257 #define ERROUT(x) do { error = (x); goto done; } while (0)
259 /************************************************************************
260 Parse type definitions for generic messages
261 ************************************************************************/
263 /* Handy structure parse type defining macro */
264 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
265 static const struct ng_parse_struct_field \
266 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
267 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
268 &ng_parse_struct_type, \
269 &ng_ ## lo ## _type_fields \
272 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
273 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
274 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
275 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
276 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
277 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
278 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
280 /* Get length of an array when the length is stored as a 32 bit
281 value immediately preceding the array -- as with struct namelist
282 and struct typelist. */
284 ng_generic_list_getLength(const struct ng_parse_type *type,
285 const u_char *start, const u_char *buf)
287 return *((const u_int32_t *)(buf - 4));
290 /* Get length of the array of struct linkinfo inside a struct hooklist */
292 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
293 const u_char *start, const u_char *buf)
295 const struct hooklist *hl = (const struct hooklist *)start;
297 return hl->nodeinfo.hooks;
300 /* Array type for a variable length array of struct namelist */
301 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
302 &ng_generic_nodeinfo_type,
303 &ng_generic_list_getLength
305 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
306 &ng_parse_array_type,
307 &ng_nodeinfoarray_type_info
310 /* Array type for a variable length array of struct typelist */
311 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
312 &ng_generic_typeinfo_type,
313 &ng_generic_list_getLength
315 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
316 &ng_parse_array_type,
317 &ng_typeinfoarray_type_info
320 /* Array type for array of struct linkinfo in struct hooklist */
321 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
322 &ng_generic_linkinfo_type,
323 &ng_generic_linkinfo_getLength
325 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
326 &ng_parse_array_type,
327 &ng_generic_linkinfo_array_type_info
330 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
331 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
332 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
333 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
334 (&ng_generic_nodeinfoarray_type));
336 /* List of commands and how to convert arguments to/from ASCII */
337 static const struct ng_cmdlist ng_generic_cmds[] = {
349 &ng_generic_mkpeer_type,
356 &ng_generic_connect_type,
363 &ng_generic_name_type,
370 &ng_generic_rmhook_type,
378 &ng_generic_nodeinfo_type
385 &ng_generic_hooklist_type
392 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
399 &ng_generic_listnodes_type
406 &ng_generic_typeinfo_type
413 &ng_parse_string_type
420 &ng_parse_string_type
426 &ng_parse_ng_mesg_type,
427 &ng_parse_ng_mesg_type
433 &ng_parse_ng_mesg_type,
434 &ng_parse_ng_mesg_type
439 /************************************************************************
441 ************************************************************************/
444 * Instantiate a node of the requested type
447 ng_make_node(const char *typename, node_p *nodepp)
449 struct ng_type *type;
452 /* Check that the type makes sense */
453 if (typename == NULL) {
458 /* Locate the node type. If we fail we return. Do not try to load
461 if ((type = ng_findtype(typename)) == NULL)
465 * If we have a constructor, then make the node and
466 * call the constructor to do type specific initialisation.
468 if (type->constructor != NULL) {
469 if ((error = ng_make_node_common(type, nodepp)) == 0) {
470 if ((error = ((*type->constructor)(*nodepp)) != 0)) {
471 NG_NODE_UNREF(*nodepp);
476 * Node has no constructor. We cannot ask for one
477 * to be made. It must be brought into existence by
478 * some external agency. The external agency should
479 * call ng_make_node_common() directly to get the
480 * netgraph part initialised.
489 * Generic node creation. Called by node initialisation for externally
490 * instantiated nodes (e.g. hardware, sockets, etc ).
491 * The returned node has a reference count of 1.
494 ng_make_node_common(struct ng_type *type, node_p *nodepp)
498 /* Require the node type to have been already installed */
499 if (ng_findtype(type->name) == NULL) {
504 /* Make a node and try attach it to the type */
505 node = kmalloc(sizeof(*node), M_NETGRAPH_NODE, M_WAITOK | M_ZERO);
506 node->nd_type = type;
507 NG_NODE_REF(node); /* note reference */
510 NG_QUEUE_LOCK_INIT(&node->nd_input_queue);
511 STAILQ_INIT(&node->nd_input_queue.queue);
512 node->nd_input_queue.q_flags = 0;
514 /* Initialize hook list for new node */
515 LIST_INIT(&node->nd_hooks);
517 /* Link us into the name hash. */
518 mtx_lock(&ng_namehash_mtx);
519 LIST_INSERT_HEAD(&ng_name_hash[0], node, nd_nodes);
520 mtx_unlock(&ng_namehash_mtx);
522 /* get an ID and put us in the hash chain */
523 mtx_lock(&ng_idhash_mtx);
524 for (;;) { /* wrap protection, even if silly */
526 node->nd_ID = nextID++; /* 137/second for 1 year before wrap */
528 /* Is there a problem with the new number? */
529 NG_IDHASH_FIND(node->nd_ID, node2); /* already taken? */
530 if ((node->nd_ID != 0) && (node2 == NULL)) {
534 LIST_INSERT_HEAD(&ng_ID_hash[NG_IDHASH_FN(node->nd_ID)],
536 mtx_unlock(&ng_idhash_mtx);
544 * Forceably start the shutdown process on a node. Either call
545 * its shutdown method, or do the default shutdown if there is
546 * no type-specific method.
548 * We can only be called from a shutdown message, so we know we have
549 * a writer lock, and therefore exclusive access. It also means
550 * that we should not be on the work queue, but we check anyhow.
552 * Persistent node types must have a type-specific method which
553 * allocates a new node in which case, this one is irretrievably going away,
554 * or cleans up anything it needs, and just makes the node valid again,
555 * in which case we allow the node to survive.
557 * XXX We need to think of how to tell a persistent node that we
558 * REALLY need to go away because the hardware has gone or we
559 * are rebooting.... etc.
562 ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3)
566 /* Check if it's already shutting down */
567 if ((node->nd_flags & NGF_CLOSING) != 0)
570 if (node == &ng_deadnode) {
571 printf ("shutdown called on deadnode\n");
575 /* Add an extra reference so it doesn't go away during this */
579 * Mark it invalid so any newcomers know not to try use it
580 * Also add our own mark so we can't recurse
581 * note that NGF_INVALID does not do this as it's also set during
584 node->nd_flags |= NGF_INVALID|NGF_CLOSING;
586 /* If node has its pre-shutdown method, then call it first*/
587 if (node->nd_type && node->nd_type->close)
588 (*node->nd_type->close)(node);
590 /* Notify all remaining connected nodes to disconnect */
591 while ((hook = LIST_FIRST(&node->nd_hooks)) != NULL)
592 ng_destroy_hook(hook);
595 * Drain the input queue forceably.
596 * it has no hooks so what's it going to do, bleed on someone?
597 * Theoretically we came here from a queue entry that was added
598 * Just before the queue was closed, so it should be empty anyway.
599 * Also removes us from worklist if needed.
601 ng_flush_input_queue(node);
603 /* Ask the type if it has anything to do in this case */
604 if (node->nd_type && node->nd_type->shutdown) {
605 (*node->nd_type->shutdown)(node);
606 if (NG_NODE_IS_VALID(node)) {
608 * Well, blow me down if the node code hasn't declared
609 * that it doesn't want to die.
610 * Presumably it is a persistant node.
611 * If we REALLY want it to go away,
612 * e.g. hardware going away,
613 * Our caller should set NGF_REALLY_DIE in nd_flags.
615 node->nd_flags &= ~(NGF_INVALID|NGF_CLOSING);
616 NG_NODE_UNREF(node); /* Assume they still have theirs */
619 } else { /* do the default thing */
623 ng_unname(node); /* basically a NOP these days */
626 * Remove extra reference, possibly the last
627 * Possible other holders of references may include
628 * timeout callouts, but theoretically the node's supposed to
629 * have cancelled them. Possibly hardware dependencies may
630 * force a driver to 'linger' with a reference.
636 * Remove a reference to the node, possibly the last.
637 * deadnode always acts as it it were the last.
640 ng_unref_node(node_p node)
644 if (node == &ng_deadnode) {
648 v = atomic_fetchadd_int(&node->nd_refs, -1);
650 if (v == 1) { /* we were the last */
652 mtx_lock(&ng_namehash_mtx);
653 node->nd_type->refs--; /* XXX maybe should get types lock? */
654 LIST_REMOVE(node, nd_nodes);
655 mtx_unlock(&ng_namehash_mtx);
657 mtx_lock(&ng_idhash_mtx);
658 LIST_REMOVE(node, nd_idnodes);
659 mtx_unlock(&ng_idhash_mtx);
661 mtx_uninit(&node->nd_input_queue.q_mtx);
667 /************************************************************************
669 ************************************************************************/
671 ng_ID2noderef(ng_ID_t ID)
674 mtx_lock(&ng_idhash_mtx);
675 NG_IDHASH_FIND(ID, node);
678 mtx_unlock(&ng_idhash_mtx);
683 ng_node2ID(node_p node)
685 return (node ? NG_NODE_ID(node) : 0);
688 /************************************************************************
690 ************************************************************************/
693 * Assign a node a name. Once assigned, the name cannot be changed.
696 ng_name_node(node_p node, const char *name)
701 /* Check the name is valid */
702 for (i = 0; i < NG_NODESIZ; i++) {
703 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
706 if (i == 0 || name[i] != '\0') {
710 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
715 /* Check the name isn't already being used */
716 if ((node2 = ng_name2noderef(node, name)) != NULL) {
717 NG_NODE_UNREF(node2);
723 strlcpy(NG_NODE_NAME(node), name, NG_NODESIZ);
725 /* Update name hash. */
726 NG_NAMEHASH(name, hash);
727 mtx_lock(&ng_namehash_mtx);
728 LIST_REMOVE(node, nd_nodes);
729 LIST_INSERT_HEAD(&ng_name_hash[hash], node, nd_nodes);
730 mtx_unlock(&ng_namehash_mtx);
736 * Find a node by absolute name. The name should NOT end with ':'
737 * The name "." means "this node" and "[xxx]" means "the node
738 * with ID (ie, at address) xxx".
740 * Returns the node if found, else NULL.
741 * Eventually should add something faster than a sequential search.
742 * Note it acquires a reference on the node so you can be sure it's still
746 ng_name2noderef(node_p here, const char *name)
752 /* "." means "this node" */
753 if (strcmp(name, ".") == 0) {
758 /* Check for name-by-ID */
759 if ((temp = ng_decodeidname(name)) != 0) {
760 return (ng_ID2noderef(temp));
763 /* Find node by name */
764 NG_NAMEHASH(name, hash);
765 mtx_lock(&ng_namehash_mtx);
766 LIST_FOREACH(node, &ng_name_hash[hash], nd_nodes) {
767 if (NG_NODE_IS_VALID(node) &&
768 (strcmp(NG_NODE_NAME(node), name) == 0)) {
774 mtx_unlock(&ng_namehash_mtx);
779 * Decode an ID name, eg. "[f03034de]". Returns 0 if the
780 * string is not valid, otherwise returns the value.
783 ng_decodeidname(const char *name)
785 const int len = strlen(name);
789 /* Check for proper length, brackets, no leading junk */
792 || (name[len - 1] != ']')
793 || (!isxdigit(name[1]))) {
798 val = strtoul(name + 1, &eptr, 16);
799 if ((eptr - name != len - 1)
800 || (val == ULONG_MAX)
808 * Remove a name from a node. This should only be called
809 * when shutting down and removing the node.
810 * IF we allow name changing this may be more resurrected.
813 ng_unname(node_p node)
817 /************************************************************************
819 Names are not optional. Hooks are always connected, except for a
820 brief moment within these routines. On invalidation or during creation
821 they are connected to the 'dead' hook.
822 ************************************************************************/
825 * Remove a hook reference
828 ng_unref_hook(hook_p hook)
832 if (hook == &ng_deadhook) {
836 v = atomic_fetchadd_int(&hook->hk_refs, -1);
838 if (v == 1) { /* we were the last */
839 if (_NG_HOOK_NODE(hook)) /* it'll probably be ng_deadnode */
840 _NG_NODE_UNREF((_NG_HOOK_NODE(hook)));
846 * Add an unconnected hook to a node. Only used internally.
847 * Assumes node is locked. (XXX not yet true )
850 ng_add_hook(node_p node, const char *name, hook_p *hookp)
855 /* Check that the given name is good */
860 if (ng_findhook(node, name) != NULL) {
865 /* Allocate the hook and link it up */
866 hook = kmalloc(sizeof(*hook), M_NETGRAPH_HOOK, M_WAITOK | M_ZERO);
867 hook->hk_refs = 1; /* add a reference for us to return */
868 hook->hk_flags = HK_INVALID;
869 hook->hk_peer = &ng_deadhook; /* start off this way */
870 hook->hk_node = node;
871 NG_NODE_REF(node); /* each hook counts as a reference */
874 strlcpy(NG_HOOK_NAME(hook), name, NG_HOOKSIZ);
877 * Check if the node type code has something to say about it
878 * If it fails, the unref of the hook will also unref the node.
880 if (node->nd_type->newhook != NULL) {
881 if ((error = (*node->nd_type->newhook)(node, hook, name))) {
882 NG_HOOK_UNREF(hook); /* this frees the hook */
887 * The 'type' agrees so far, so go ahead and link it in.
888 * We'll ask again later when we actually connect the hooks.
890 LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
892 NG_HOOK_REF(hook); /* one for the node */
902 * Node types may supply their own optimized routines for finding
903 * hooks. If none is supplied, we just do a linear search.
904 * XXX Possibly we should add a reference to the hook?
907 ng_findhook(node_p node, const char *name)
911 if (node->nd_type->findhook != NULL)
912 return (*node->nd_type->findhook)(node, name);
913 LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
914 if (NG_HOOK_IS_VALID(hook)
915 && (strcmp(NG_HOOK_NAME(hook), name) == 0))
924 * As hooks are always attached, this really destroys two hooks.
925 * The one given, and the one attached to it. Disconnect the hooks
926 * from each other first. We reconnect the peer hook to the 'dead'
927 * hook so that it can still exist after we depart. We then
928 * send the peer its own destroy message. This ensures that we only
929 * interact with the peer's structures when it is locked processing that
930 * message. We hold a reference to the peer hook so we are guaranteed that
931 * the peer hook and node are still going to exist until
932 * we are finished there as the hook holds a ref on the node.
933 * We run this same code again on the peer hook, but that time it is already
934 * attached to the 'dead' hook.
936 * This routine is called at all stages of hook creation
937 * on error detection and must be able to handle any such stage.
940 ng_destroy_hook(hook_p hook)
945 if (hook == &ng_deadhook) { /* better safe than sorry */
946 printf("ng_destroy_hook called on deadhook\n");
951 * Protect divorce process with mutex, to avoid races on
952 * simultaneous disconnect.
954 mtx_lock(&ng_topo_mtx);
956 hook->hk_flags |= HK_INVALID;
958 peer = NG_HOOK_PEER(hook);
959 node = NG_HOOK_NODE(hook);
961 if (peer && (peer != &ng_deadhook)) {
963 * Set the peer to point to ng_deadhook
964 * from this moment on we are effectively independent it.
965 * send it an rmhook message of it's own.
967 peer->hk_peer = &ng_deadhook; /* They no longer know us */
968 hook->hk_peer = &ng_deadhook; /* Nor us, them */
969 if (NG_HOOK_NODE(peer) == &ng_deadnode) {
971 * If it's already divorced from a node,
974 mtx_unlock(&ng_topo_mtx);
976 mtx_unlock(&ng_topo_mtx);
977 ng_rmhook_self(peer); /* Send it a surprise */
979 NG_HOOK_UNREF(peer); /* account for peer link */
980 NG_HOOK_UNREF(hook); /* account for peer link */
982 mtx_unlock(&ng_topo_mtx);
984 KKASSERT(mtx_notowned(&ng_topo_mtx));
987 * Remove the hook from the node's list to avoid possible recursion
988 * in case the disconnection results in node shutdown.
990 if (node == &ng_deadnode) { /* happens if called from ng_con_nodes() */
993 LIST_REMOVE(hook, hk_hooks);
995 if (node->nd_type->disconnect) {
997 * The type handler may elect to destroy the node so don't
998 * trust its existence after this point. (except
999 * that we still hold a reference on it. (which we
1000 * inherrited from the hook we are destroying)
1002 (*node->nd_type->disconnect) (hook);
1006 * Note that because we will point to ng_deadnode, the original node
1007 * is not decremented automatically so we do that manually.
1009 _NG_HOOK_NODE(hook) = &ng_deadnode;
1010 NG_NODE_UNREF(node); /* We no longer point to it so adjust count */
1011 NG_HOOK_UNREF(hook); /* Account for linkage (in list) to node */
1015 * Take two hooks on a node and merge the connection so that the given node
1016 * is effectively bypassed.
1019 ng_bypass(hook_p hook1, hook_p hook2)
1021 if (hook1->hk_node != hook2->hk_node) {
1025 hook1->hk_peer->hk_peer = hook2->hk_peer;
1026 hook2->hk_peer->hk_peer = hook1->hk_peer;
1028 hook1->hk_peer = &ng_deadhook;
1029 hook2->hk_peer = &ng_deadhook;
1031 NG_HOOK_UNREF(hook1);
1032 NG_HOOK_UNREF(hook2);
1034 /* XXX If we ever cache methods on hooks update them as well */
1035 ng_destroy_hook(hook1);
1036 ng_destroy_hook(hook2);
1041 * Install a new netgraph type
1044 ng_newtype(struct ng_type *tp)
1046 const size_t namelen = strlen(tp->name);
1048 /* Check version and type name fields */
1049 if ((tp->version != NG_ABI_VERSION)
1051 || (namelen >= NG_TYPESIZ)) {
1053 if (tp->version != NG_ABI_VERSION) {
1054 printf("Netgraph: Node type rejected. ABI mismatch. Suggest recompile\n");
1059 /* Check for name collision */
1060 if (ng_findtype(tp->name) != NULL) {
1066 /* Link in new type */
1067 mtx_lock(&ng_typelist_mtx);
1068 LIST_INSERT_HEAD(&ng_typelist, tp, types);
1069 tp->refs = 1; /* first ref is linked list */
1070 mtx_unlock(&ng_typelist_mtx);
1075 * unlink a netgraph type
1076 * If no examples exist
1079 ng_rmtype(struct ng_type *tp)
1081 /* Check for name collision */
1082 if (tp->refs != 1) {
1088 mtx_lock(&ng_typelist_mtx);
1089 LIST_REMOVE(tp, types);
1090 mtx_unlock(&ng_typelist_mtx);
1095 * Look for a type of the name given
1098 ng_findtype(const char *typename)
1100 struct ng_type *type;
1102 mtx_lock(&ng_typelist_mtx);
1103 LIST_FOREACH(type, &ng_typelist, types) {
1104 if (strcmp(type->name, typename) == 0)
1107 mtx_unlock(&ng_typelist_mtx);
1111 /************************************************************************
1113 ************************************************************************/
1115 * Connect two nodes using the specified hooks, using queued functions.
1118 ng_con_part3(node_p node, item_p item, hook_p hook)
1123 * When we run, we know that the node 'node' is locked for us.
1124 * Our caller has a reference on the hook.
1125 * Our caller has a reference on the node.
1126 * (In this case our caller is ng_apply_item() ).
1127 * The peer hook has a reference on the hook.
1128 * We are all set up except for the final call to the node, and
1129 * the clearing of the INVALID flag.
1131 if (NG_HOOK_NODE(hook) == &ng_deadnode) {
1133 * The node must have been freed again since we last visited
1134 * here. ng_destry_hook() has this effect but nothing else does.
1135 * We should just release our references and
1136 * free anything we can think of.
1137 * Since we know it's been destroyed, and it's our caller
1138 * that holds the references, just return.
1142 if (hook->hk_node->nd_type->connect) {
1143 if ((error = (*hook->hk_node->nd_type->connect) (hook))) {
1144 ng_destroy_hook(hook); /* also zaps peer */
1145 printf("failed in ng_con_part3()\n");
1150 * XXX this is wrong for SMP. Possibly we need
1151 * to separate out 'create' and 'invalid' flags.
1152 * should only set flags on hooks we have locked under our node.
1154 hook->hk_flags &= ~HK_INVALID;
1161 ng_con_part2(node_p node, item_p item, hook_p hook)
1167 * When we run, we know that the node 'node' is locked for us.
1168 * Our caller has a reference on the hook.
1169 * Our caller has a reference on the node.
1170 * (In this case our caller is ng_apply_item() ).
1171 * The peer hook has a reference on the hook.
1172 * our node pointer points to the 'dead' node.
1173 * First check the hook name is unique.
1174 * Should not happen because we checked before queueing this.
1176 if (ng_findhook(node, NG_HOOK_NAME(hook)) != NULL) {
1178 ng_destroy_hook(hook); /* should destroy peer too */
1179 printf("failed in ng_con_part2()\n");
1183 * Check if the node type code has something to say about it
1184 * If it fails, the unref of the hook will also unref the attached node,
1185 * however since that node is 'ng_deadnode' this will do nothing.
1186 * The peer hook will also be destroyed.
1188 if (node->nd_type->newhook != NULL) {
1189 if ((error = (*node->nd_type->newhook)(node, hook,
1191 ng_destroy_hook(hook); /* should destroy peer too */
1192 printf("failed in ng_con_part2()\n");
1198 * The 'type' agrees so far, so go ahead and link it in.
1199 * We'll ask again later when we actually connect the hooks.
1201 hook->hk_node = node; /* just overwrite ng_deadnode */
1202 NG_NODE_REF(node); /* each hook counts as a reference */
1203 LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
1204 node->nd_numhooks++;
1205 NG_HOOK_REF(hook); /* one for the node */
1208 * We now have a symmetrical situation, where both hooks have been
1209 * linked to their nodes, the newhook methods have been called
1210 * And the references are all correct. The hooks are still marked
1211 * as invalid, as we have not called the 'connect' methods
1213 * We can call the local one immediately as we have the
1214 * node locked, but we need to queue the remote one.
1216 if (hook->hk_node->nd_type->connect) {
1217 if ((error = (*hook->hk_node->nd_type->connect) (hook))) {
1218 ng_destroy_hook(hook); /* also zaps peer */
1219 printf("failed in ng_con_part2(A)\n");
1225 * Acquire topo mutex to avoid race with ng_destroy_hook().
1227 mtx_lock(&ng_topo_mtx);
1228 peer = hook->hk_peer;
1229 if (peer == &ng_deadhook) {
1230 mtx_unlock(&ng_topo_mtx);
1231 printf("failed in ng_con_part2(B)\n");
1232 ng_destroy_hook(hook);
1235 mtx_unlock(&ng_topo_mtx);
1237 if ((error = ng_send_fn2(peer->hk_node, peer, item, &ng_con_part3,
1238 NULL, 0, NG_REUSE_ITEM))) {
1239 printf("failed in ng_con_part2(C)\n");
1240 ng_destroy_hook(hook); /* also zaps peer */
1241 return (error); /* item was consumed. */
1243 hook->hk_flags &= ~HK_INVALID; /* need both to be able to work */
1244 return (0); /* item was consumed. */
1251 * Connect this node with another node. We assume that this node is
1252 * currently locked, as we are only called from an NGM_CONNECT message.
1255 ng_con_nodes(item_p item, node_p node, const char *name,
1256 node_p node2, const char *name2)
1262 if (ng_findhook(node2, name2) != NULL) {
1265 if ((error = ng_add_hook(node, name, &hook))) /* gives us a ref */
1267 /* Allocate the other hook and link it up */
1268 hook2 = kmalloc(sizeof(*hook2), M_NETGRAPH_HOOK, M_WAITOK | M_ZERO);
1269 hook2->hk_refs = 1; /* start with a reference for us. */
1270 hook2->hk_flags = HK_INVALID;
1271 hook2->hk_peer = hook; /* Link the two together */
1272 hook->hk_peer = hook2;
1273 NG_HOOK_REF(hook); /* Add a ref for the peer to each*/
1275 hook2->hk_node = &ng_deadnode;
1276 strlcpy(NG_HOOK_NAME(hook2), name2, NG_HOOKSIZ);
1279 * Queue the function above.
1280 * Procesing continues in that function in the lock context of
1283 if ((error = ng_send_fn2(node2, hook2, item, &ng_con_part2, NULL, 0,
1285 printf("failed in ng_con_nodes(): %d\n", error);
1286 ng_destroy_hook(hook); /* also zaps peer */
1289 NG_HOOK_UNREF(hook); /* Let each hook go if it wants to */
1290 NG_HOOK_UNREF(hook2);
1295 * Make a peer and connect.
1296 * We assume that the local node is locked.
1297 * The new node probably doesn't need a lock until
1298 * it has a hook, because it cannot really have any work until then,
1299 * but we should think about it a bit more.
1301 * The problem may come if the other node also fires up
1302 * some hardware or a timer or some other source of activation,
1303 * also it may already get a command msg via it's ID.
1305 * We could use the same method as ng_con_nodes() but we'd have
1306 * to add ability to remove the node when failing. (Not hard, just
1307 * make arg1 point to the node to remove).
1308 * Unless of course we just ignore failure to connect and leave
1309 * an unconnected node?
1312 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
1315 hook_p hook1, hook2;
1318 if ((error = ng_make_node(type, &node2))) {
1322 if ((error = ng_add_hook(node, name, &hook1))) { /* gives us a ref */
1323 ng_rmnode(node2, NULL, NULL, 0);
1327 if ((error = ng_add_hook(node2, name2, &hook2))) {
1328 ng_rmnode(node2, NULL, NULL, 0);
1329 ng_destroy_hook(hook1);
1330 NG_HOOK_UNREF(hook1);
1335 * Actually link the two hooks together.
1337 hook1->hk_peer = hook2;
1338 hook2->hk_peer = hook1;
1340 /* Each hook is referenced by the other */
1344 /* Give each node the opportunity to veto the pending connection */
1345 if (hook1->hk_node->nd_type->connect) {
1346 error = (*hook1->hk_node->nd_type->connect) (hook1);
1349 if ((error == 0) && hook2->hk_node->nd_type->connect) {
1350 error = (*hook2->hk_node->nd_type->connect) (hook2);
1355 * drop the references we were holding on the two hooks.
1358 ng_destroy_hook(hook2); /* also zaps hook1 */
1359 ng_rmnode(node2, NULL, NULL, 0);
1361 /* As a last act, allow the hooks to be used */
1362 hook1->hk_flags &= ~HK_INVALID;
1363 hook2->hk_flags &= ~HK_INVALID;
1365 NG_HOOK_UNREF(hook1);
1366 NG_HOOK_UNREF(hook2);
1370 /************************************************************************
1371 Utility routines to send self messages
1372 ************************************************************************/
1374 /* Shut this node down as soon as everyone is clear of it */
1375 /* Should add arg "immediately" to jump the queue */
1377 ng_rmnode_self(node_p node)
1381 if (node == &ng_deadnode)
1383 node->nd_flags |= NGF_INVALID;
1384 if (node->nd_flags & NGF_CLOSING)
1387 error = ng_send_fn(node, NULL, &ng_rmnode, NULL, 0);
1392 ng_rmhook_part2(node_p node, hook_p hook, void *arg1, int arg2)
1394 ng_destroy_hook(hook);
1399 ng_rmhook_self(hook_p hook)
1402 node_p node = NG_HOOK_NODE(hook);
1404 if (node == &ng_deadnode)
1407 error = ng_send_fn(node, hook, &ng_rmhook_part2, NULL, 0);
1411 /***********************************************************************
1412 * Parse and verify a string of the form: <NODE:><PATH>
1414 * Such a string can refer to a specific node or a specific hook
1415 * on a specific node, depending on how you look at it. In the
1416 * latter case, the PATH component must not end in a dot.
1418 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1419 * of hook names separated by dots. This breaks out the original
1420 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1421 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1422 * the final hook component of <PATH>, if any, otherwise NULL.
1424 * This returns -1 if the path is malformed. The char ** are optional.
1425 ***********************************************************************/
1427 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1429 char *node, *path, *hook;
1433 * Extract absolute NODE, if any
1435 for (path = addr; *path && *path != ':'; path++);
1437 node = addr; /* Here's the NODE */
1438 *path++ = '\0'; /* Here's the PATH */
1440 /* Node name must not be empty */
1444 /* A name of "." is OK; otherwise '.' not allowed */
1445 if (strcmp(node, ".") != 0) {
1446 for (k = 0; node[k]; k++)
1451 node = NULL; /* No absolute NODE */
1452 path = addr; /* Here's the PATH */
1455 /* Snoop for illegal characters in PATH */
1456 for (k = 0; path[k]; k++)
1460 /* Check for no repeated dots in PATH */
1461 for (k = 0; path[k]; k++)
1462 if (path[k] == '.' && path[k + 1] == '.')
1465 /* Remove extra (degenerate) dots from beginning or end of PATH */
1468 if (*path && path[strlen(path) - 1] == '.')
1469 path[strlen(path) - 1] = 0;
1471 /* If PATH has a dot, then we're not talking about a hook */
1473 for (hook = path, k = 0; path[k]; k++)
1474 if (path[k] == '.') {
1492 * Given a path, which may be absolute or relative, and a starting node,
1493 * return the destination node.
1496 ng_path2noderef(node_p here, const char *address,
1497 node_p *destp, hook_p *lasthook)
1499 char fullpath[NG_PATHSIZ];
1500 char *nodename, *path, pbuf[2];
1501 node_p node, oldnode;
1506 if (destp == NULL) {
1512 /* Make a writable copy of address for ng_path_parse() */
1513 strncpy(fullpath, address, sizeof(fullpath) - 1);
1514 fullpath[sizeof(fullpath) - 1] = '\0';
1516 /* Parse out node and sequence of hooks */
1517 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1522 pbuf[0] = '.'; /* Needs to be writable */
1528 * For an absolute address, jump to the starting node.
1529 * Note that this holds a reference on the node for us.
1530 * Don't forget to drop the reference if we don't need it.
1533 node = ng_name2noderef(here, nodename);
1548 * Now follow the sequence of hooks
1550 * We actually cannot guarantee that the sequence
1551 * is not being demolished as we crawl along it
1552 * without extra-ordinary locking etc.
1553 * So this is a bit dodgy to say the least.
1554 * We can probably hold up some things by holding
1555 * the nodelist mutex for the time of this
1556 * crawl if we wanted.. At least that way we wouldn't have to
1557 * worry about the nodes disappearing, but the hooks would still
1560 for (cp = path; node != NULL && *cp != '\0'; ) {
1564 * Break out the next path segment. Replace the dot we just
1565 * found with a NUL; "cp" points to the next segment (or the
1568 for (segment = cp; *cp != '\0'; cp++) {
1576 if (*segment == '\0')
1579 /* We have a segment, so look for a hook by that name */
1580 hook = ng_findhook(node, segment);
1582 /* Can't get there from here... */
1584 || NG_HOOK_PEER(hook) == NULL
1585 || NG_HOOK_NOT_VALID(hook)
1586 || NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))) {
1588 NG_NODE_UNREF(node);
1590 printf("hooknotvalid %s %s %d %d %d %d ",
1594 NG_HOOK_PEER(hook) == NULL,
1595 NG_HOOK_NOT_VALID(hook),
1596 NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook)));
1602 * Hop on over to the next node
1604 * Big race conditions here as hooks and nodes go away
1605 * *** Idea.. store an ng_ID_t in each hook and use that
1606 * instead of the direct hook in this crawl?
1609 if ((node = NG_PEER_NODE(hook)))
1610 NG_NODE_REF(node); /* XXX RACE */
1611 NG_NODE_UNREF(oldnode); /* XXX another race */
1612 if (NG_NODE_NOT_VALID(node)) {
1613 NG_NODE_UNREF(node); /* XXX more races */
1618 /* If node somehow missing, fail here (probably this is not needed) */
1626 if (lasthook != NULL)
1627 *lasthook = (hook ? NG_HOOK_PEER(hook) : NULL);
1631 /***************************************************************\
1632 * Input queue handling.
1633 * All activities are submitted to the node via the input queue
1634 * which implements a multiple-reader/single-writer gate.
1635 * Items which cannot be handled immediately are queued.
1637 * read-write queue locking inline functions *
1638 \***************************************************************/
1640 static __inline void ng_queue_rw(node_p node, item_p item, int rw);
1641 static __inline item_p ng_dequeue(node_p node, int *rw);
1642 static __inline item_p ng_acquire_read(node_p node, item_p item);
1643 static __inline item_p ng_acquire_write(node_p node, item_p item);
1644 static __inline void ng_leave_read(node_p node);
1645 static __inline void ng_leave_write(node_p node);
1648 * Definition of the bits fields in the ng_queue flag word.
1649 * Defined here rather than in netgraph.h because no-one should fiddle
1652 * The ordering here may be important! don't shuffle these.
1655 Safety Barrier--------+ (adjustable to suit taste) (not used yet)
1658 +-------+-------+-------+-------+-------+-------+-------+-------+
1659 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
1660 | |A|c|t|i|v|e| |R|e|a|d|e|r| |C|o|u|n|t| | | | | | | | | |P|A|
1661 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |O|W|
1662 +-------+-------+-------+-------+-------+-------+-------+-------+
1663 \___________________________ ____________________________/ | |
1665 [active reader count] | |
1667 Operation Pending -------------------------------+ |
1669 Active Writer ---------------------------------------+
1671 Node queue has such semantics:
1672 - All flags modifications are atomic.
1673 - Reader count can be incremented only if there is no writer or pending flags.
1674 As soon as this can't be done with single operation, it is implemented with
1675 spin loop and atomic_cmpset().
1676 - Writer flag can be set only if there is no any bits set.
1677 It is implemented with atomic_cmpset().
1678 - Pending flag can be set any time, but to avoid collision on queue processing
1679 all queue fields are protected by the mutex.
1680 - Queue processing thread reads queue holding the mutex, but releases it while
1681 processing. When queue is empty pending flag is removed.
1684 #define WRITER_ACTIVE 0x00000001
1685 #define OP_PENDING 0x00000002
1686 #define READER_INCREMENT 0x00000004
1687 #define READER_MASK 0xfffffffc /* Not valid if WRITER_ACTIVE is set */
1688 #define SAFETY_BARRIER 0x00100000 /* 128K items queued should be enough */
1690 /* Defines of more elaborate states on the queue */
1691 /* Mask of bits a new read cares about */
1692 #define NGQ_RMASK (WRITER_ACTIVE|OP_PENDING)
1694 /* Mask of bits a new write cares about */
1695 #define NGQ_WMASK (NGQ_RMASK|READER_MASK)
1697 /* Test to decide if there is something on the queue. */
1698 #define QUEUE_ACTIVE(QP) ((QP)->q_flags & OP_PENDING)
1700 /* How to decide what the next queued item is. */
1701 #define HEAD_IS_READER(QP) NGI_QUEUED_READER(STAILQ_FIRST(&(QP)->queue))
1702 #define HEAD_IS_WRITER(QP) NGI_QUEUED_WRITER(STAILQ_FIRST(&(QP)->queue)) /* notused */
1704 /* Read the status to decide if the next item on the queue can now run. */
1705 #define QUEUED_READER_CAN_PROCEED(QP) \
1706 (((QP)->q_flags & (NGQ_RMASK & ~OP_PENDING)) == 0)
1707 #define QUEUED_WRITER_CAN_PROCEED(QP) \
1708 (((QP)->q_flags & (NGQ_WMASK & ~OP_PENDING)) == 0)
1710 /* Is there a chance of getting ANY work off the queue? */
1711 #define NEXT_QUEUED_ITEM_CAN_PROCEED(QP) \
1712 ((HEAD_IS_READER(QP)) ? QUEUED_READER_CAN_PROCEED(QP) : \
1713 QUEUED_WRITER_CAN_PROCEED(QP))
1718 #define NGQ2_WORKQ 0x00000001
1721 * Taking into account the current state of the queue and node, possibly take
1722 * the next entry off the queue and return it. Return NULL if there was
1723 * nothing we could return, either because there really was nothing there, or
1724 * because the node was in a state where it cannot yet process the next item
1727 static __inline item_p
1728 ng_dequeue(node_p node, int *rw)
1731 struct ng_queue *ngq = &node->nd_input_queue;
1733 /* This MUST be called with the mutex held. */
1734 KKASSERT(mtx_owned(&ngq->q_mtx));
1736 /* If there is nothing queued, then just return. */
1737 if (!QUEUE_ACTIVE(ngq)) {
1738 CTR4(KTR_NET, "%20s: node [%x] (%p) queue empty; "
1739 "queue flags 0x%lx", __func__,
1740 node->nd_ID, node, ngq->q_flags);
1745 * From here, we can assume there is a head item.
1746 * We need to find out what it is and if it can be dequeued, given
1747 * the current state of the node.
1749 if (HEAD_IS_READER(ngq)) {
1751 long t = ngq->q_flags;
1752 if (t & WRITER_ACTIVE) {
1753 /* There is writer, reader can't proceed. */
1754 CTR4(KTR_NET, "%20s: node [%x] (%p) queued reader "
1755 "can't proceed; queue flags 0x%lx", __func__,
1756 node->nd_ID, node, t);
1759 if (atomic_cmpset_acq_int(&ngq->q_flags, t,
1760 t + READER_INCREMENT))
1764 /* We have got reader lock for the node. */
1766 } else if (atomic_cmpset_acq_int(&ngq->q_flags, OP_PENDING,
1767 OP_PENDING + WRITER_ACTIVE)) {
1768 /* We have got writer lock for the node. */
1771 /* There is somebody other, writer can't proceed. */
1772 CTR4(KTR_NET, "%20s: node [%x] (%p) queued writer "
1773 "can't proceed; queue flags 0x%lx", __func__,
1774 node->nd_ID, node, ngq->q_flags);
1779 * Now we dequeue the request (whatever it may be) and correct the
1780 * pending flags and the next and last pointers.
1782 item = STAILQ_FIRST(&ngq->queue);
1783 STAILQ_REMOVE_HEAD(&ngq->queue, el_next);
1784 if (STAILQ_EMPTY(&ngq->queue))
1785 atomic_clear_int(&ngq->q_flags, OP_PENDING);
1786 CTR6(KTR_NET, "%20s: node [%x] (%p) returning item %p as %s; "
1787 "queue flags 0x%lx", __func__,
1788 node->nd_ID, node, item, *rw ? "WRITER" : "READER" ,
1794 * Queue a packet to be picked up later by someone else.
1795 * If the queue could be run now, add node to the queue handler's worklist.
1797 static __inline void
1798 ng_queue_rw(node_p node, item_p item, int rw)
1800 struct ng_queue *ngq = &node->nd_input_queue;
1802 NGI_SET_WRITER(item);
1804 NGI_SET_READER(item);
1807 /* Set OP_PENDING flag and enqueue the item. */
1808 atomic_set_int(&ngq->q_flags, OP_PENDING);
1809 STAILQ_INSERT_TAIL(&ngq->queue, item, el_next);
1811 CTR5(KTR_NET, "%20s: node [%x] (%p) queued item %p as %s", __func__,
1812 node->nd_ID, node, item, rw ? "WRITER" : "READER" );
1815 * We can take the worklist lock with the node locked
1816 * BUT NOT THE REVERSE!
1818 if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
1819 ng_worklist_add(node);
1820 NG_QUEUE_UNLOCK(ngq);
1823 /* Acquire reader lock on node. If node is busy, queue the packet. */
1824 static __inline item_p
1825 ng_acquire_read(node_p node, item_p item)
1827 KASSERT(node != &ng_deadnode,
1828 ("%s: working on deadnode", __func__));
1830 /* Reader needs node without writer and pending items. */
1832 long t = node->nd_input_queue.q_flags;
1834 break; /* Node is not ready for reader. */
1835 if (atomic_cmpset_acq_int(&node->nd_input_queue.q_flags,
1836 t, t + READER_INCREMENT)) {
1837 /* Successfully grabbed node */
1838 CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
1839 __func__, node->nd_ID, node, item);
1845 /* Queue the request for later. */
1846 ng_queue_rw(node, item, NGQRW_R);
1851 /* Acquire writer lock on node. If node is busy, queue the packet. */
1852 static __inline item_p
1853 ng_acquire_write(node_p node, item_p item)
1855 KASSERT(node != &ng_deadnode,
1856 ("%s: working on deadnode", __func__));
1858 /* Writer needs completely idle node. */
1859 if (atomic_cmpset_acq_int(&node->nd_input_queue.q_flags,
1860 0, WRITER_ACTIVE)) {
1861 /* Successfully grabbed node */
1862 CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
1863 __func__, node->nd_ID, node, item);
1867 /* Queue the request for later. */
1868 ng_queue_rw(node, item, NGQRW_W);
1874 static __inline item_p
1875 ng_upgrade_write(node_p node, item_p item)
1877 struct ng_queue *ngq = &node->nd_input_queue;
1878 KASSERT(node != &ng_deadnode,
1879 ("%s: working on deadnode", __func__));
1881 NGI_SET_WRITER(item);
1886 * There will never be no readers as we are there ourselves.
1887 * Set the WRITER_ACTIVE flags ASAP to block out fast track readers.
1888 * The caller we are running from will call ng_leave_read()
1889 * soon, so we must account for that. We must leave again with the
1890 * READER lock. If we find other readers, then
1891 * queue the request for later. However "later" may be rignt now
1892 * if there are no readers. We don't really care if there are queued
1893 * items as we will bypass them anyhow.
1895 atomic_add_int(&ngq->q_flags, WRITER_ACTIVE - READER_INCREMENT);
1896 if ((ngq->q_flags & (NGQ_WMASK & ~OP_PENDING)) == WRITER_ACTIVE) {
1897 NG_QUEUE_UNLOCK(ngq);
1899 /* It's just us, act on the item. */
1900 /* will NOT drop writer lock when done */
1901 ng_apply_item(node, item, 0);
1904 * Having acted on the item, atomically
1905 * down grade back to READER and finish up
1907 atomic_add_int(&ngq->q_flags,
1908 READER_INCREMENT - WRITER_ACTIVE);
1910 /* Our caller will call ng_leave_read() */
1914 * It's not just us active, so queue us AT THE HEAD.
1915 * "Why?" I hear you ask.
1916 * Put us at the head of the queue as we've already been
1917 * through it once. If there is nothing else waiting,
1918 * set the correct flags.
1920 if (STAILQ_EMPTY(&ngq->queue)) {
1921 /* We've gone from, 0 to 1 item in the queue */
1922 atomic_set_int(&ngq->q_flags, OP_PENDING);
1924 CTR3(KTR_NET, "%20s: node [%x] (%p) set OP_PENDING", __func__,
1927 STAILQ_INSERT_HEAD(&ngq->queue, item, el_next);
1928 CTR4(KTR_NET, "%20s: node [%x] (%p) requeued item %p as WRITER",
1929 __func__, node->nd_ID, node, item );
1931 /* Reverse what we did above. That downgrades us back to reader */
1932 atomic_add_int(&ngq->q_flags, READER_INCREMENT - WRITER_ACTIVE);
1933 if (QUEUE_ACTIVE(ngq) && NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
1934 ng_worklist_add(node);
1935 NG_QUEUE_UNLOCK(ngq);
1941 /* Release reader lock. */
1942 static __inline void
1943 ng_leave_read(node_p node)
1945 atomic_subtract_rel_int(&node->nd_input_queue.q_flags, READER_INCREMENT);
1948 /* Release writer lock. */
1949 static __inline void
1950 ng_leave_write(node_p node)
1952 atomic_clear_rel_int(&node->nd_input_queue.q_flags, WRITER_ACTIVE);
1955 /* Purge node queue. Called on node shutdown. */
1957 ng_flush_input_queue(node_p node)
1959 struct ng_queue *ngq = &node->nd_input_queue;
1963 while ((item = STAILQ_FIRST(&ngq->queue)) != NULL) {
1964 STAILQ_REMOVE_HEAD(&ngq->queue, el_next);
1965 if (STAILQ_EMPTY(&ngq->queue))
1966 atomic_clear_int(&ngq->q_flags, OP_PENDING);
1967 NG_QUEUE_UNLOCK(ngq);
1969 /* If the item is supplying a callback, call it with an error */
1970 if (item->apply != NULL) {
1971 if (item->depth == 1)
1972 item->apply->error = ENOENT;
1973 if (refcount_release(&item->apply->refs)) {
1974 (*item->apply->apply)(item->apply->context,
1975 item->apply->error);
1981 NG_QUEUE_UNLOCK(ngq);
1984 /***********************************************************************
1985 * Externally visible method for sending or queueing messages or data.
1986 ***********************************************************************/
1989 * The module code should have filled out the item correctly by this stage:
1991 * reference to destination node.
1992 * Reference to destination rcv hook if relevant.
1993 * apply pointer must be or NULL or reference valid struct ng_apply_info.
1998 * ID of original sender node. (return address)
2004 * The nodes have several routines and macros to help with this task:
2008 ng_snd_item(item_p item, int flags)
2013 struct ng_queue *ngq;
2016 /* We are sending item, so it must be present! */
2017 KASSERT(item != NULL, ("ng_snd_item: item is NULL"));
2019 /* Item was sent once more, postpone apply() call. */
2021 refcount_acquire(&item->apply->refs);
2023 node = NGI_NODE(item);
2024 /* Node is never optional. */
2025 KASSERT(node != NULL, ("ng_snd_item: node is NULL"));
2027 hook = NGI_HOOK(item);
2028 /* Valid hook and mbuf are mandatory for data. */
2029 if ((item->el_flags & NGQF_TYPE) == NGQF_DATA) {
2030 KASSERT(hook != NULL, ("ng_snd_item: hook for data is NULL"));
2031 if (NGI_M(item) == NULL)
2033 CHECK_DATA_MBUF(NGI_M(item));
2037 * If the item or the node specifies single threading, force
2038 * writer semantics. Similarly, the node may say one hook always
2039 * produces writers. These are overrides.
2041 if (((item->el_flags & NGQF_RW) == NGQF_WRITER) ||
2042 (node->nd_flags & NGF_FORCE_WRITER) ||
2043 (hook && (hook->hk_flags & HK_FORCE_WRITER))) {
2050 * If sender or receiver requests queued delivery or stack usage
2051 * level is dangerous - enqueue message.
2053 if ((flags & NG_QUEUE) || (hook && (hook->hk_flags & HK_QUEUE))) {
2057 #ifdef GET_STACK_USAGE
2059 * Most of netgraph nodes have small stack consumption and
2060 * for them 25% of free stack space is more than enough.
2061 * Nodes/hooks with higher stack usage should be marked as
2062 * HI_STACK. For them 50% of stack will be guaranteed then.
2063 * XXX: Values 25% and 50% are completely empirical.
2066 GET_STACK_USAGE(st, su);
2068 if ((sl * 4 < st) ||
2069 ((sl * 2 < st) && ((node->nd_flags & NGF_HI_STACK) ||
2070 (hook && (hook->hk_flags & HK_HI_STACK))))) {
2078 /* Put it on the queue for that node*/
2079 ng_queue_rw(node, item, rw);
2080 return ((flags & NG_PROGRESS) ? EINPROGRESS : 0);
2084 * We already decided how we will be queueud or treated.
2085 * Try get the appropriate operating permission.
2088 item = ng_acquire_read(node, item);
2090 item = ng_acquire_write(node, item);
2092 /* Item was queued while trying to get permission. */
2094 return ((flags & NG_PROGRESS) ? EINPROGRESS : 0);
2096 NGI_GET_NODE(item, node); /* zaps stored node */
2099 error = ng_apply_item(node, item, rw); /* drops r/w lock when done */
2101 /* If something is waiting on queue and ready, schedule it. */
2102 ngq = &node->nd_input_queue;
2103 if (QUEUE_ACTIVE(ngq)) {
2105 if (QUEUE_ACTIVE(ngq) && NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2106 ng_worklist_add(node);
2107 NG_QUEUE_UNLOCK(ngq);
2111 * Node may go away as soon as we remove the reference.
2112 * Whatever we do, DO NOT access the node again!
2114 NG_NODE_UNREF(node);
2119 /* If was not sent, apply callback here. */
2120 if (item->apply != NULL) {
2121 if (item->depth == 0 && error != 0)
2122 item->apply->error = error;
2123 if (refcount_release(&item->apply->refs)) {
2124 (*item->apply->apply)(item->apply->context,
2125 item->apply->error);
2134 * We have an item that was possibly queued somewhere.
2135 * It should contain all the information needed
2136 * to run it on the appropriate node/hook.
2137 * If there is apply pointer and we own the last reference, call apply().
2140 ng_apply_item(node_p node, item_p item, int rw)
2143 ng_rcvdata_t *rcvdata;
2144 ng_rcvmsg_t *rcvmsg;
2145 struct ng_apply_info *apply;
2146 int error = 0, depth;
2148 /* Node and item are never optional. */
2149 KASSERT(node != NULL, ("ng_apply_item: node is NULL"));
2150 KASSERT(item != NULL, ("ng_apply_item: item is NULL"));
2152 NGI_GET_HOOK(item, hook); /* clears stored hook */
2154 apply = item->apply;
2155 depth = item->depth;
2157 switch (item->el_flags & NGQF_TYPE) {
2160 * Check things are still ok as when we were queued.
2162 KASSERT(hook != NULL, ("ng_apply_item: hook for data is NULL"));
2163 if (NG_HOOK_NOT_VALID(hook) ||
2164 NG_NODE_NOT_VALID(node)) {
2170 * If no receive method, just silently drop it.
2171 * Give preference to the hook over-ride method
2173 if ((!(rcvdata = hook->hk_rcvdata))
2174 && (!(rcvdata = NG_HOOK_NODE(hook)->nd_type->rcvdata))) {
2179 error = (*rcvdata)(hook, item);
2182 if (hook && NG_HOOK_NOT_VALID(hook)) {
2184 * The hook has been zapped then we can't use it.
2185 * Immediately drop its reference.
2186 * The message may not need it.
2188 NG_HOOK_UNREF(hook);
2192 * Similarly, if the node is a zombie there is
2193 * nothing we can do with it, drop everything.
2195 if (NG_NODE_NOT_VALID(node)) {
2202 * Call the appropriate message handler for the object.
2203 * It is up to the message handler to free the message.
2204 * If it's a generic message, handle it generically,
2205 * otherwise call the type's message handler (if it exists).
2206 * XXX (race). Remember that a queued message may
2207 * reference a node or hook that has just been
2208 * invalidated. It will exist as the queue code
2209 * is holding a reference, but..
2211 if ((NGI_MSG(item)->header.typecookie == NGM_GENERIC_COOKIE) &&
2212 ((NGI_MSG(item)->header.flags & NGF_RESP) == 0)) {
2213 error = ng_generic_msg(node, item, hook);
2216 if (((!hook) || (!(rcvmsg = hook->hk_rcvmsg))) &&
2217 (!(rcvmsg = node->nd_type->rcvmsg))) {
2223 error = (*rcvmsg)(node, item, hook);
2228 * We have to implicitly trust the hook,
2229 * as some of these are used for system purposes
2230 * where the hook is invalid. In the case of
2231 * the shutdown message we allow it to hit
2232 * even if the node is invalid.
2234 if ((NG_NODE_NOT_VALID(node))
2235 && (NGI_FN(item) != &ng_rmnode)) {
2241 if ((item->el_flags & NGQF_TYPE) == NGQF_FN) {
2242 (*NGI_FN(item))(node, hook, NGI_ARG1(item),
2245 } else /* it is NGQF_FN2 */
2246 error = (*NGI_FN2(item))(node, item, hook);
2250 * We held references on some of the resources
2251 * that we took from the item. Now that we have
2252 * finished doing everything, drop those references.
2255 NG_HOOK_UNREF(hook);
2258 ng_leave_read(node);
2260 ng_leave_write(node);
2262 /* Apply callback. */
2263 if (apply != NULL) {
2264 if (depth == 1 && error != 0)
2265 apply->error = error;
2266 if (refcount_release(&apply->refs))
2267 (*apply->apply)(apply->context, apply->error);
2273 /***********************************************************************
2274 * Implement the 'generic' control messages
2275 ***********************************************************************/
2277 ng_generic_msg(node_p here, item_p item, hook_p lasthook)
2280 struct ng_mesg *msg;
2281 struct ng_mesg *resp = NULL;
2283 NGI_GET_MSG(item, msg);
2284 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
2289 switch (msg->header.cmd) {
2291 ng_rmnode(here, NULL, NULL, 0);
2295 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
2297 if (msg->header.arglen != sizeof(*mkp)) {
2302 mkp->type[sizeof(mkp->type) - 1] = '\0';
2303 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
2304 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
2305 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
2310 struct ngm_connect *const con =
2311 (struct ngm_connect *) msg->data;
2314 if (msg->header.arglen != sizeof(*con)) {
2319 con->path[sizeof(con->path) - 1] = '\0';
2320 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
2321 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
2322 /* Don't forget we get a reference.. */
2323 error = ng_path2noderef(here, con->path, &node2, NULL);
2326 error = ng_con_nodes(item, here, con->ourhook,
2327 node2, con->peerhook);
2328 NG_NODE_UNREF(node2);
2333 struct ngm_name *const nam = (struct ngm_name *) msg->data;
2335 if (msg->header.arglen != sizeof(*nam)) {
2340 nam->name[sizeof(nam->name) - 1] = '\0';
2341 error = ng_name_node(here, nam->name);
2346 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
2349 if (msg->header.arglen != sizeof(*rmh)) {
2354 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
2355 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
2356 ng_destroy_hook(hook);
2361 struct nodeinfo *ni;
2363 NG_MKRESPONSE(resp, msg, sizeof(*ni), M_WAITOK | M_NULLOK);
2369 /* Fill in node info */
2370 ni = (struct nodeinfo *) resp->data;
2371 if (NG_NODE_HAS_NAME(here))
2372 strcpy(ni->name, NG_NODE_NAME(here));
2373 strcpy(ni->type, here->nd_type->name);
2374 ni->id = ng_node2ID(here);
2375 ni->hooks = here->nd_numhooks;
2380 const int nhooks = here->nd_numhooks;
2381 struct hooklist *hl;
2382 struct nodeinfo *ni;
2385 /* Get response struct */
2386 NG_MKRESPONSE(resp, msg, sizeof(*hl)
2387 + (nhooks * sizeof(struct linkinfo)), M_WAITOK | M_NULLOK);
2392 hl = (struct hooklist *) resp->data;
2395 /* Fill in node info */
2396 if (NG_NODE_HAS_NAME(here))
2397 strcpy(ni->name, NG_NODE_NAME(here));
2398 strcpy(ni->type, here->nd_type->name);
2399 ni->id = ng_node2ID(here);
2401 /* Cycle through the linked list of hooks */
2403 LIST_FOREACH(hook, &here->nd_hooks, hk_hooks) {
2404 struct linkinfo *const link = &hl->link[ni->hooks];
2406 if (ni->hooks >= nhooks) {
2407 log(LOG_ERR, "%s: number of %s changed\n",
2411 if (NG_HOOK_NOT_VALID(hook))
2413 strcpy(link->ourhook, NG_HOOK_NAME(hook));
2414 strcpy(link->peerhook, NG_PEER_HOOK_NAME(hook));
2415 if (NG_PEER_NODE_NAME(hook)[0] != '\0')
2416 strcpy(link->nodeinfo.name,
2417 NG_PEER_NODE_NAME(hook));
2418 strcpy(link->nodeinfo.type,
2419 NG_PEER_NODE(hook)->nd_type->name);
2420 link->nodeinfo.id = ng_node2ID(NG_PEER_NODE(hook));
2421 link->nodeinfo.hooks = NG_PEER_NODE(hook)->nd_numhooks;
2430 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
2431 struct namelist *nl;
2435 mtx_lock(&ng_namehash_mtx);
2436 /* Count number of nodes */
2437 for (i = 0; i < NG_NAME_HASH_SIZE; i++) {
2438 LIST_FOREACH(node, &ng_name_hash[i], nd_nodes) {
2439 if (NG_NODE_IS_VALID(node) &&
2440 (unnamed || NG_NODE_HAS_NAME(node))) {
2445 mtx_unlock(&ng_namehash_mtx);
2447 /* Get response struct */
2448 NG_MKRESPONSE(resp, msg, sizeof(*nl)
2449 + (num * sizeof(struct nodeinfo)), M_WAITOK | M_NULLOK);
2454 nl = (struct namelist *) resp->data;
2456 /* Cycle through the linked list of nodes */
2458 mtx_lock(&ng_namehash_mtx);
2459 for (i = 0; i < NG_NAME_HASH_SIZE; i++) {
2460 LIST_FOREACH(node, &ng_name_hash[i], nd_nodes) {
2461 struct nodeinfo *const np =
2462 &nl->nodeinfo[nl->numnames];
2464 if (NG_NODE_NOT_VALID(node))
2466 if (!unnamed && (! NG_NODE_HAS_NAME(node)))
2468 if (nl->numnames >= num) {
2469 log(LOG_ERR, "%s: number of nodes changed\n",
2473 if (NG_NODE_HAS_NAME(node))
2474 strcpy(np->name, NG_NODE_NAME(node));
2475 strcpy(np->type, node->nd_type->name);
2476 np->id = ng_node2ID(node);
2477 np->hooks = node->nd_numhooks;
2481 mtx_unlock(&ng_namehash_mtx);
2487 struct typelist *tl;
2488 struct ng_type *type;
2491 mtx_lock(&ng_typelist_mtx);
2492 /* Count number of types */
2493 LIST_FOREACH(type, &ng_typelist, types) {
2496 mtx_unlock(&ng_typelist_mtx);
2498 /* Get response struct */
2499 NG_MKRESPONSE(resp, msg, sizeof(*tl)
2500 + (num * sizeof(struct typeinfo)), M_WAITOK | M_NULLOK);
2505 tl = (struct typelist *) resp->data;
2507 /* Cycle through the linked list of types */
2509 mtx_lock(&ng_typelist_mtx);
2510 LIST_FOREACH(type, &ng_typelist, types) {
2511 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
2513 if (tl->numtypes >= num) {
2514 log(LOG_ERR, "%s: number of %s changed\n",
2518 strcpy(tp->type_name, type->name);
2519 tp->numnodes = type->refs - 1; /* don't count list */
2522 mtx_unlock(&ng_typelist_mtx);
2526 case NGM_BINARY2ASCII:
2528 int bufSize = 20 * 1024; /* XXX hard coded constant */
2529 const struct ng_parse_type *argstype;
2530 const struct ng_cmdlist *c;
2531 struct ng_mesg *binary, *ascii;
2533 /* Data area must contain a valid netgraph message */
2534 binary = (struct ng_mesg *)msg->data;
2535 if (msg->header.arglen < sizeof(struct ng_mesg) ||
2536 (msg->header.arglen - sizeof(struct ng_mesg) <
2537 binary->header.arglen)) {
2543 /* Get a response message with lots of room */
2544 NG_MKRESPONSE(resp, msg, sizeof(*ascii) + bufSize, M_WAITOK | M_NULLOK);
2549 ascii = (struct ng_mesg *)resp->data;
2551 /* Copy binary message header to response message payload */
2552 bcopy(binary, ascii, sizeof(*binary));
2554 /* Find command by matching typecookie and command number */
2555 for (c = here->nd_type->cmdlist;
2556 c != NULL && c->name != NULL; c++) {
2557 if (binary->header.typecookie == c->cookie
2558 && binary->header.cmd == c->cmd)
2561 if (c == NULL || c->name == NULL) {
2562 for (c = ng_generic_cmds; c->name != NULL; c++) {
2563 if (binary->header.typecookie == c->cookie
2564 && binary->header.cmd == c->cmd)
2567 if (c->name == NULL) {
2574 /* Convert command name to ASCII */
2575 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
2578 /* Convert command arguments to ASCII */
2579 argstype = (binary->header.flags & NGF_RESP) ?
2580 c->respType : c->mesgType;
2581 if (argstype == NULL) {
2582 *ascii->data = '\0';
2584 if ((error = ng_unparse(argstype,
2585 (u_char *)binary->data,
2586 ascii->data, bufSize)) != 0) {
2592 /* Return the result as struct ng_mesg plus ASCII string */
2593 bufSize = strlen(ascii->data) + 1;
2594 ascii->header.arglen = bufSize;
2595 resp->header.arglen = sizeof(*ascii) + bufSize;
2599 case NGM_ASCII2BINARY:
2601 int bufSize = 2000; /* XXX hard coded constant */
2602 const struct ng_cmdlist *c;
2603 const struct ng_parse_type *argstype;
2604 struct ng_mesg *ascii, *binary;
2607 /* Data area must contain at least a struct ng_mesg + '\0' */
2608 ascii = (struct ng_mesg *)msg->data;
2609 if ((msg->header.arglen < sizeof(*ascii) + 1) ||
2610 (ascii->header.arglen < 1) ||
2611 (msg->header.arglen < sizeof(*ascii) +
2612 ascii->header.arglen)) {
2617 ascii->data[ascii->header.arglen - 1] = '\0';
2619 /* Get a response message with lots of room */
2620 NG_MKRESPONSE(resp, msg, sizeof(*binary) + bufSize, M_WAITOK | M_NULLOK);
2625 binary = (struct ng_mesg *)resp->data;
2627 /* Copy ASCII message header to response message payload */
2628 bcopy(ascii, binary, sizeof(*ascii));
2630 /* Find command by matching ASCII command string */
2631 for (c = here->nd_type->cmdlist;
2632 c != NULL && c->name != NULL; c++) {
2633 if (strcmp(ascii->header.cmdstr, c->name) == 0)
2636 if (c == NULL || c->name == NULL) {
2637 for (c = ng_generic_cmds; c->name != NULL; c++) {
2638 if (strcmp(ascii->header.cmdstr, c->name) == 0)
2641 if (c->name == NULL) {
2648 /* Convert command name to binary */
2649 binary->header.cmd = c->cmd;
2650 binary->header.typecookie = c->cookie;
2652 /* Convert command arguments to binary */
2653 argstype = (binary->header.flags & NGF_RESP) ?
2654 c->respType : c->mesgType;
2655 if (argstype == NULL) {
2658 if ((error = ng_parse(argstype, ascii->data,
2659 &off, (u_char *)binary->data, &bufSize)) != 0) {
2665 /* Return the result */
2666 binary->header.arglen = bufSize;
2667 resp->header.arglen = sizeof(*binary) + bufSize;
2671 case NGM_TEXT_CONFIG:
2672 case NGM_TEXT_STATUS:
2674 * This one is tricky as it passes the command down to the
2675 * actual node, even though it is a generic type command.
2676 * This means we must assume that the item/msg is already freed
2677 * when control passes back to us.
2679 if (here->nd_type->rcvmsg != NULL) {
2680 NGI_MSG(item) = msg; /* put it back as we found it */
2681 return((*here->nd_type->rcvmsg)(here, item, lasthook));
2683 /* Fall through if rcvmsg not supported */
2689 * Sometimes a generic message may be statically allocated
2690 * to avoid problems with allocating when in tight memeory situations.
2691 * Don't free it if it is so.
2692 * I break them appart here, because erros may cause a free if the item
2693 * in which case we'd be doing it twice.
2694 * they are kept together above, to simplify freeing.
2697 NG_RESPOND_MSG(error, here, item, resp);
2703 /************************************************************************
2704 Queue element get/free routines
2705 ************************************************************************/
2707 uma_zone_t ng_qzone;
2708 uma_zone_t ng_qdzone;
2709 static int maxalloc = 4096;/* limit the damage of a leak */
2710 static int maxdata = 512; /* limit the damage of a DoS */
2712 TUNABLE_INT("net.graph.maxalloc", &maxalloc);
2713 SYSCTL_INT(_net_graph, OID_AUTO, maxalloc, CTLFLAG_RDTUN, &maxalloc,
2714 0, "Maximum number of non-data queue items to allocate");
2715 TUNABLE_INT("net.graph.maxdata", &maxdata);
2716 SYSCTL_INT(_net_graph, OID_AUTO, maxdata, CTLFLAG_RDTUN, &maxdata,
2717 0, "Maximum number of data queue items to allocate");
2720 * Get a queue entry.
2721 * This is usually called when a packet first enters netgraph.
2722 * By definition, this is usually from an interrupt, or from a user.
2723 * Users are not so important, but try be quick for the times that it's
2726 static __inline item_p
2727 ng_alloc_item(int type, int flags)
2731 KASSERT(((type & ~NGQF_TYPE) == 0),
2732 ("%s: incorrect item type: %d", __func__, type));
2734 item = uma_zalloc((type == NGQF_DATA)?ng_qdzone:ng_qzone,
2735 (flags & NG_WAITOK) ? M_WAITOK : M_NOWAIT );
2738 item->el_flags = type;
2745 * Release a queue entry
2748 ng_free_item(item_p item)
2751 * The item may hold resources on it's own. We need to free
2752 * these before we can free the item. What they are depends upon
2753 * what kind of item it is. it is important that nodes zero
2754 * out pointers to resources that they remove from the item
2755 * or we release them again here.
2757 switch (item->el_flags & NGQF_TYPE) {
2759 /* If we have an mbuf still attached.. */
2760 NG_FREE_M(_NGI_M(item));
2763 _NGI_RETADDR(item) = 0;
2764 NG_FREE_MSG(_NGI_MSG(item));
2768 /* nothing to free really, */
2769 _NGI_FN(item) = NULL;
2770 _NGI_ARG1(item) = NULL;
2771 _NGI_ARG2(item) = 0;
2774 /* If we still have a node or hook referenced... */
2775 _NGI_CLR_NODE(item);
2776 _NGI_CLR_HOOK(item);
2778 uma_zfree(((item->el_flags & NGQF_TYPE) == NGQF_DATA)?
2779 ng_qdzone:ng_qzone, item);
2783 * Change type of the queue entry.
2784 * Possibly reallocates it from another UMA zone.
2786 static __inline item_p
2787 ng_realloc_item(item_p pitem, int type, int flags)
2792 KASSERT((pitem != NULL), ("%s: can't reallocate NULL", __func__));
2793 KASSERT(((type & ~NGQF_TYPE) == 0),
2794 ("%s: incorrect item type: %d", __func__, type));
2796 from = ((pitem->el_flags & NGQF_TYPE) == NGQF_DATA);
2797 to = (type == NGQF_DATA);
2799 /* If reallocation is required do it and copy item. */
2800 if ((item = ng_alloc_item(type, flags)) == NULL) {
2801 ng_free_item(pitem);
2805 ng_free_item(pitem);
2808 item->el_flags = (item->el_flags & ~NGQF_TYPE) | type;
2813 /************************************************************************
2815 ************************************************************************/
2818 * Handle the loading/unloading of a netgraph node type module
2821 ng_mod_event(module_t mod, int event, void *data)
2823 struct ng_type *const type = data;
2829 /* Register new netgraph node type */
2831 if ((error = ng_newtype(type)) != 0) {
2836 /* Call type specific code */
2837 if (type->mod_event != NULL)
2838 if ((error = (*type->mod_event)(mod, event, data))) {
2839 mtx_lock(&ng_typelist_mtx);
2840 type->refs--; /* undo it */
2841 LIST_REMOVE(type, types);
2842 mtx_unlock(&ng_typelist_mtx);
2849 if (type->refs > 1) { /* make sure no nodes exist! */
2852 if (type->refs == 0) {
2853 /* failed load, nothing to undo */
2857 if (type->mod_event != NULL) { /* check with type */
2858 error = (*type->mod_event)(mod, event, data);
2859 if (error != 0) { /* type refuses.. */
2864 mtx_lock(&ng_typelist_mtx);
2865 LIST_REMOVE(type, types);
2866 mtx_unlock(&ng_typelist_mtx);
2872 if (type->mod_event != NULL)
2873 error = (*type->mod_event)(mod, event, data);
2875 error = EOPNOTSUPP; /* XXX ? */
2882 * Handle loading and unloading for this code.
2883 * The only thing we need to link into is the NETISR strucure.
2886 ngb_mod_event(module_t mod, int event, void *data)
2892 /* Initialize everything. */
2893 NG_WORKLIST_LOCK_INIT();
2894 mtx_init(&ng_typelist_mtx);
2895 mtx_init(&ng_idhash_mtx);
2896 mtx_init(&ng_namehash_mtx);
2897 mtx_init(&ng_topo_mtx);
2898 ng_qzone = uma_zcreate("NetGraph items", sizeof(struct ng_item),
2899 NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
2900 uma_zone_set_max(ng_qzone, maxalloc);
2901 ng_qdzone = uma_zcreate("NetGraph data items", sizeof(struct ng_item),
2902 NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
2903 uma_zone_set_max(ng_qdzone, maxdata);
2906 /* You can't unload it because an interface may be using it. */
2916 static moduledata_t netgraph_mod = {
2921 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_NETGRAPH, SI_ORDER_MIDDLE);
2922 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
2923 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
2924 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
2926 /***********************************************************************
2928 **********************************************************************/
2929 /* NETGRAPH taskqueue routine
2931 * Pick a node off the list of nodes with work,
2932 * try get an item to process off it.
2933 * If there are no more, remove the node from the list.
2935 * This routine used to be a netisr but because no actual packets are
2936 * really sent to it, it has been converted to a taskqueue.
2939 ngtask(void *context, int pending)
2944 /* Get node from the worklist. */
2946 node = STAILQ_FIRST(&ng_worklist);
2948 NG_WORKLIST_UNLOCK();
2951 STAILQ_REMOVE_HEAD(&ng_worklist, nd_input_queue.q_work);
2952 NG_WORKLIST_UNLOCK();
2953 CTR3(KTR_NET, "%20s: node [%x] (%p) taken off worklist",
2954 __func__, node->nd_ID, node);
2956 * We have the node. We also take over the reference
2957 * that the list had on it.
2958 * Now process as much as you can, until it won't
2959 * let you have another item off the queue.
2960 * All this time, keep the reference
2961 * that lets us be sure that the node still exists.
2962 * Let the reference go at the last minute.
2968 NG_QUEUE_LOCK(&node->nd_input_queue);
2969 item = ng_dequeue(node, &rw);
2971 node->nd_input_queue.q_flags2 &= ~NGQ2_WORKQ;
2972 NG_QUEUE_UNLOCK(&node->nd_input_queue);
2973 break; /* go look for another node */
2975 NG_QUEUE_UNLOCK(&node->nd_input_queue);
2976 NGI_GET_NODE(item, node); /* zaps stored node */
2977 ng_apply_item(node, item, rw);
2978 NG_NODE_UNREF(node);
2981 NG_NODE_UNREF(node);
2987 * It's posible that a debugging NG_NODE_REF may need
2988 * to be outside the mutex zone
2991 ng_worklist_add(node_p node)
2994 KKASSERT(mtx_owned(&node->nd_input_queue.q_mtx));
2996 if ((node->nd_input_queue.q_flags2 & NGQ2_WORKQ) == 0) {
2997 static struct task ng_task;
3000 * If we are not already on the work queue,
3003 node->nd_input_queue.q_flags2 |= NGQ2_WORKQ;
3004 NG_NODE_REF(node); /* XXX fafe in mutex? */
3006 STAILQ_INSERT_TAIL(&ng_worklist, node, nd_input_queue.q_work);
3007 NG_WORKLIST_UNLOCK();
3008 TASK_INIT(&ng_task, 0, ngtask, NULL);
3009 taskqueue_enqueue(taskqueue_swi, &ng_task);
3010 CTR3(KTR_NET, "%20s: node [%x] (%p) put on worklist", __func__,
3013 CTR3(KTR_NET, "%20s: node [%x] (%p) already on worklist",
3014 __func__, node->nd_ID, node);
3019 /***********************************************************************
3020 * Externally useable functions to set up a queue item ready for sending
3021 ***********************************************************************/
3024 * Put mbuf into the item.
3025 * Hook and node references will be removed when the item is dequeued.
3027 * (XXX) Unsafe because no reference held by peer on remote node.
3028 * remote node might go away in this timescale.
3029 * We know the hooks can't go away because that would require getting
3030 * a writer item on both nodes and we must have at least a reader
3031 * here to be able to do this.
3032 * Note that the hook loaded is the REMOTE hook.
3034 * This is possibly in the critical path for new data.
3037 ng_package_data(struct mbuf *m, int flags)
3041 if ((item = ng_alloc_item(NGQF_DATA, flags)) == NULL) {
3045 item->el_flags |= NGQF_READER;
3051 * Allocate a queue item and put items into it..
3052 * Evaluate the address as this will be needed to queue it and
3053 * to work out what some of the fields should be.
3054 * Hook and node references will be removed when the item is dequeued.
3058 ng_package_msg(struct ng_mesg *msg, int flags)
3062 if ((item = ng_alloc_item(NGQF_MESG, flags)) == NULL) {
3066 /* Messages items count as writers unless explicitly exempted. */
3067 if (msg->header.cmd & NGM_READONLY)
3068 item->el_flags |= NGQF_READER;
3070 item->el_flags |= NGQF_WRITER;
3072 * Set the current lasthook into the queue item
3074 NGI_MSG(item) = msg;
3075 NGI_RETADDR(item) = 0;
3081 #define SET_RETADDR(item, here, retaddr) \
3082 do { /* Data or fn items don't have retaddrs */ \
3083 if ((item->el_flags & NGQF_TYPE) == NGQF_MESG) { \
3085 NGI_RETADDR(item) = retaddr; \
3088 * The old return address should be ok. \
3089 * If there isn't one, use the address \
3092 if (NGI_RETADDR(item) == 0) { \
3094 = ng_node2ID(here); \
3101 ng_address_hook(node_p here, item_p item, hook_p hook, ng_ID_t retaddr)
3106 * Quick sanity check..
3107 * Since a hook holds a reference on it's node, once we know
3108 * that the peer is still connected (even if invalid,) we know
3109 * that the peer node is present, though maybe invalid.
3111 if ((hook == NULL) ||
3112 NG_HOOK_NOT_VALID(hook) ||
3113 NG_HOOK_NOT_VALID(peer = NG_HOOK_PEER(hook)) ||
3114 NG_NODE_NOT_VALID(peernode = NG_PEER_NODE(hook))) {
3121 * Transfer our interest to the other (peer) end.
3124 NG_NODE_REF(peernode);
3125 NGI_SET_HOOK(item, peer);
3126 NGI_SET_NODE(item, peernode);
3127 SET_RETADDR(item, here, retaddr);
3132 ng_address_path(node_p here, item_p item, char *address, ng_ID_t retaddr)
3139 * Note that ng_path2noderef increments the reference count
3140 * on the node for us if it finds one. So we don't have to.
3142 error = ng_path2noderef(here, address, &dest, &hook);
3147 NGI_SET_NODE(item, dest);
3149 NG_HOOK_REF(hook); /* don't let it go while on the queue */
3150 NGI_SET_HOOK(item, hook);
3152 SET_RETADDR(item, here, retaddr);
3157 ng_address_ID(node_p here, item_p item, ng_ID_t ID, ng_ID_t retaddr)
3162 * Find the target node.
3164 dest = ng_ID2noderef(ID); /* GETS REFERENCE! */
3170 /* Fill out the contents */
3171 NGI_SET_NODE(item, dest);
3173 SET_RETADDR(item, here, retaddr);
3178 * special case to send a message to self (e.g. destroy node)
3179 * Possibly indicate an arrival hook too.
3180 * Useful for removing that hook :-)
3183 ng_package_msg_self(node_p here, hook_p hook, struct ng_mesg *msg)
3188 * Find the target node.
3189 * If there is a HOOK argument, then use that in preference
3192 if ((item = ng_alloc_item(NGQF_MESG, NG_NOFLAGS)) == NULL) {
3197 /* Fill out the contents */
3198 item->el_flags |= NGQF_WRITER;
3200 NGI_SET_NODE(item, here);
3203 NGI_SET_HOOK(item, hook);
3205 NGI_MSG(item) = msg;
3206 NGI_RETADDR(item) = ng_node2ID(here);
3211 * Send ng_item_fn function call to the specified node.
3215 ng_send_fn(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2)
3218 return ng_send_fn1(node, hook, fn, arg1, arg2, NG_NOFLAGS);
3222 ng_send_fn1(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2,
3227 if ((item = ng_alloc_item(NGQF_FN, flags)) == NULL) {
3230 item->el_flags |= NGQF_WRITER;
3231 NG_NODE_REF(node); /* and one for the item */
3232 NGI_SET_NODE(item, node);
3235 NGI_SET_HOOK(item, hook);
3238 NGI_ARG1(item) = arg1;
3239 NGI_ARG2(item) = arg2;
3240 return(ng_snd_item(item, flags));
3244 * Send ng_item_fn2 function call to the specified node.
3246 * If an optional pitem parameter is supplied, its apply
3247 * callback will be copied to the new item. If also NG_REUSE_ITEM
3248 * flag is set, no new item will be allocated, but pitem will
3252 ng_send_fn2(node_p node, hook_p hook, item_p pitem, ng_item_fn2 *fn, void *arg1,
3253 int arg2, int flags)
3257 KASSERT((pitem != NULL || (flags & NG_REUSE_ITEM) == 0),
3258 ("%s: NG_REUSE_ITEM but no pitem", __func__));
3261 * Allocate a new item if no supplied or
3262 * if we can't use supplied one.
3264 if (pitem == NULL || (flags & NG_REUSE_ITEM) == 0) {
3265 if ((item = ng_alloc_item(NGQF_FN2, flags)) == NULL)
3268 item->apply = pitem->apply;
3270 if ((item = ng_realloc_item(pitem, NGQF_FN2, flags)) == NULL)
3274 item->el_flags = (item->el_flags & ~NGQF_RW) | NGQF_WRITER;
3275 NG_NODE_REF(node); /* and one for the item */
3276 NGI_SET_NODE(item, node);
3279 NGI_SET_HOOK(item, hook);
3282 NGI_ARG1(item) = arg1;
3283 NGI_ARG2(item) = arg2;
3284 return(ng_snd_item(item, flags));
3288 * Official timeout routines for Netgraph nodes.
3291 ng_callout_trampoline(void *arg)
3295 ng_snd_item(item, 0);
3300 ng_callout(struct callout *c, node_p node, hook_p hook, int ticks,
3301 ng_item_fn *fn, void * arg1, int arg2)
3305 if ((item = ng_alloc_item(NGQF_FN, NG_NOFLAGS)) == NULL)
3308 item->el_flags |= NGQF_WRITER;
3309 NG_NODE_REF(node); /* and one for the item */
3310 NGI_SET_NODE(item, node);
3313 NGI_SET_HOOK(item, hook);
3316 NGI_ARG1(item) = arg1;
3317 NGI_ARG2(item) = arg2;
3319 callout_reset(c, ticks, &ng_callout_trampoline, item);
3323 /* A special modified version of untimeout() */
3325 ng_uncallout(struct callout *c, node_p node)
3330 KASSERT(c != NULL, ("ng_uncallout: NULL callout"));
3331 KASSERT(node != NULL, ("ng_uncallout: NULL node"));
3333 rval = callout_stop(c);
3335 /* Do an extra check */
3336 if ((rval > 0) && (c->c_func == &ng_callout_trampoline) &&
3337 (NGI_NODE(item) == node)) {
3339 * We successfully removed it from the queue before it ran
3340 * So now we need to unreference everything that was
3341 * given extra references. (NG_FREE_ITEM does this).
3351 * Set the address, if none given, give the node here.
3354 ng_replace_retaddr(node_p here, item_p item, ng_ID_t retaddr)
3357 NGI_RETADDR(item) = retaddr;
3360 * The old return address should be ok.
3361 * If there isn't one, use the address here.
3363 NGI_RETADDR(item) = ng_node2ID(here);
3368 bzero_ctor(void *obj, void *private, int ocflags)
3370 struct ng_item *i = obj;
3372 bzero(i, sizeof(struct ng_item));
3378 /* just test all the macros */
3380 ng_macro_test(item_p item);
3382 ng_macro_test(item_p item)
3387 struct ng_mesg *msg;
3392 NGI_GET_MSG(item, msg);
3393 retaddr = NGI_RETADDR(item);
3394 NG_SEND_DATA(error, hook, m, NULL);
3395 NG_SEND_DATA_ONLY(error, hook, m);
3396 NG_FWD_NEW_DATA(error, item, hook, m);
3397 NG_FWD_ITEM_HOOK(error, item, hook);
3398 NG_SEND_MSG_HOOK(error, node, msg, hook, retaddr);
3399 NG_SEND_MSG_ID(error, node, msg, retaddr, retaddr);
3400 NG_SEND_MSG_PATH(error, node, msg, ".:", retaddr);
3401 NG_FWD_MSG_HOOK(error, node, item, hook, retaddr);
3403 #endif /* TESTING */