5 * Copyright (c) 1996-1999 Whistle Communications, Inc.
8 * Subject to the following obligations and disclaimer of warranty, use and
9 * redistribution of this software, in source or object code forms, with or
10 * without modifications are expressly permitted by Whistle Communications;
11 * provided, however, that:
12 * 1. Any and all reproductions of the source or object code must include the
13 * copyright notice above and the following disclaimer of warranties; and
14 * 2. No rights are granted, in any manner or form, to use Whistle
15 * Communications, Inc. trademarks, including the mark "WHISTLE
16 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17 * such appears in the above copyright notice or in the software.
19 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
37 * Authors: Julian Elischer <julian@freebsd.org>
38 * Archie Cobbs <archie@freebsd.org>
40 * $FreeBSD: src/sys/netgraph/ng_base.c,v 1.11.2.17 2002/07/02 23:44:02 archie Exp $
41 * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
45 * This file implements the base netgraph code.
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/errno.h>
51 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/syslog.h>
54 #include <sys/linker.h>
55 #include <sys/queue.h>
57 #include <sys/ctype.h>
58 #include <sys/sysctl.h>
59 #include <sys/vnode.h>
60 #include <machine/limits.h>
62 #include <sys/thread2.h>
63 #include <sys/msgport2.h>
64 #include <sys/mplock2.h>
66 #include <net/netisr.h>
68 #include <netgraph/ng_message.h>
69 #include <netgraph/netgraph.h>
70 #include <netgraph/ng_parse.h>
72 MODULE_VERSION(netgraph, NG_ABI_VERSION);
76 /* List of all nodes */
77 static LIST_HEAD(, ng_node) nodelist;
79 /* List of installed types */
80 static LIST_HEAD(, ng_type) typelist;
82 /* Hash releted definitions */
83 #define ID_HASH_SIZE 32 /* most systems wont need even this many */
84 static LIST_HEAD(, ng_node) ID_hash[ID_HASH_SIZE];
85 /* Don't nead to initialise them because it's a LIST */
87 /* Internal functions */
88 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
89 static int ng_connect(hook_p hook1, hook_p hook2);
90 static void ng_disconnect_hook(hook_p hook);
91 static int ng_generic_msg(node_p here, struct ng_mesg *msg,
92 const char *retaddr, struct ng_mesg ** resp);
93 static ng_ID_t ng_decodeidname(const char *name);
94 static int ngb_mod_event(module_t mod, int event, void *data);
95 static void ngintr(union netmsg *);
96 static int ng_load_module(const char *);
98 /* Our own netgraph malloc type */
99 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
101 /* Set this to Debugger("X") to catch all errors as they occur */
106 static ng_ID_t nextID = 1;
109 #define CHECK_DATA_MBUF(m) do { \
113 if (((m)->m_flags & M_PKTHDR) == 0) \
114 panic("%s: !PKTHDR", __func__); \
115 for (total = 0, n = (m); n != NULL; n = n->m_next) \
117 if ((m)->m_pkthdr.len != total) { \
118 panic("%s: %d != %d", \
119 __func__, (m)->m_pkthdr.len, total); \
123 #define CHECK_DATA_MBUF(m)
127 /************************************************************************
128 Parse type definitions for generic messages
129 ************************************************************************/
131 /* Handy structure parse type defining macro */
132 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
133 static const struct ng_parse_struct_field \
134 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
135 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
136 &ng_parse_struct_type, \
137 &ng_ ## lo ## _type_fields \
140 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
141 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
142 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
143 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
144 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
145 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
146 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
148 /* Get length of an array when the length is stored as a 32 bit
149 value immediately preceeding the array -- as with struct namelist
150 and struct typelist. */
152 ng_generic_list_getLength(const struct ng_parse_type *type,
153 const u_char *start, const u_char *buf)
155 return *((const u_int32_t *)(buf - 4));
158 /* Get length of the array of struct linkinfo inside a struct hooklist */
160 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
161 const u_char *start, const u_char *buf)
163 const struct hooklist *hl = (const struct hooklist *)start;
165 return hl->nodeinfo.hooks;
168 /* Array type for a variable length array of struct namelist */
169 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
170 &ng_generic_nodeinfo_type,
171 &ng_generic_list_getLength
173 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
174 &ng_parse_array_type,
175 &ng_nodeinfoarray_type_info
178 /* Array type for a variable length array of struct typelist */
179 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
180 &ng_generic_typeinfo_type,
181 &ng_generic_list_getLength
183 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
184 &ng_parse_array_type,
185 &ng_typeinfoarray_type_info
188 /* Array type for array of struct linkinfo in struct hooklist */
189 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
190 &ng_generic_linkinfo_type,
191 &ng_generic_linkinfo_getLength
193 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
194 &ng_parse_array_type,
195 &ng_generic_linkinfo_array_type_info
198 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
199 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
200 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
201 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
202 (&ng_generic_nodeinfoarray_type));
204 /* List of commands and how to convert arguments to/from ASCII */
205 static const struct ng_cmdlist ng_generic_cmds[] = {
217 &ng_generic_mkpeer_type,
224 &ng_generic_connect_type,
231 &ng_generic_name_type,
238 &ng_generic_rmhook_type,
246 &ng_generic_nodeinfo_type
253 &ng_generic_hooklist_type
260 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
267 &ng_generic_listnodes_type
274 &ng_generic_typeinfo_type
281 &ng_parse_string_type
288 &ng_parse_string_type
294 &ng_parse_ng_mesg_type,
295 &ng_parse_ng_mesg_type
301 &ng_parse_ng_mesg_type,
302 &ng_parse_ng_mesg_type
307 /************************************************************************
309 ************************************************************************/
312 linker_api_available(void)
314 /* linker_* API won't work without a process context */
318 * nlookup_init() relies on namei_oc to be initialized,
319 * but it's not when the netgraph module is loaded during boot.
321 if (namei_oc == NULL)
327 ng_load_module(const char *name)
329 char *path, filename[NG_TYPESIZ + 3];
333 if (!linker_api_available())
336 /* Not found, try to load it as a loadable module */
337 ksnprintf(filename, sizeof(filename), "ng_%s.ko", name);
338 if ((path = linker_search_path(filename)) == NULL)
340 error = linker_load_file(path, &lf);
341 kfree(path, M_LINKER);
343 lf->userrefs++; /* pretend kldload'ed */
348 * Instantiate a node of the requested type
351 ng_make_node(const char *typename, node_p *nodepp)
353 struct ng_type *type;
355 /* Check that the type makes sense */
356 if (typename == NULL) {
361 /* Locate the node type */
362 if ((type = ng_findtype(typename)) == NULL)
365 /* Call the constructor */
366 if (type->constructor != NULL)
367 return ((*type->constructor)(nodepp));
369 return (ng_make_node_common(type, nodepp));
373 * Generic node creation. Called by node constructors.
374 * The returned node has a reference count of 1.
377 ng_make_node_common(struct ng_type *type, node_p *nodepp)
381 /* Require the node type to have been already installed */
382 if (ng_findtype(type->name) == NULL) {
387 /* Make a node and try attach it to the type */
388 node = kmalloc(sizeof(*node), M_NETGRAPH, M_NOWAIT | M_ZERO);
394 node->refs++; /* note reference */
397 /* Link us into the node linked list */
398 LIST_INSERT_HEAD(&nodelist, node, nodes);
400 /* Initialize hook list for new node */
401 LIST_INIT(&node->hooks);
403 /* get an ID and put us in the hash chain */
404 node->ID = nextID++; /* 137 per second for 1 year before wrap */
405 LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
413 * Forceably start the shutdown process on a node. Either call
414 * it's shutdown method, or do the default shutdown if there is
415 * no type-specific method.
417 * Persistent nodes must have a type-specific method which
418 * resets the NG_INVALID flag.
421 ng_rmnode(node_p node)
423 /* Check if it's already shutting down */
424 if ((node->flags & NG_INVALID) != 0)
427 /* Add an extra reference so it doesn't go away during this */
430 /* Mark it invalid so any newcomers know not to try use it */
431 node->flags |= NG_INVALID;
433 /* Ask the type if it has anything to do in this case */
434 if (node->type && node->type->shutdown)
435 (*node->type->shutdown)(node);
436 else { /* do the default thing */
442 /* Remove extra reference, possibly the last */
447 * Called by the destructor to remove any STANDARD external references
450 ng_cutlinks(node_p node)
454 /* Make sure that this is set to stop infinite loops */
455 node->flags |= NG_INVALID;
457 /* If we have sleepers, wake them up; they'll see NG_INVALID */
461 /* Notify all remaining connected nodes to disconnect */
462 while ((hook = LIST_FIRST(&node->hooks)) != NULL)
463 ng_destroy_hook(hook);
467 * Remove a reference to the node, possibly the last
470 ng_unref(node_p node)
473 if (--node->refs <= 0) {
475 LIST_REMOVE(node, nodes);
476 LIST_REMOVE(node, idnodes);
477 kfree(node, M_NETGRAPH);
483 * Wait for a node to come ready. Returns a node with a reference count;
484 * don't forget to drop it when we are done with it using ng_release_node().
487 ng_wait_node(node_p node, char *msg)
495 node->refs++; /* the sleeping process counts as a reference */
496 while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
497 error = tsleep(node, PCATCH, msg, 0);
499 if (node->flags & NG_INVALID) {
503 KASSERT(node->refs > 1,
504 ("%s: refs=%d", __func__, node->refs));
505 node->flags |= NG_BUSY;
509 /* Release the reference we had on it */
516 * Release a node acquired via ng_wait_node()
519 ng_release_node(node_p node)
521 /* Declare that we don't want it */
522 node->flags &= ~NG_BUSY;
524 /* If we have sleepers, then wake them up */
528 /* We also have a reference.. drop it too */
532 /************************************************************************
534 ************************************************************************/
536 ng_ID2node(ng_ID_t ID)
539 LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
540 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
547 ng_node2ID(node_p node)
552 /************************************************************************
554 ************************************************************************/
557 * Assign a node a name. Once assigned, the name cannot be changed.
560 ng_name_node(node_p node, const char *name)
564 /* Check the name is valid */
565 for (i = 0; i < NG_NODESIZ; i++) {
566 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
569 if (i == 0 || name[i] != '\0') {
573 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
578 /* Check the node isn't already named */
579 if (node->name != NULL) {
584 /* Check the name isn't already being used */
585 if (ng_findname(node, name) != NULL) {
590 /* Allocate space and copy it */
591 node->name = kmalloc(strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
592 if (node->name == NULL) {
596 strcpy(node->name, name);
598 /* The name counts as a reference */
604 * Find a node by absolute name. The name should NOT end with ':'
605 * The name "." means "this node" and "[xxx]" means "the node
606 * with ID (ie, at address) xxx".
608 * Returns the node if found, else NULL.
611 ng_findname(node_p this, const char *name)
616 /* "." means "this node" */
617 if (strcmp(name, ".") == 0)
620 /* Check for name-by-ID */
621 if ((temp = ng_decodeidname(name)) != 0) {
622 return (ng_ID2node(temp));
625 /* Find node by name */
626 LIST_FOREACH(node, &nodelist, nodes) {
627 if ((node->name != NULL)
628 && (strcmp(node->name, name) == 0)
629 && ((node->flags & NG_INVALID) == 0))
636 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
637 * string is not valid, otherwise returns the value.
640 ng_decodeidname(const char *name)
642 const int len = strlen(name);
646 /* Check for proper length, brackets, no leading junk */
647 if (len < 3 || name[0] != '[' || name[len - 1] != ']'
648 || !isxdigit(name[1]))
652 val = strtoul(name + 1, &eptr, 16);
653 if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
659 * Remove a name from a node. This should only be called
660 * when shutting down and removing the node.
663 ng_unname(node_p node)
666 kfree(node->name, M_NETGRAPH);
672 /************************************************************************
675 Names are not optional. Hooks are always connected, except for a
676 brief moment within these routines.
678 ************************************************************************/
681 * Remove a hook reference
684 ng_unref_hook(hook_p hook)
687 if (--hook->refs == 0)
688 kfree(hook, M_NETGRAPH);
693 * Add an unconnected hook to a node. Only used internally.
696 ng_add_hook(node_p node, const char *name, hook_p *hookp)
701 /* Check that the given name is good */
706 if (ng_findhook(node, name) != NULL) {
711 /* Allocate the hook and link it up */
712 hook = kmalloc(sizeof(*hook), M_NETGRAPH, M_NOWAIT | M_ZERO);
718 hook->flags = HK_INVALID;
720 node->refs++; /* each hook counts as a reference */
722 /* Check if the node type code has something to say about it */
723 if (node->type->newhook != NULL)
724 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
728 * The 'type' agrees so far, so go ahead and link it in.
729 * We'll ask again later when we actually connect the hooks.
731 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
735 hook->name = kmalloc(strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
736 if (hook->name == NULL) {
738 LIST_REMOVE(hook, hooks);
743 ng_unref_hook(hook); /* this frees the hook */
746 strcpy(hook->name, name);
753 * Connect a pair of hooks. Only used internally.
756 ng_connect(hook_p hook1, hook_p hook2)
763 /* Give each node the opportunity to veto the impending connection */
764 if (hook1->node->type->connect) {
765 if ((error = (*hook1->node->type->connect) (hook1))) {
766 ng_destroy_hook(hook1); /* also zaps hook2 */
770 if (hook2->node->type->connect) {
771 if ((error = (*hook2->node->type->connect) (hook2))) {
772 ng_destroy_hook(hook2); /* also zaps hook1 */
776 hook1->flags &= ~HK_INVALID;
777 hook2->flags &= ~HK_INVALID;
784 * Node types may supply their own optimized routines for finding
785 * hooks. If none is supplied, we just do a linear search.
788 ng_findhook(node_p node, const char *name)
792 if (node->type->findhook != NULL)
793 return (*node->type->findhook)(node, name);
794 LIST_FOREACH(hook, &node->hooks, hooks) {
795 if (hook->name != NULL
796 && strcmp(hook->name, name) == 0
797 && (hook->flags & HK_INVALID) == 0)
806 * As hooks are always attached, this really destroys two hooks.
807 * The one given, and the one attached to it. Disconnect the hooks
808 * from each other first.
811 ng_destroy_hook(hook_p hook)
813 hook_p peer = hook->peer;
815 hook->flags |= HK_INVALID; /* as soon as possible */
817 peer->flags |= HK_INVALID; /* as soon as possible */
820 ng_disconnect_hook(peer);
822 ng_disconnect_hook(hook);
826 * Notify the node of the hook's demise. This may result in more actions
827 * (e.g. shutdown) but we don't do that ourselves and don't know what
828 * happens there. If there is no appropriate handler, then just remove it
829 * (and decrement the reference count of it's node which in turn might
830 * make something happen).
833 ng_disconnect_hook(hook_p hook)
835 node_p node = hook->node;
838 * Remove the hook from the node's list to avoid possible recursion
839 * in case the disconnection results in node shutdown.
841 LIST_REMOVE(hook, hooks);
843 if (node->type->disconnect) {
845 * The type handler may elect to destroy the peer so don't
846 * trust its existance after this point.
848 (*node->type->disconnect) (hook);
850 ng_unref(node); /* might be the last reference */
852 kfree(hook->name, M_NETGRAPH);
853 hook->node = NULL; /* may still be referenced elsewhere */
858 * Take two hooks on a node and merge the connection so that the given node
859 * is effectively bypassed.
862 ng_bypass(hook_p hook1, hook_p hook2)
864 if (hook1->node != hook2->node)
866 hook1->peer->peer = hook2->peer;
867 hook2->peer->peer = hook1->peer;
869 /* XXX If we ever cache methods on hooks update them as well */
872 ng_destroy_hook(hook1);
873 ng_destroy_hook(hook2);
878 * Install a new netgraph type
881 ng_newtype(struct ng_type *tp)
883 const size_t namelen = strlen(tp->name);
885 /* Check version and type name fields */
886 if (tp->version != NG_VERSION || namelen == 0 || namelen >= NG_TYPESIZ) {
891 /* Check for name collision */
892 if (ng_findtype(tp->name) != NULL) {
897 /* Link in new type */
898 LIST_INSERT_HEAD(&typelist, tp, types);
899 tp->refs = 1; /* first ref is linked list */
904 * Look for a type of the name given
907 ng_findtype(const char *typename)
909 struct ng_type *type;
911 LIST_FOREACH(type, &typelist, types) {
912 if (strcmp(type->name, typename) == 0)
919 /************************************************************************
921 ************************************************************************/
924 * Make a peer and connect. The order is arranged to minimise
925 * the work needed to back out in case of error.
928 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
935 if ((error = ng_add_hook(node, name, &hook)))
938 /* make sure we have the module needed */
939 if (ng_findtype(type) == NULL) {
940 /* Not found, try to load it as a loadable module */
941 error = ng_load_module(type);
943 kprintf("required netgraph module ng_%s not loaded\n",
948 if ((error = ng_make_node(type, &node2))) {
949 ng_destroy_hook(hook);
952 if ((error = ng_add_hook(node2, name2, &hook2))) {
954 ng_destroy_hook(hook);
959 * Actually link the two hooks together.. on failure they are
960 * destroyed so we don't have to do that here.
962 if ((error = ng_connect(hook, hook2)))
968 * Connect two nodes using the specified hooks
971 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
977 if ((error = ng_add_hook(node, name, &hook)))
979 if ((error = ng_add_hook(node2, name2, &hook2))) {
980 ng_destroy_hook(hook);
983 return (ng_connect(hook, hook2));
987 * Parse and verify a string of the form: <NODE:><PATH>
989 * Such a string can refer to a specific node or a specific hook
990 * on a specific node, depending on how you look at it. In the
991 * latter case, the PATH component must not end in a dot.
993 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
994 * of hook names separated by dots. This breaks out the original
995 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
996 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
997 * the final hook component of <PATH>, if any, otherwise NULL.
999 * This returns -1 if the path is malformed. The char ** are optional.
1003 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1005 char *node, *path, *hook;
1009 * Extract absolute NODE, if any
1011 for (path = addr; *path && *path != ':'; path++);
1013 node = addr; /* Here's the NODE */
1014 *path++ = '\0'; /* Here's the PATH */
1016 /* Node name must not be empty */
1020 /* A name of "." is OK; otherwise '.' not allowed */
1021 if (strcmp(node, ".") != 0) {
1022 for (k = 0; node[k]; k++)
1027 node = NULL; /* No absolute NODE */
1028 path = addr; /* Here's the PATH */
1031 /* Snoop for illegal characters in PATH */
1032 for (k = 0; path[k]; k++)
1036 /* Check for no repeated dots in PATH */
1037 for (k = 0; path[k]; k++)
1038 if (path[k] == '.' && path[k + 1] == '.')
1041 /* Remove extra (degenerate) dots from beginning or end of PATH */
1044 if (*path && path[strlen(path) - 1] == '.')
1045 path[strlen(path) - 1] = 0;
1047 /* If PATH has a dot, then we're not talking about a hook */
1049 for (hook = path, k = 0; path[k]; k++)
1050 if (path[k] == '.') {
1068 * Given a path, which may be absolute or relative, and a starting node,
1069 * return the destination node. Compute the "return address" if desired.
1072 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1074 const node_p start = here;
1075 char fullpath[NG_PATHSIZ];
1076 char *nodename, *path, pbuf[2];
1087 /* Make a writable copy of address for ng_path_parse() */
1088 strncpy(fullpath, address, sizeof(fullpath) - 1);
1089 fullpath[sizeof(fullpath) - 1] = '\0';
1091 /* Parse out node and sequence of hooks */
1092 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1097 pbuf[0] = '.'; /* Needs to be writable */
1102 /* For an absolute address, jump to the starting node */
1104 node = ng_findname(here, nodename);
1112 /* Now follow the sequence of hooks */
1113 for (cp = path; node != NULL && *cp != '\0'; ) {
1118 * Break out the next path segment. Replace the dot we just
1119 * found with a NUL; "cp" points to the next segment (or the
1122 for (segment = cp; *cp != '\0'; cp++) {
1130 if (*segment == '\0')
1133 /* We have a segment, so look for a hook by that name */
1134 hook = ng_findhook(node, segment);
1136 /* Can't get there from here... */
1138 || hook->peer == NULL
1139 || (hook->flags & HK_INVALID) != 0) {
1144 /* Hop on over to the next node */
1145 node = hook->peer->node;
1148 /* If node somehow missing, fail here (probably this is not needed) */
1154 /* Now compute return address, i.e., the path to the sender */
1156 *rtnp = kmalloc(NG_NODESIZ + 1, M_NETGRAPH, M_NOWAIT);
1157 if (*rtnp == NULL) {
1161 if (start->name != NULL)
1162 ksprintf(*rtnp, "%s:", start->name);
1164 ksprintf(*rtnp, "[%x]:", ng_node2ID(start));
1173 * Call the appropriate message handler for the object.
1174 * It is up to the message handler to free the message.
1175 * If it's a generic message, handle it generically, otherwise
1176 * call the type's message handler (if it exists)
1177 * XXX (race). Remember that a queued message may reference a node
1178 * or hook that has just been invalidated. It will exist
1179 * as the queue code is holding a reference, but..
1182 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1184 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1185 (error) = ng_generic_msg((node), (msg), \
1186 (retaddr), (resp)); \
1188 if ((node)->type->rcvmsg != NULL) { \
1189 (error) = (*(node)->type->rcvmsg)((node), \
1190 (msg), (retaddr), (resp)); \
1193 kfree((msg), M_NETGRAPH); \
1201 * Send a control message to a node
1204 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1205 struct ng_mesg **rptr)
1208 char *retaddr = NULL;
1211 /* Find the target node */
1212 error = ng_path2node(here, address, &dest, &retaddr);
1214 kfree(msg, M_NETGRAPH);
1218 /* Make sure the resp field is null before we start */
1222 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1224 /* Make sure that if there is a response, it has the RESP bit set */
1225 if ((error == 0) && rptr && *rptr)
1226 (*rptr)->header.flags |= NGF_RESP;
1229 * If we had a return address it is up to us to free it. They should
1230 * have taken a copy if they needed to make a delayed response.
1233 kfree(retaddr, M_NETGRAPH);
1238 * Implement the 'generic' control messages
1241 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1242 struct ng_mesg **resp)
1246 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1248 kfree(msg, M_NETGRAPH);
1251 switch (msg->header.cmd) {
1257 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1259 if (msg->header.arglen != sizeof(*mkp)) {
1263 mkp->type[sizeof(mkp->type) - 1] = '\0';
1264 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1265 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1266 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1271 struct ngm_connect *const con =
1272 (struct ngm_connect *) msg->data;
1275 if (msg->header.arglen != sizeof(*con)) {
1279 con->path[sizeof(con->path) - 1] = '\0';
1280 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1281 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1282 error = ng_path2node(here, con->path, &node2, NULL);
1285 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1290 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1292 if (msg->header.arglen != sizeof(*nam)) {
1296 nam->name[sizeof(nam->name) - 1] = '\0';
1297 error = ng_name_node(here, nam->name);
1302 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1305 if (msg->header.arglen != sizeof(*rmh)) {
1309 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1310 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1311 ng_destroy_hook(hook);
1316 struct nodeinfo *ni;
1319 /* Get response struct */
1324 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1330 /* Fill in node info */
1331 ni = (struct nodeinfo *) rp->data;
1332 if (here->name != NULL)
1333 strlcpy(ni->name, here->name, NG_NODESIZ);
1334 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1335 ni->id = ng_node2ID(here);
1336 ni->hooks = here->numhooks;
1342 const int nhooks = here->numhooks;
1343 struct hooklist *hl;
1344 struct nodeinfo *ni;
1348 /* Get response struct */
1353 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1354 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1359 hl = (struct hooklist *) rp->data;
1362 /* Fill in node info */
1364 strlcpy(ni->name, here->name, NG_NODESIZ);
1365 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1366 ni->id = ng_node2ID(here);
1368 /* Cycle through the linked list of hooks */
1370 LIST_FOREACH(hook, &here->hooks, hooks) {
1371 struct linkinfo *const link = &hl->link[ni->hooks];
1373 if (ni->hooks >= nhooks) {
1374 log(LOG_ERR, "%s: number of %s changed\n",
1378 if ((hook->flags & HK_INVALID) != 0)
1380 strlcpy(link->ourhook, hook->name, NG_HOOKSIZ);
1381 strlcpy(link->peerhook, hook->peer->name, NG_HOOKSIZ);
1382 if (hook->peer->node->name != NULL)
1383 strlcpy(link->nodeinfo.name,
1384 hook->peer->node->name, NG_NODESIZ);
1385 strlcpy(link->nodeinfo.type,
1386 hook->peer->node->type->name, NG_TYPESIZ);
1387 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1388 link->nodeinfo.hooks = hook->peer->node->numhooks;
1398 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1399 struct namelist *nl;
1409 /* Count number of nodes */
1410 LIST_FOREACH(node, &nodelist, nodes) {
1411 if ((node->flags & NG_INVALID) == 0
1412 && (unnamed || node->name != NULL))
1416 /* Get response struct */
1421 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1422 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1427 nl = (struct namelist *) rp->data;
1429 /* Cycle through the linked list of nodes */
1431 LIST_FOREACH(node, &nodelist, nodes) {
1432 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1434 if (nl->numnames >= num) {
1435 log(LOG_ERR, "%s: number of %s changed\n",
1439 if ((node->flags & NG_INVALID) != 0)
1441 if (!unnamed && node->name == NULL)
1443 if (node->name != NULL)
1444 strlcpy(np->name, node->name, NG_NODESIZ);
1445 strlcpy(np->type, node->type->name, NG_TYPESIZ);
1446 np->id = ng_node2ID(node);
1447 np->hooks = node->numhooks;
1456 struct typelist *tl;
1458 struct ng_type *type;
1466 /* Count number of types */
1467 LIST_FOREACH(type, &typelist, types)
1470 /* Get response struct */
1475 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1476 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1481 tl = (struct typelist *) rp->data;
1483 /* Cycle through the linked list of types */
1485 LIST_FOREACH(type, &typelist, types) {
1486 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1488 if (tl->numtypes >= num) {
1489 log(LOG_ERR, "%s: number of %s changed\n",
1493 strlcpy(tp->type_name, type->name, NG_TYPESIZ);
1494 tp->numnodes = type->refs - 1; /* don't count list */
1501 case NGM_BINARY2ASCII:
1503 int bufSize = 20 * 1024; /* XXX hard coded constant */
1504 const struct ng_parse_type *argstype;
1505 const struct ng_cmdlist *c;
1506 struct ng_mesg *rp, *binary, *ascii;
1508 /* Data area must contain a valid netgraph message */
1509 binary = (struct ng_mesg *)msg->data;
1510 if (msg->header.arglen < sizeof(struct ng_mesg)
1511 || msg->header.arglen - sizeof(struct ng_mesg)
1512 < binary->header.arglen) {
1517 /* Get a response message with lots of room */
1518 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1523 ascii = (struct ng_mesg *)rp->data;
1525 /* Copy binary message header to response message payload */
1526 bcopy(binary, ascii, sizeof(*binary));
1528 /* Find command by matching typecookie and command number */
1529 for (c = here->type->cmdlist;
1530 c != NULL && c->name != NULL; c++) {
1531 if (binary->header.typecookie == c->cookie
1532 && binary->header.cmd == c->cmd)
1535 if (c == NULL || c->name == NULL) {
1536 for (c = ng_generic_cmds; c->name != NULL; c++) {
1537 if (binary->header.typecookie == c->cookie
1538 && binary->header.cmd == c->cmd)
1541 if (c->name == NULL) {
1542 kfree(rp, M_NETGRAPH);
1548 /* Convert command name to ASCII */
1549 ksnprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1552 /* Convert command arguments to ASCII */
1553 argstype = (binary->header.flags & NGF_RESP) ?
1554 c->respType : c->mesgType;
1555 if (argstype == NULL)
1556 *ascii->data = '\0';
1558 if ((error = ng_unparse(argstype,
1559 (u_char *)binary->data,
1560 ascii->data, bufSize)) != 0) {
1561 kfree(rp, M_NETGRAPH);
1566 /* Return the result as struct ng_mesg plus ASCII string */
1567 bufSize = strlen(ascii->data) + 1;
1568 ascii->header.arglen = bufSize;
1569 rp->header.arglen = sizeof(*ascii) + bufSize;
1574 case NGM_ASCII2BINARY:
1576 int bufSize = 2000; /* XXX hard coded constant */
1577 const struct ng_cmdlist *c;
1578 const struct ng_parse_type *argstype;
1579 struct ng_mesg *rp, *ascii, *binary;
1582 /* Data area must contain at least a struct ng_mesg + '\0' */
1583 ascii = (struct ng_mesg *)msg->data;
1584 if (msg->header.arglen < sizeof(*ascii) + 1
1585 || ascii->header.arglen < 1
1586 || msg->header.arglen
1587 < sizeof(*ascii) + ascii->header.arglen) {
1591 ascii->data[ascii->header.arglen - 1] = '\0';
1593 /* Get a response message with lots of room */
1594 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1599 binary = (struct ng_mesg *)rp->data;
1601 /* Copy ASCII message header to response message payload */
1602 bcopy(ascii, binary, sizeof(*ascii));
1604 /* Find command by matching ASCII command string */
1605 for (c = here->type->cmdlist;
1606 c != NULL && c->name != NULL; c++) {
1607 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1610 if (c == NULL || c->name == NULL) {
1611 for (c = ng_generic_cmds; c->name != NULL; c++) {
1612 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1615 if (c->name == NULL) {
1616 kfree(rp, M_NETGRAPH);
1622 /* Convert command name to binary */
1623 binary->header.cmd = c->cmd;
1624 binary->header.typecookie = c->cookie;
1626 /* Convert command arguments to binary */
1627 argstype = (binary->header.flags & NGF_RESP) ?
1628 c->respType : c->mesgType;
1629 if (argstype == NULL)
1632 if ((error = ng_parse(argstype, ascii->data,
1633 &off, (u_char *)binary->data, &bufSize)) != 0) {
1634 kfree(rp, M_NETGRAPH);
1639 /* Return the result */
1640 binary->header.arglen = bufSize;
1641 rp->header.arglen = sizeof(*binary) + bufSize;
1646 case NGM_TEXT_CONFIG:
1647 case NGM_TEXT_STATUS:
1649 * This one is tricky as it passes the command down to the
1650 * actual node, even though it is a generic type command.
1651 * This means we must assume that the msg is already freed
1652 * when control passes back to us.
1658 if (here->type->rcvmsg != NULL)
1659 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1660 /* Fall through if rcvmsg not supported */
1665 kfree(msg, M_NETGRAPH);
1670 * Send a data packet to a node. If the recipient has no
1671 * 'receive data' method, then silently discard the packet.
1674 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1676 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1680 if (hook && (hook->flags & HK_INVALID) == 0) {
1681 rcvdata = hook->peer->node->type->rcvdata;
1682 if (rcvdata != NULL)
1683 error = (*rcvdata)(hook->peer, m, meta);
1686 NG_FREE_DATA(m, meta);
1691 NG_FREE_DATA(m, meta);
1697 * Send a queued data packet to a node. If the recipient has no
1698 * 'receive queued data' method, then try the 'receive data' method above.
1701 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1703 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1707 if (hook && (hook->flags & HK_INVALID) == 0) {
1708 rcvdataq = hook->peer->node->type->rcvdataq;
1709 if (rcvdataq != NULL)
1710 error = (*rcvdataq)(hook->peer, m, meta);
1712 error = ng_send_data(hook, m, meta);
1717 NG_FREE_DATA(m, meta);
1725 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1728 ng_copy_meta(meta_p meta)
1734 meta2 = kmalloc(meta->used_len, M_NETGRAPH, M_NOWAIT);
1737 meta2->allocated_len = meta->used_len;
1738 bcopy(meta, meta2, meta->used_len);
1742 /************************************************************************
1744 ************************************************************************/
1747 * Handle the loading/unloading of a netgraph node type module
1750 ng_mod_event(module_t mod, int event, void *data)
1752 struct ng_type *const type = data;
1758 /* Register new netgraph node type */
1760 if ((error = ng_newtype(type)) != 0) {
1765 /* Call type specific code */
1766 if (type->mod_event != NULL)
1767 if ((error = (*type->mod_event)(mod, event, data))) {
1768 type->refs--; /* undo it */
1769 LIST_REMOVE(type, types);
1776 if (type->refs > 1) { /* make sure no nodes exist! */
1779 if (type->refs == 0) {
1780 /* failed load, nothing to undo */
1784 if (type->mod_event != NULL) { /* check with type */
1785 error = (*type->mod_event)(mod, event, data);
1786 if (error != 0) { /* type refuses.. */
1791 LIST_REMOVE(type, types);
1797 if (type->mod_event != NULL)
1798 error = (*type->mod_event)(mod, event, data);
1800 error = 0; /* XXX ? */
1807 * Handle loading and unloading for this code.
1808 * The only thing we need to link into is the NETISR strucure.
1811 ngb_mod_event(module_t mod, int event, void *data)
1817 /* Register line discipline */
1819 netisr_register(NETISR_NETGRAPH, ngintr, NULL);
1823 /* You cant unload it because an interface may be using it. */
1833 static moduledata_t netgraph_mod = {
1838 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1839 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1840 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1841 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1843 /************************************************************************
1845 ************************************************************************/
1847 /* The structure for queueing across ISR switches */
1848 struct ng_queue_entry {
1850 struct ng_queue_entry *next;
1853 hook_p da_hook; /* target hook */
1858 struct ng_mesg *msg_msg;
1864 #define NGQF_DATA 0x01 /* the queue element is data */
1865 #define NGQF_MESG 0x02 /* the queue element is a message */
1867 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1868 static struct ng_queue_entry *ngqlast; /* last item queued */
1869 static const int ngqroom = 256; /* max items to queue */
1870 static int ngqsize; /* number of items in queue */
1872 static struct ng_queue_entry *ngqfree; /* free ones */
1873 static const int ngqfreemax = 256;/* cache at most this many */
1874 static int ngqfreesize; /* number of cached entries */
1879 static struct ng_queue_entry *
1882 struct ng_queue_entry *q;
1884 /* Could be guarding against tty ints or whatever */
1887 /* Try get a cached queue block, or else allocate a new one */
1888 if ((q = ngqfree) == NULL) {
1890 if (ngqsize < ngqroom) { /* don't worry about races */
1891 q = kmalloc(sizeof(*q), M_NETGRAPH, M_NOWAIT);
1902 * Release a queue entry
1904 #define RETURN_QBLK(q) \
1906 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1908 (q)->next = ngqfree; \
1913 kfree((q), M_NETGRAPH); \
1918 * Running at a raised (but we don't know which) processor priority level,
1919 * put the data onto a queue to be picked up by another PPL (probably splnet)
1922 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1924 struct ng_queue_entry *q;
1927 NG_FREE_DATA(m, meta);
1930 if ((q = ng_getqblk()) == NULL) {
1931 NG_FREE_DATA(m, meta);
1935 /* Fill out the contents */
1936 q->flags = NGQF_DATA;
1938 q->body.data.da_hook = hook;
1939 q->body.data.da_m = m;
1940 q->body.data.da_meta = meta;
1941 crit_enter(); /* protect refs and queue */
1942 hook->refs++; /* don't let it go away while on the queue */
1944 /* Put it on the queue */
1954 /* Schedule software interrupt to handle it later */
1955 schednetisr(NETISR_NETGRAPH);
1960 * Running at a raised (but we don't know which) processor priority level,
1961 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1964 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1966 struct ng_queue_entry *q;
1968 char *retaddr = NULL;
1971 /* Find the target node. */
1972 error = ng_path2node(here, address, &dest, &retaddr);
1974 kfree(msg, M_NETGRAPH);
1977 if ((q = ng_getqblk()) == NULL) {
1978 kfree(msg, M_NETGRAPH);
1980 kfree(retaddr, M_NETGRAPH);
1984 /* Fill out the contents */
1985 q->flags = NGQF_MESG;
1987 q->body.msg.msg_node = dest;
1988 q->body.msg.msg_msg = msg;
1989 q->body.msg.msg_retaddr = retaddr;
1990 crit_enter(); /* protect refs and queue */
1991 dest->refs++; /* don't let it go away while on the queue */
1993 /* Put it on the queue */
2003 /* Schedule software interrupt to handle it later */
2004 schednetisr(NETISR_NETGRAPH);
2009 * Pick an item off the queue, process it, and dispose of the queue entry.
2012 ngintr(netmsg_t pmsg)
2016 struct ng_queue_entry *ngq;
2019 struct ng_mesg *msg;
2024 * Packets are never sent to this netisr so the message must always
2025 * be replied. Interlock processing and notification by replying
2026 * the message first.
2028 lwkt_replymsg(&pmsg->lmsg, 0);
2034 if ((ngq = ngqbase)) {
2035 ngqbase = ngq->next;
2041 switch (ngq->flags) {
2043 hook = ngq->body.data.da_hook;
2044 m = ngq->body.data.da_m;
2045 meta = ngq->body.data.da_meta;
2047 NG_SEND_DATAQ(error, hook, m, meta);
2048 ng_unref_hook(hook);
2051 node = ngq->body.msg.msg_node;
2052 msg = ngq->body.msg.msg_msg;
2053 retaddr = ngq->body.msg.msg_retaddr;
2055 if (node->flags & NG_INVALID) {
2056 kfree(msg, M_NETGRAPH);
2058 CALL_MSG_HANDLER(error, node, msg,
2063 kfree(retaddr, M_NETGRAPH);