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 * $DragonFly: src/sys/netgraph/netgraph/ng_base.c,v 1.17 2005/08/30 14:22:05 y0netan1 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/errno.h>
52 #include <sys/kernel.h>
53 #include <sys/malloc.h>
54 #include <sys/syslog.h>
55 #include <sys/linker.h>
56 #include <sys/queue.h>
58 #include <sys/ctype.h>
59 #include <sys/sysctl.h>
60 #include <machine/limits.h>
62 #include <sys/thread2.h>
63 #include <sys/msgport2.h>
65 #include <net/netisr.h>
67 #include <netgraph/ng_message.h>
68 #include <netgraph/netgraph.h>
69 #include <netgraph/ng_parse.h>
71 /* List of all nodes */
72 static LIST_HEAD(, ng_node) nodelist;
74 /* List of installed types */
75 static LIST_HEAD(, ng_type) typelist;
77 /* Hash releted definitions */
78 #define ID_HASH_SIZE 32 /* most systems wont need even this many */
79 static LIST_HEAD(, ng_node) ID_hash[ID_HASH_SIZE];
80 /* Don't nead to initialise them because it's a LIST */
82 /* Internal functions */
83 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
84 static int ng_connect(hook_p hook1, hook_p hook2);
85 static void ng_disconnect_hook(hook_p hook);
86 static int ng_generic_msg(node_p here, struct ng_mesg *msg,
87 const char *retaddr, struct ng_mesg ** resp);
88 static ng_ID_t ng_decodeidname(const char *name);
89 static int ngb_mod_event(module_t mod, int event, void *data);
90 static int ngintr(struct netmsg *);
91 static int ng_load_module(const char *);
92 static int ng_unload_module(const char *);
94 /* Our own netgraph malloc type */
95 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
97 /* Set this to Debugger("X") to catch all errors as they occur */
102 static ng_ID_t nextID = 1;
105 #define CHECK_DATA_MBUF(m) do { \
109 if (((m)->m_flags & M_PKTHDR) == 0) \
110 panic("%s: !PKTHDR", __func__); \
111 for (total = 0, n = (m); n != NULL; n = n->m_next) \
113 if ((m)->m_pkthdr.len != total) { \
114 panic("%s: %d != %d", \
115 __func__, (m)->m_pkthdr.len, total); \
119 #define CHECK_DATA_MBUF(m)
123 /************************************************************************
124 Parse type definitions for generic messages
125 ************************************************************************/
127 /* Handy structure parse type defining macro */
128 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
129 static const struct ng_parse_struct_field \
130 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
131 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
132 &ng_parse_struct_type, \
133 &ng_ ## lo ## _type_fields \
136 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
137 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
138 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
139 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
140 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
141 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
142 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
144 /* Get length of an array when the length is stored as a 32 bit
145 value immediately preceeding the array -- as with struct namelist
146 and struct typelist. */
148 ng_generic_list_getLength(const struct ng_parse_type *type,
149 const u_char *start, const u_char *buf)
151 return *((const u_int32_t *)(buf - 4));
154 /* Get length of the array of struct linkinfo inside a struct hooklist */
156 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
157 const u_char *start, const u_char *buf)
159 const struct hooklist *hl = (const struct hooklist *)start;
161 return hl->nodeinfo.hooks;
164 /* Array type for a variable length array of struct namelist */
165 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
166 &ng_generic_nodeinfo_type,
167 &ng_generic_list_getLength
169 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
170 &ng_parse_array_type,
171 &ng_nodeinfoarray_type_info
174 /* Array type for a variable length array of struct typelist */
175 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
176 &ng_generic_typeinfo_type,
177 &ng_generic_list_getLength
179 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
180 &ng_parse_array_type,
181 &ng_typeinfoarray_type_info
184 /* Array type for array of struct linkinfo in struct hooklist */
185 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
186 &ng_generic_linkinfo_type,
187 &ng_generic_linkinfo_getLength
189 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
190 &ng_parse_array_type,
191 &ng_generic_linkinfo_array_type_info
194 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
195 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
196 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
197 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
198 (&ng_generic_nodeinfoarray_type));
200 /* List of commands and how to convert arguments to/from ASCII */
201 static const struct ng_cmdlist ng_generic_cmds[] = {
213 &ng_generic_mkpeer_type,
220 &ng_generic_connect_type,
227 &ng_generic_name_type,
234 &ng_generic_rmhook_type,
242 &ng_generic_nodeinfo_type
249 &ng_generic_hooklist_type
256 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
263 &ng_generic_listnodes_type
270 &ng_generic_typeinfo_type
277 &ng_parse_string_type
284 &ng_parse_string_type
290 &ng_parse_ng_mesg_type,
291 &ng_parse_ng_mesg_type
297 &ng_parse_ng_mesg_type,
298 &ng_parse_ng_mesg_type
303 /************************************************************************
305 ************************************************************************/
308 ng_load_module(const char *name)
310 char *path, filename[NG_TYPELEN + 4];
314 /* linker_* API won't work without a process context */
318 /* Not found, try to load it as a loadable module */
319 snprintf(filename, sizeof(filename), "ng_%s.ko", name);
320 if ((path = linker_search_path(filename)) == NULL)
322 error = linker_load_file(path, &lf);
323 FREE(path, M_LINKER);
325 lf->userrefs++; /* pretend kldload'ed */
330 ng_unload_module(const char *name)
332 char filename[NG_TYPELEN + 4];
336 /* linker_* API won't work without a process context */
340 /* Not found, try to load it as a loadable module */
341 snprintf(filename, sizeof(filename), "ng_%s.ko", name);
342 if ((lf = linker_find_file_by_name(filename)) == NULL)
344 error = linker_file_unload(lf);
347 lf->userrefs--; /* pretend kldunload'ed */
352 * Instantiate a node of the requested type
355 ng_make_node(const char *typename, node_p *nodepp)
357 struct ng_type *type;
359 /* Check that the type makes sense */
360 if (typename == NULL) {
365 /* Locate the node type */
366 if ((type = ng_findtype(typename)) == NULL)
369 /* Call the constructor */
370 if (type->constructor != NULL)
371 return ((*type->constructor)(nodepp));
373 return (ng_make_node_common(type, nodepp));
377 * Generic node creation. Called by node constructors.
378 * The returned node has a reference count of 1.
381 ng_make_node_common(struct ng_type *type, node_p *nodepp)
385 /* Require the node type to have been already installed */
386 if (ng_findtype(type->name) == NULL) {
391 /* Make a node and try attach it to the type */
392 MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_NOWAIT);
397 bzero(node, sizeof(*node));
399 node->refs++; /* note reference */
402 /* Link us into the node linked list */
403 LIST_INSERT_HEAD(&nodelist, node, nodes);
405 /* Initialize hook list for new node */
406 LIST_INIT(&node->hooks);
408 /* get an ID and put us in the hash chain */
409 node->ID = nextID++; /* 137 per second for 1 year before wrap */
410 LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
418 * Forceably start the shutdown process on a node. Either call
419 * it's shutdown method, or do the default shutdown if there is
420 * no type-specific method.
422 * Persistent nodes must have a type-specific method which
423 * resets the NG_INVALID flag.
426 ng_rmnode(node_p node)
428 /* Check if it's already shutting down */
429 if ((node->flags & NG_INVALID) != 0)
432 /* Add an extra reference so it doesn't go away during this */
435 /* Mark it invalid so any newcomers know not to try use it */
436 node->flags |= NG_INVALID;
438 /* Ask the type if it has anything to do in this case */
439 if (node->type && node->type->shutdown)
440 (*node->type->shutdown)(node);
441 else { /* do the default thing */
447 /* Remove extra reference, possibly the last */
452 * Called by the destructor to remove any STANDARD external references
455 ng_cutlinks(node_p node)
459 /* Make sure that this is set to stop infinite loops */
460 node->flags |= NG_INVALID;
462 /* If we have sleepers, wake them up; they'll see NG_INVALID */
466 /* Notify all remaining connected nodes to disconnect */
467 while ((hook = LIST_FIRST(&node->hooks)) != NULL)
468 ng_destroy_hook(hook);
472 * Remove a reference to the node, possibly the last
475 ng_unref(node_p node)
478 if (--node->refs <= 0) {
480 LIST_REMOVE(node, nodes);
481 LIST_REMOVE(node, idnodes);
482 FREE(node, M_NETGRAPH);
488 * Wait for a node to come ready. Returns a node with a reference count;
489 * don't forget to drop it when we are done with it using ng_release_node().
492 ng_wait_node(node_p node, char *msg)
500 node->refs++; /* the sleeping process counts as a reference */
501 while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
502 error = tsleep(node, PCATCH, msg, 0);
504 if (node->flags & NG_INVALID) {
508 KASSERT(node->refs > 1,
509 ("%s: refs=%d", __func__, node->refs));
510 node->flags |= NG_BUSY;
514 /* Release the reference we had on it */
521 * Release a node acquired via ng_wait_node()
524 ng_release_node(node_p node)
526 /* Declare that we don't want it */
527 node->flags &= ~NG_BUSY;
529 /* If we have sleepers, then wake them up */
533 /* We also have a reference.. drop it too */
537 /************************************************************************
539 ************************************************************************/
541 ng_ID2node(ng_ID_t ID)
544 LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
545 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
552 ng_node2ID(node_p node)
557 /************************************************************************
559 ************************************************************************/
562 * Assign a node a name. Once assigned, the name cannot be changed.
565 ng_name_node(node_p node, const char *name)
569 /* Check the name is valid */
570 for (i = 0; i < NG_NODELEN + 1; i++) {
571 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
574 if (i == 0 || name[i] != '\0') {
578 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
583 /* Check the node isn't already named */
584 if (node->name != NULL) {
589 /* Check the name isn't already being used */
590 if (ng_findname(node, name) != NULL) {
595 /* Allocate space and copy it */
596 MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
597 if (node->name == NULL) {
601 strcpy(node->name, name);
603 /* The name counts as a reference */
609 * Find a node by absolute name. The name should NOT end with ':'
610 * The name "." means "this node" and "[xxx]" means "the node
611 * with ID (ie, at address) xxx".
613 * Returns the node if found, else NULL.
616 ng_findname(node_p this, const char *name)
621 /* "." means "this node" */
622 if (strcmp(name, ".") == 0)
625 /* Check for name-by-ID */
626 if ((temp = ng_decodeidname(name)) != 0) {
627 return (ng_ID2node(temp));
630 /* Find node by name */
631 LIST_FOREACH(node, &nodelist, nodes) {
632 if ((node->name != NULL)
633 && (strcmp(node->name, name) == 0)
634 && ((node->flags & NG_INVALID) == 0))
641 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
642 * string is not valid, otherwise returns the value.
645 ng_decodeidname(const char *name)
647 const int len = strlen(name);
651 /* Check for proper length, brackets, no leading junk */
652 if (len < 3 || name[0] != '[' || name[len - 1] != ']'
653 || !isxdigit(name[1]))
657 val = strtoul(name + 1, &eptr, 16);
658 if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
664 * Remove a name from a node. This should only be called
665 * when shutting down and removing the node.
668 ng_unname(node_p node)
671 FREE(node->name, M_NETGRAPH);
677 /************************************************************************
680 Names are not optional. Hooks are always connected, except for a
681 brief moment within these routines.
683 ************************************************************************/
686 * Remove a hook reference
689 ng_unref_hook(hook_p hook)
692 if (--hook->refs == 0)
693 FREE(hook, M_NETGRAPH);
698 * Add an unconnected hook to a node. Only used internally.
701 ng_add_hook(node_p node, const char *name, hook_p *hookp)
706 /* Check that the given name is good */
711 if (ng_findhook(node, name) != NULL) {
716 /* Allocate the hook and link it up */
717 MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_NOWAIT);
722 bzero(hook, sizeof(*hook));
724 hook->flags = HK_INVALID;
726 node->refs++; /* each hook counts as a reference */
728 /* Check if the node type code has something to say about it */
729 if (node->type->newhook != NULL)
730 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
734 * The 'type' agrees so far, so go ahead and link it in.
735 * We'll ask again later when we actually connect the hooks.
737 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
741 MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
742 if (hook->name == NULL) {
744 LIST_REMOVE(hook, hooks);
749 ng_unref_hook(hook); /* this frees the hook */
752 strcpy(hook->name, name);
759 * Connect a pair of hooks. Only used internally.
762 ng_connect(hook_p hook1, hook_p hook2)
769 /* Give each node the opportunity to veto the impending connection */
770 if (hook1->node->type->connect) {
771 if ((error = (*hook1->node->type->connect) (hook1))) {
772 ng_destroy_hook(hook1); /* also zaps hook2 */
776 if (hook2->node->type->connect) {
777 if ((error = (*hook2->node->type->connect) (hook2))) {
778 ng_destroy_hook(hook2); /* also zaps hook1 */
782 hook1->flags &= ~HK_INVALID;
783 hook2->flags &= ~HK_INVALID;
790 * Node types may supply their own optimized routines for finding
791 * hooks. If none is supplied, we just do a linear search.
794 ng_findhook(node_p node, const char *name)
798 if (node->type->findhook != NULL)
799 return (*node->type->findhook)(node, name);
800 LIST_FOREACH(hook, &node->hooks, hooks) {
801 if (hook->name != NULL
802 && strcmp(hook->name, name) == 0
803 && (hook->flags & HK_INVALID) == 0)
812 * As hooks are always attached, this really destroys two hooks.
813 * The one given, and the one attached to it. Disconnect the hooks
814 * from each other first.
817 ng_destroy_hook(hook_p hook)
819 hook_p peer = hook->peer;
821 hook->flags |= HK_INVALID; /* as soon as possible */
823 peer->flags |= HK_INVALID; /* as soon as possible */
826 ng_disconnect_hook(peer);
828 ng_disconnect_hook(hook);
832 * Notify the node of the hook's demise. This may result in more actions
833 * (e.g. shutdown) but we don't do that ourselves and don't know what
834 * happens there. If there is no appropriate handler, then just remove it
835 * (and decrement the reference count of it's node which in turn might
836 * make something happen).
839 ng_disconnect_hook(hook_p hook)
841 node_p node = hook->node;
844 * Remove the hook from the node's list to avoid possible recursion
845 * in case the disconnection results in node shutdown.
847 LIST_REMOVE(hook, hooks);
849 if (node->type->disconnect) {
851 * The type handler may elect to destroy the peer so don't
852 * trust its existance after this point.
854 (*node->type->disconnect) (hook);
856 ng_unref(node); /* might be the last reference */
858 FREE(hook->name, M_NETGRAPH);
859 hook->node = NULL; /* may still be referenced elsewhere */
864 * Take two hooks on a node and merge the connection so that the given node
865 * is effectively bypassed.
868 ng_bypass(hook_p hook1, hook_p hook2)
870 if (hook1->node != hook2->node)
872 hook1->peer->peer = hook2->peer;
873 hook2->peer->peer = hook1->peer;
875 /* XXX If we ever cache methods on hooks update them as well */
878 ng_destroy_hook(hook1);
879 ng_destroy_hook(hook2);
884 * Install a new netgraph type
887 ng_newtype(struct ng_type *tp)
889 const size_t namelen = strlen(tp->name);
891 /* Check version and type name fields */
892 if (tp->version != NG_VERSION || namelen == 0 || namelen > NG_TYPELEN) {
897 /* Check for name collision */
898 if (ng_findtype(tp->name) != NULL) {
903 /* Link in new type */
904 LIST_INSERT_HEAD(&typelist, tp, types);
905 tp->refs = 1; /* first ref is linked list */
910 * Look for a type of the name given
913 ng_findtype(const char *typename)
915 struct ng_type *type;
917 LIST_FOREACH(type, &typelist, types) {
918 if (strcmp(type->name, typename) == 0)
925 /************************************************************************
927 ************************************************************************/
930 * Make a peer and connect. The order is arranged to minimise
931 * the work needed to back out in case of error.
934 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
941 if ((error = ng_add_hook(node, name, &hook)))
944 /* make sure we have the module needed */
945 if (ng_findtype(type) == NULL) {
946 /* Not found, try to load it as a loadable module */
947 error = ng_load_module(type);
949 printf("required netgraph module ng_%s not loaded\n",
954 if ((error = ng_make_node(type, &node2))) {
955 ng_destroy_hook(hook);
958 if ((error = ng_add_hook(node2, name2, &hook2))) {
960 ng_destroy_hook(hook);
965 * Actually link the two hooks together.. on failure they are
966 * destroyed so we don't have to do that here.
968 if ((error = ng_connect(hook, hook2)))
974 * Connect two nodes using the specified hooks
977 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
983 if ((error = ng_add_hook(node, name, &hook)))
985 if ((error = ng_add_hook(node2, name2, &hook2))) {
986 ng_destroy_hook(hook);
989 return (ng_connect(hook, hook2));
993 * Parse and verify a string of the form: <NODE:><PATH>
995 * Such a string can refer to a specific node or a specific hook
996 * on a specific node, depending on how you look at it. In the
997 * latter case, the PATH component must not end in a dot.
999 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1000 * of hook names separated by dots. This breaks out the original
1001 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1002 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1003 * the final hook component of <PATH>, if any, otherwise NULL.
1005 * This returns -1 if the path is malformed. The char ** are optional.
1009 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1011 char *node, *path, *hook;
1015 * Extract absolute NODE, if any
1017 for (path = addr; *path && *path != ':'; path++);
1019 node = addr; /* Here's the NODE */
1020 *path++ = '\0'; /* Here's the PATH */
1022 /* Node name must not be empty */
1026 /* A name of "." is OK; otherwise '.' not allowed */
1027 if (strcmp(node, ".") != 0) {
1028 for (k = 0; node[k]; k++)
1033 node = NULL; /* No absolute NODE */
1034 path = addr; /* Here's the PATH */
1037 /* Snoop for illegal characters in PATH */
1038 for (k = 0; path[k]; k++)
1042 /* Check for no repeated dots in PATH */
1043 for (k = 0; path[k]; k++)
1044 if (path[k] == '.' && path[k + 1] == '.')
1047 /* Remove extra (degenerate) dots from beginning or end of PATH */
1050 if (*path && path[strlen(path) - 1] == '.')
1051 path[strlen(path) - 1] = 0;
1053 /* If PATH has a dot, then we're not talking about a hook */
1055 for (hook = path, k = 0; path[k]; k++)
1056 if (path[k] == '.') {
1074 * Given a path, which may be absolute or relative, and a starting node,
1075 * return the destination node. Compute the "return address" if desired.
1078 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1080 const node_p start = here;
1081 char fullpath[NG_PATHLEN + 1];
1082 char *nodename, *path, pbuf[2];
1093 /* Make a writable copy of address for ng_path_parse() */
1094 strncpy(fullpath, address, sizeof(fullpath) - 1);
1095 fullpath[sizeof(fullpath) - 1] = '\0';
1097 /* Parse out node and sequence of hooks */
1098 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1103 pbuf[0] = '.'; /* Needs to be writable */
1108 /* For an absolute address, jump to the starting node */
1110 node = ng_findname(here, nodename);
1118 /* Now follow the sequence of hooks */
1119 for (cp = path; node != NULL && *cp != '\0'; ) {
1124 * Break out the next path segment. Replace the dot we just
1125 * found with a NUL; "cp" points to the next segment (or the
1128 for (segment = cp; *cp != '\0'; cp++) {
1136 if (*segment == '\0')
1139 /* We have a segment, so look for a hook by that name */
1140 hook = ng_findhook(node, segment);
1142 /* Can't get there from here... */
1144 || hook->peer == NULL
1145 || (hook->flags & HK_INVALID) != 0) {
1150 /* Hop on over to the next node */
1151 node = hook->peer->node;
1154 /* If node somehow missing, fail here (probably this is not needed) */
1160 /* Now compute return address, i.e., the path to the sender */
1162 MALLOC(*rtnp, char *, NG_NODELEN + 2, M_NETGRAPH, M_NOWAIT);
1163 if (*rtnp == NULL) {
1167 if (start->name != NULL)
1168 sprintf(*rtnp, "%s:", start->name);
1170 sprintf(*rtnp, "[%x]:", ng_node2ID(start));
1179 * Call the appropriate message handler for the object.
1180 * It is up to the message handler to free the message.
1181 * If it's a generic message, handle it generically, otherwise
1182 * call the type's message handler (if it exists)
1183 * XXX (race). Remember that a queued message may reference a node
1184 * or hook that has just been invalidated. It will exist
1185 * as the queue code is holding a reference, but..
1188 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1190 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1191 (error) = ng_generic_msg((node), (msg), \
1192 (retaddr), (resp)); \
1194 if ((node)->type->rcvmsg != NULL) { \
1195 (error) = (*(node)->type->rcvmsg)((node), \
1196 (msg), (retaddr), (resp)); \
1199 FREE((msg), M_NETGRAPH); \
1207 * Send a control message to a node
1210 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1211 struct ng_mesg **rptr)
1214 char *retaddr = NULL;
1217 /* Find the target node */
1218 error = ng_path2node(here, address, &dest, &retaddr);
1220 FREE(msg, M_NETGRAPH);
1224 /* Make sure the resp field is null before we start */
1228 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1230 /* Make sure that if there is a response, it has the RESP bit set */
1231 if ((error == 0) && rptr && *rptr)
1232 (*rptr)->header.flags |= NGF_RESP;
1235 * If we had a return address it is up to us to free it. They should
1236 * have taken a copy if they needed to make a delayed response.
1239 FREE(retaddr, M_NETGRAPH);
1244 * Implement the 'generic' control messages
1247 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1248 struct ng_mesg **resp)
1252 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1254 FREE(msg, M_NETGRAPH);
1257 switch (msg->header.cmd) {
1263 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1265 if (msg->header.arglen != sizeof(*mkp)) {
1269 mkp->type[sizeof(mkp->type) - 1] = '\0';
1270 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1271 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1272 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1277 struct ngm_connect *const con =
1278 (struct ngm_connect *) msg->data;
1281 if (msg->header.arglen != sizeof(*con)) {
1285 con->path[sizeof(con->path) - 1] = '\0';
1286 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1287 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1288 error = ng_path2node(here, con->path, &node2, NULL);
1291 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1296 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1298 if (msg->header.arglen != sizeof(*nam)) {
1302 nam->name[sizeof(nam->name) - 1] = '\0';
1303 error = ng_name_node(here, nam->name);
1308 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1311 if (msg->header.arglen != sizeof(*rmh)) {
1315 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1316 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1317 ng_destroy_hook(hook);
1322 struct nodeinfo *ni;
1325 /* Get response struct */
1330 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1336 /* Fill in node info */
1337 ni = (struct nodeinfo *) rp->data;
1338 if (here->name != NULL)
1339 strncpy(ni->name, here->name, NG_NODELEN);
1340 strncpy(ni->type, here->type->name, NG_TYPELEN);
1341 ni->id = ng_node2ID(here);
1342 ni->hooks = here->numhooks;
1348 const int nhooks = here->numhooks;
1349 struct hooklist *hl;
1350 struct nodeinfo *ni;
1354 /* Get response struct */
1359 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1360 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1365 hl = (struct hooklist *) rp->data;
1368 /* Fill in node info */
1370 strncpy(ni->name, here->name, NG_NODELEN);
1371 strncpy(ni->type, here->type->name, NG_TYPELEN);
1372 ni->id = ng_node2ID(here);
1374 /* Cycle through the linked list of hooks */
1376 LIST_FOREACH(hook, &here->hooks, hooks) {
1377 struct linkinfo *const link = &hl->link[ni->hooks];
1379 if (ni->hooks >= nhooks) {
1380 log(LOG_ERR, "%s: number of %s changed\n",
1384 if ((hook->flags & HK_INVALID) != 0)
1386 strncpy(link->ourhook, hook->name, NG_HOOKLEN);
1387 strncpy(link->peerhook, hook->peer->name, NG_HOOKLEN);
1388 if (hook->peer->node->name != NULL)
1389 strncpy(link->nodeinfo.name,
1390 hook->peer->node->name, NG_NODELEN);
1391 strncpy(link->nodeinfo.type,
1392 hook->peer->node->type->name, NG_TYPELEN);
1393 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1394 link->nodeinfo.hooks = hook->peer->node->numhooks;
1404 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1405 struct namelist *nl;
1415 /* Count number of nodes */
1416 LIST_FOREACH(node, &nodelist, nodes) {
1417 if ((node->flags & NG_INVALID) == 0
1418 && (unnamed || node->name != NULL))
1422 /* Get response struct */
1427 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1428 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1433 nl = (struct namelist *) rp->data;
1435 /* Cycle through the linked list of nodes */
1437 LIST_FOREACH(node, &nodelist, nodes) {
1438 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1440 if (nl->numnames >= num) {
1441 log(LOG_ERR, "%s: number of %s changed\n",
1445 if ((node->flags & NG_INVALID) != 0)
1447 if (!unnamed && node->name == NULL)
1449 if (node->name != NULL)
1450 strncpy(np->name, node->name, NG_NODELEN);
1451 strncpy(np->type, node->type->name, NG_TYPELEN);
1452 np->id = ng_node2ID(node);
1453 np->hooks = node->numhooks;
1462 struct typelist *tl;
1464 struct ng_type *type;
1472 /* Count number of types */
1473 LIST_FOREACH(type, &typelist, types)
1476 /* Get response struct */
1481 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1482 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1487 tl = (struct typelist *) rp->data;
1489 /* Cycle through the linked list of types */
1491 LIST_FOREACH(type, &typelist, types) {
1492 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1494 if (tl->numtypes >= num) {
1495 log(LOG_ERR, "%s: number of %s changed\n",
1499 strncpy(tp->type_name, type->name, NG_TYPELEN);
1500 tp->numnodes = type->refs - 1; /* don't count list */
1507 case NGM_BINARY2ASCII:
1509 int bufSize = 20 * 1024; /* XXX hard coded constant */
1510 const struct ng_parse_type *argstype;
1511 const struct ng_cmdlist *c;
1512 struct ng_mesg *rp, *binary, *ascii;
1514 /* Data area must contain a valid netgraph message */
1515 binary = (struct ng_mesg *)msg->data;
1516 if (msg->header.arglen < sizeof(struct ng_mesg)
1517 || msg->header.arglen - sizeof(struct ng_mesg)
1518 < binary->header.arglen) {
1523 /* Get a response message with lots of room */
1524 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1529 ascii = (struct ng_mesg *)rp->data;
1531 /* Copy binary message header to response message payload */
1532 bcopy(binary, ascii, sizeof(*binary));
1534 /* Find command by matching typecookie and command number */
1535 for (c = here->type->cmdlist;
1536 c != NULL && c->name != NULL; c++) {
1537 if (binary->header.typecookie == c->cookie
1538 && binary->header.cmd == c->cmd)
1541 if (c == NULL || c->name == NULL) {
1542 for (c = ng_generic_cmds; c->name != NULL; c++) {
1543 if (binary->header.typecookie == c->cookie
1544 && binary->header.cmd == c->cmd)
1547 if (c->name == NULL) {
1548 FREE(rp, M_NETGRAPH);
1554 /* Convert command name to ASCII */
1555 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1558 /* Convert command arguments to ASCII */
1559 argstype = (binary->header.flags & NGF_RESP) ?
1560 c->respType : c->mesgType;
1561 if (argstype == NULL)
1562 *ascii->data = '\0';
1564 if ((error = ng_unparse(argstype,
1565 (u_char *)binary->data,
1566 ascii->data, bufSize)) != 0) {
1567 FREE(rp, M_NETGRAPH);
1572 /* Return the result as struct ng_mesg plus ASCII string */
1573 bufSize = strlen(ascii->data) + 1;
1574 ascii->header.arglen = bufSize;
1575 rp->header.arglen = sizeof(*ascii) + bufSize;
1580 case NGM_ASCII2BINARY:
1582 int bufSize = 2000; /* XXX hard coded constant */
1583 const struct ng_cmdlist *c;
1584 const struct ng_parse_type *argstype;
1585 struct ng_mesg *rp, *ascii, *binary;
1588 /* Data area must contain at least a struct ng_mesg + '\0' */
1589 ascii = (struct ng_mesg *)msg->data;
1590 if (msg->header.arglen < sizeof(*ascii) + 1
1591 || ascii->header.arglen < 1
1592 || msg->header.arglen
1593 < sizeof(*ascii) + ascii->header.arglen) {
1597 ascii->data[ascii->header.arglen - 1] = '\0';
1599 /* Get a response message with lots of room */
1600 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1605 binary = (struct ng_mesg *)rp->data;
1607 /* Copy ASCII message header to response message payload */
1608 bcopy(ascii, binary, sizeof(*ascii));
1610 /* Find command by matching ASCII command string */
1611 for (c = here->type->cmdlist;
1612 c != NULL && c->name != NULL; c++) {
1613 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1616 if (c == NULL || c->name == NULL) {
1617 for (c = ng_generic_cmds; c->name != NULL; c++) {
1618 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1621 if (c->name == NULL) {
1622 FREE(rp, M_NETGRAPH);
1628 /* Convert command name to binary */
1629 binary->header.cmd = c->cmd;
1630 binary->header.typecookie = c->cookie;
1632 /* Convert command arguments to binary */
1633 argstype = (binary->header.flags & NGF_RESP) ?
1634 c->respType : c->mesgType;
1635 if (argstype == NULL)
1638 if ((error = ng_parse(argstype, ascii->data,
1639 &off, (u_char *)binary->data, &bufSize)) != 0) {
1640 FREE(rp, M_NETGRAPH);
1645 /* Return the result */
1646 binary->header.arglen = bufSize;
1647 rp->header.arglen = sizeof(*binary) + bufSize;
1652 case NGM_TEXT_CONFIG:
1653 case NGM_TEXT_STATUS:
1655 * This one is tricky as it passes the command down to the
1656 * actual node, even though it is a generic type command.
1657 * This means we must assume that the msg is already freed
1658 * when control passes back to us.
1664 if (here->type->rcvmsg != NULL)
1665 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1666 /* Fall through if rcvmsg not supported */
1671 FREE(msg, M_NETGRAPH);
1676 * Send a data packet to a node. If the recipient has no
1677 * 'receive data' method, then silently discard the packet.
1680 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1682 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1686 if (hook && (hook->flags & HK_INVALID) == 0) {
1687 rcvdata = hook->peer->node->type->rcvdata;
1688 if (rcvdata != NULL)
1689 error = (*rcvdata)(hook->peer, m, meta);
1692 NG_FREE_DATA(m, meta);
1697 NG_FREE_DATA(m, meta);
1703 * Send a queued data packet to a node. If the recipient has no
1704 * 'receive queued data' method, then try the 'receive data' method above.
1707 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1709 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1713 if (hook && (hook->flags & HK_INVALID) == 0) {
1714 rcvdataq = hook->peer->node->type->rcvdataq;
1715 if (rcvdataq != NULL)
1716 error = (*rcvdataq)(hook->peer, m, meta);
1718 error = ng_send_data(hook, m, meta);
1723 NG_FREE_DATA(m, meta);
1731 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1734 ng_copy_meta(meta_p meta)
1740 MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1743 meta2->allocated_len = meta->used_len;
1744 bcopy(meta, meta2, meta->used_len);
1748 /************************************************************************
1750 ************************************************************************/
1753 * Handle the loading/unloading of a netgraph node type module
1756 ng_mod_event(module_t mod, int event, void *data)
1758 struct ng_type *const type = data;
1764 /* Register new netgraph node type */
1766 if ((error = ng_newtype(type)) != 0) {
1771 /* Call type specific code */
1772 if (type->mod_event != NULL)
1773 if ((error = (*type->mod_event)(mod, event, data))) {
1774 type->refs--; /* undo it */
1775 LIST_REMOVE(type, types);
1782 if (type->refs > 1) { /* make sure no nodes exist! */
1785 if (type->refs == 0) {
1786 /* failed load, nothing to undo */
1790 if (type->mod_event != NULL) { /* check with type */
1791 error = (*type->mod_event)(mod, event, data);
1792 if (error != 0) { /* type refuses.. */
1797 LIST_REMOVE(type, types);
1803 if (type->mod_event != NULL)
1804 error = (*type->mod_event)(mod, event, data);
1806 error = 0; /* XXX ? */
1813 * Handle loading and unloading for this code.
1814 * The only thing we need to link into is the NETISR strucure.
1817 ngb_mod_event(module_t mod, int event, void *data)
1823 /* Register line discipline */
1825 error = ng_load_module("ksocket");
1830 netisr_register(NETISR_NETGRAPH, cpu0_portfn, ngintr);
1835 ng_unload_module("ksocket");
1836 /* You cant unload it because an interface may be using it. */
1846 static moduledata_t netgraph_mod = {
1851 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1852 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1853 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1854 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1856 /************************************************************************
1858 ************************************************************************/
1860 /* The structure for queueing across ISR switches */
1861 struct ng_queue_entry {
1863 struct ng_queue_entry *next;
1866 hook_p da_hook; /* target hook */
1871 struct ng_mesg *msg_msg;
1877 #define NGQF_DATA 0x01 /* the queue element is data */
1878 #define NGQF_MESG 0x02 /* the queue element is a message */
1880 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1881 static struct ng_queue_entry *ngqlast; /* last item queued */
1882 static const int ngqroom = 256; /* max items to queue */
1883 static int ngqsize; /* number of items in queue */
1885 static struct ng_queue_entry *ngqfree; /* free ones */
1886 static const int ngqfreemax = 256;/* cache at most this many */
1887 static int ngqfreesize; /* number of cached entries */
1892 static struct ng_queue_entry *
1895 struct ng_queue_entry *q;
1897 /* Could be guarding against tty ints or whatever */
1900 /* Try get a cached queue block, or else allocate a new one */
1901 if ((q = ngqfree) == NULL) {
1903 if (ngqsize < ngqroom) { /* don't worry about races */
1904 MALLOC(q, struct ng_queue_entry *,
1905 sizeof(*q), M_NETGRAPH, M_NOWAIT);
1916 * Release a queue entry
1918 #define RETURN_QBLK(q) \
1920 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1922 (q)->next = ngqfree; \
1927 FREE((q), M_NETGRAPH); \
1932 * Running at a raised (but we don't know which) processor priority level,
1933 * put the data onto a queue to be picked up by another PPL (probably splnet)
1936 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1938 struct ng_queue_entry *q;
1941 NG_FREE_DATA(m, meta);
1944 if ((q = ng_getqblk()) == NULL) {
1945 NG_FREE_DATA(m, meta);
1949 /* Fill out the contents */
1950 q->flags = NGQF_DATA;
1952 q->body.data.da_hook = hook;
1953 q->body.data.da_m = m;
1954 q->body.data.da_meta = meta;
1955 crit_enter(); /* protect refs and queue */
1956 hook->refs++; /* don't let it go away while on the queue */
1958 /* Put it on the queue */
1968 /* Schedule software interrupt to handle it later */
1969 schednetisr(NETISR_NETGRAPH);
1974 * Running at a raised (but we don't know which) processor priority level,
1975 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1978 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1980 struct ng_queue_entry *q;
1982 char *retaddr = NULL;
1985 /* Find the target node. */
1986 error = ng_path2node(here, address, &dest, &retaddr);
1988 FREE(msg, M_NETGRAPH);
1991 if ((q = ng_getqblk()) == NULL) {
1992 FREE(msg, M_NETGRAPH);
1994 FREE(retaddr, M_NETGRAPH);
1998 /* Fill out the contents */
1999 q->flags = NGQF_MESG;
2001 q->body.msg.msg_node = dest;
2002 q->body.msg.msg_msg = msg;
2003 q->body.msg.msg_retaddr = retaddr;
2004 crit_enter(); /* protect refs and queue */
2005 dest->refs++; /* don't let it go away while on the queue */
2007 /* Put it on the queue */
2017 /* Schedule software interrupt to handle it later */
2018 schednetisr(NETISR_NETGRAPH);
2023 * Pick an item off the queue, process it, and dispose of the queue entry.
2024 * Should be running at splnet.
2027 ngintr(struct netmsg *pmsg)
2029 struct mbuf *m = ((struct netmsg_packet *)pmsg)->nm_packet;
2031 struct ng_queue_entry *ngq;
2034 struct ng_mesg *msg;
2040 if ((ngq = ngqbase)) {
2041 ngqbase = ngq->next;
2047 switch (ngq->flags) {
2049 hook = ngq->body.data.da_hook;
2050 m = ngq->body.data.da_m;
2051 meta = ngq->body.data.da_meta;
2053 NG_SEND_DATAQ(error, hook, m, meta);
2054 ng_unref_hook(hook);
2057 node = ngq->body.msg.msg_node;
2058 msg = ngq->body.msg.msg_msg;
2059 retaddr = ngq->body.msg.msg_retaddr;
2061 if (node->flags & NG_INVALID) {
2062 FREE(msg, M_NETGRAPH);
2064 CALL_MSG_HANDLER(error, node, msg,
2069 FREE(retaddr, M_NETGRAPH);
2076 lwkt_replymsg(&pmsg->nm_lmsg, 0);