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.25 2007/06/03 20:51:12 dillon 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 <sys/vnode.h>
61 #include <machine/limits.h>
63 #include <sys/thread2.h>
64 #include <sys/msgport2.h>
66 #include <net/netisr.h>
68 #include <netgraph/ng_message.h>
69 #include <netgraph/netgraph.h>
70 #include <netgraph/ng_parse.h>
72 /* List of all nodes */
73 static LIST_HEAD(, ng_node) nodelist;
75 /* List of installed types */
76 static LIST_HEAD(, ng_type) typelist;
78 /* Hash releted definitions */
79 #define ID_HASH_SIZE 32 /* most systems wont need even this many */
80 static LIST_HEAD(, ng_node) ID_hash[ID_HASH_SIZE];
81 /* Don't nead to initialise them because it's a LIST */
83 /* Internal functions */
84 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
85 static int ng_connect(hook_p hook1, hook_p hook2);
86 static void ng_disconnect_hook(hook_p hook);
87 static int ng_generic_msg(node_p here, struct ng_mesg *msg,
88 const char *retaddr, struct ng_mesg ** resp);
89 static ng_ID_t ng_decodeidname(const char *name);
90 static int ngb_mod_event(module_t mod, int event, void *data);
91 static void ngintr(struct netmsg *);
92 static int ng_load_module(const char *);
93 static int ng_unload_module(const char *);
95 /* Our own netgraph malloc type */
96 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
98 /* Set this to Debugger("X") to catch all errors as they occur */
103 static ng_ID_t nextID = 1;
106 #define CHECK_DATA_MBUF(m) do { \
110 if (((m)->m_flags & M_PKTHDR) == 0) \
111 panic("%s: !PKTHDR", __func__); \
112 for (total = 0, n = (m); n != NULL; n = n->m_next) \
114 if ((m)->m_pkthdr.len != total) { \
115 panic("%s: %d != %d", \
116 __func__, (m)->m_pkthdr.len, total); \
120 #define CHECK_DATA_MBUF(m)
124 /************************************************************************
125 Parse type definitions for generic messages
126 ************************************************************************/
128 /* Handy structure parse type defining macro */
129 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
130 static const struct ng_parse_struct_field \
131 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
132 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
133 &ng_parse_struct_type, \
134 &ng_ ## lo ## _type_fields \
137 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
138 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
139 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
140 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
141 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
142 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
143 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
145 /* Get length of an array when the length is stored as a 32 bit
146 value immediately preceeding the array -- as with struct namelist
147 and struct typelist. */
149 ng_generic_list_getLength(const struct ng_parse_type *type,
150 const u_char *start, const u_char *buf)
152 return *((const u_int32_t *)(buf - 4));
155 /* Get length of the array of struct linkinfo inside a struct hooklist */
157 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
158 const u_char *start, const u_char *buf)
160 const struct hooklist *hl = (const struct hooklist *)start;
162 return hl->nodeinfo.hooks;
165 /* Array type for a variable length array of struct namelist */
166 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
167 &ng_generic_nodeinfo_type,
168 &ng_generic_list_getLength
170 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
171 &ng_parse_array_type,
172 &ng_nodeinfoarray_type_info
175 /* Array type for a variable length array of struct typelist */
176 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
177 &ng_generic_typeinfo_type,
178 &ng_generic_list_getLength
180 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
181 &ng_parse_array_type,
182 &ng_typeinfoarray_type_info
185 /* Array type for array of struct linkinfo in struct hooklist */
186 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
187 &ng_generic_linkinfo_type,
188 &ng_generic_linkinfo_getLength
190 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
191 &ng_parse_array_type,
192 &ng_generic_linkinfo_array_type_info
195 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
196 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
197 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
198 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
199 (&ng_generic_nodeinfoarray_type));
201 /* List of commands and how to convert arguments to/from ASCII */
202 static const struct ng_cmdlist ng_generic_cmds[] = {
214 &ng_generic_mkpeer_type,
221 &ng_generic_connect_type,
228 &ng_generic_name_type,
235 &ng_generic_rmhook_type,
243 &ng_generic_nodeinfo_type
250 &ng_generic_hooklist_type
257 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
264 &ng_generic_listnodes_type
271 &ng_generic_typeinfo_type
278 &ng_parse_string_type
285 &ng_parse_string_type
291 &ng_parse_ng_mesg_type,
292 &ng_parse_ng_mesg_type
298 &ng_parse_ng_mesg_type,
299 &ng_parse_ng_mesg_type
304 /************************************************************************
306 ************************************************************************/
309 linker_api_available(void)
311 /* linker_* API won't work without a process context */
315 * nlookup_init() relies on namei_oc to be initialized,
316 * but it's not when the netgraph module is loaded during boot.
318 if (namei_oc == NULL)
324 ng_load_module(const char *name)
326 char *path, filename[NG_TYPESIZ + 3];
330 if (!linker_api_available())
333 /* Not found, try to load it as a loadable module */
334 ksnprintf(filename, sizeof(filename), "ng_%s.ko", name);
335 if ((path = linker_search_path(filename)) == NULL)
337 error = linker_load_file(path, &lf);
338 FREE(path, M_LINKER);
340 lf->userrefs++; /* pretend kldload'ed */
345 ng_unload_module(const char *name)
347 char filename[NG_TYPESIZ + 3];
351 if (!linker_api_available())
354 /* Not found, try to load it as a loadable module */
355 ksnprintf(filename, sizeof(filename), "ng_%s.ko", name);
356 if ((lf = linker_find_file_by_name(filename)) == NULL)
358 error = linker_file_unload(lf);
361 lf->userrefs--; /* pretend kldunload'ed */
366 * Instantiate a node of the requested type
369 ng_make_node(const char *typename, node_p *nodepp)
371 struct ng_type *type;
373 /* Check that the type makes sense */
374 if (typename == NULL) {
379 /* Locate the node type */
380 if ((type = ng_findtype(typename)) == NULL)
383 /* Call the constructor */
384 if (type->constructor != NULL)
385 return ((*type->constructor)(nodepp));
387 return (ng_make_node_common(type, nodepp));
391 * Generic node creation. Called by node constructors.
392 * The returned node has a reference count of 1.
395 ng_make_node_common(struct ng_type *type, node_p *nodepp)
399 /* Require the node type to have been already installed */
400 if (ng_findtype(type->name) == NULL) {
405 /* Make a node and try attach it to the type */
406 MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_NOWAIT);
411 bzero(node, sizeof(*node));
413 node->refs++; /* note reference */
416 /* Link us into the node linked list */
417 LIST_INSERT_HEAD(&nodelist, node, nodes);
419 /* Initialize hook list for new node */
420 LIST_INIT(&node->hooks);
422 /* get an ID and put us in the hash chain */
423 node->ID = nextID++; /* 137 per second for 1 year before wrap */
424 LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
432 * Forceably start the shutdown process on a node. Either call
433 * it's shutdown method, or do the default shutdown if there is
434 * no type-specific method.
436 * Persistent nodes must have a type-specific method which
437 * resets the NG_INVALID flag.
440 ng_rmnode(node_p node)
442 /* Check if it's already shutting down */
443 if ((node->flags & NG_INVALID) != 0)
446 /* Add an extra reference so it doesn't go away during this */
449 /* Mark it invalid so any newcomers know not to try use it */
450 node->flags |= NG_INVALID;
452 /* Ask the type if it has anything to do in this case */
453 if (node->type && node->type->shutdown)
454 (*node->type->shutdown)(node);
455 else { /* do the default thing */
461 /* Remove extra reference, possibly the last */
466 * Called by the destructor to remove any STANDARD external references
469 ng_cutlinks(node_p node)
473 /* Make sure that this is set to stop infinite loops */
474 node->flags |= NG_INVALID;
476 /* If we have sleepers, wake them up; they'll see NG_INVALID */
480 /* Notify all remaining connected nodes to disconnect */
481 while ((hook = LIST_FIRST(&node->hooks)) != NULL)
482 ng_destroy_hook(hook);
486 * Remove a reference to the node, possibly the last
489 ng_unref(node_p node)
492 if (--node->refs <= 0) {
494 LIST_REMOVE(node, nodes);
495 LIST_REMOVE(node, idnodes);
496 FREE(node, M_NETGRAPH);
502 * Wait for a node to come ready. Returns a node with a reference count;
503 * don't forget to drop it when we are done with it using ng_release_node().
506 ng_wait_node(node_p node, char *msg)
514 node->refs++; /* the sleeping process counts as a reference */
515 while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
516 error = tsleep(node, PCATCH, msg, 0);
518 if (node->flags & NG_INVALID) {
522 KASSERT(node->refs > 1,
523 ("%s: refs=%d", __func__, node->refs));
524 node->flags |= NG_BUSY;
528 /* Release the reference we had on it */
535 * Release a node acquired via ng_wait_node()
538 ng_release_node(node_p node)
540 /* Declare that we don't want it */
541 node->flags &= ~NG_BUSY;
543 /* If we have sleepers, then wake them up */
547 /* We also have a reference.. drop it too */
551 /************************************************************************
553 ************************************************************************/
555 ng_ID2node(ng_ID_t ID)
558 LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
559 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
566 ng_node2ID(node_p node)
571 /************************************************************************
573 ************************************************************************/
576 * Assign a node a name. Once assigned, the name cannot be changed.
579 ng_name_node(node_p node, const char *name)
583 /* Check the name is valid */
584 for (i = 0; i < NG_NODESIZ; i++) {
585 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
588 if (i == 0 || name[i] != '\0') {
592 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
597 /* Check the node isn't already named */
598 if (node->name != NULL) {
603 /* Check the name isn't already being used */
604 if (ng_findname(node, name) != NULL) {
609 /* Allocate space and copy it */
610 MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
611 if (node->name == NULL) {
615 strcpy(node->name, name);
617 /* The name counts as a reference */
623 * Find a node by absolute name. The name should NOT end with ':'
624 * The name "." means "this node" and "[xxx]" means "the node
625 * with ID (ie, at address) xxx".
627 * Returns the node if found, else NULL.
630 ng_findname(node_p this, const char *name)
635 /* "." means "this node" */
636 if (strcmp(name, ".") == 0)
639 /* Check for name-by-ID */
640 if ((temp = ng_decodeidname(name)) != 0) {
641 return (ng_ID2node(temp));
644 /* Find node by name */
645 LIST_FOREACH(node, &nodelist, nodes) {
646 if ((node->name != NULL)
647 && (strcmp(node->name, name) == 0)
648 && ((node->flags & NG_INVALID) == 0))
655 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
656 * string is not valid, otherwise returns the value.
659 ng_decodeidname(const char *name)
661 const int len = strlen(name);
665 /* Check for proper length, brackets, no leading junk */
666 if (len < 3 || name[0] != '[' || name[len - 1] != ']'
667 || !isxdigit(name[1]))
671 val = strtoul(name + 1, &eptr, 16);
672 if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
678 * Remove a name from a node. This should only be called
679 * when shutting down and removing the node.
682 ng_unname(node_p node)
685 FREE(node->name, M_NETGRAPH);
691 /************************************************************************
694 Names are not optional. Hooks are always connected, except for a
695 brief moment within these routines.
697 ************************************************************************/
700 * Remove a hook reference
703 ng_unref_hook(hook_p hook)
706 if (--hook->refs == 0)
707 FREE(hook, M_NETGRAPH);
712 * Add an unconnected hook to a node. Only used internally.
715 ng_add_hook(node_p node, const char *name, hook_p *hookp)
720 /* Check that the given name is good */
725 if (ng_findhook(node, name) != NULL) {
730 /* Allocate the hook and link it up */
731 MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_NOWAIT);
736 bzero(hook, sizeof(*hook));
738 hook->flags = HK_INVALID;
740 node->refs++; /* each hook counts as a reference */
742 /* Check if the node type code has something to say about it */
743 if (node->type->newhook != NULL)
744 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
748 * The 'type' agrees so far, so go ahead and link it in.
749 * We'll ask again later when we actually connect the hooks.
751 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
755 MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
756 if (hook->name == NULL) {
758 LIST_REMOVE(hook, hooks);
763 ng_unref_hook(hook); /* this frees the hook */
766 strcpy(hook->name, name);
773 * Connect a pair of hooks. Only used internally.
776 ng_connect(hook_p hook1, hook_p hook2)
783 /* Give each node the opportunity to veto the impending connection */
784 if (hook1->node->type->connect) {
785 if ((error = (*hook1->node->type->connect) (hook1))) {
786 ng_destroy_hook(hook1); /* also zaps hook2 */
790 if (hook2->node->type->connect) {
791 if ((error = (*hook2->node->type->connect) (hook2))) {
792 ng_destroy_hook(hook2); /* also zaps hook1 */
796 hook1->flags &= ~HK_INVALID;
797 hook2->flags &= ~HK_INVALID;
804 * Node types may supply their own optimized routines for finding
805 * hooks. If none is supplied, we just do a linear search.
808 ng_findhook(node_p node, const char *name)
812 if (node->type->findhook != NULL)
813 return (*node->type->findhook)(node, name);
814 LIST_FOREACH(hook, &node->hooks, hooks) {
815 if (hook->name != NULL
816 && strcmp(hook->name, name) == 0
817 && (hook->flags & HK_INVALID) == 0)
826 * As hooks are always attached, this really destroys two hooks.
827 * The one given, and the one attached to it. Disconnect the hooks
828 * from each other first.
831 ng_destroy_hook(hook_p hook)
833 hook_p peer = hook->peer;
835 hook->flags |= HK_INVALID; /* as soon as possible */
837 peer->flags |= HK_INVALID; /* as soon as possible */
840 ng_disconnect_hook(peer);
842 ng_disconnect_hook(hook);
846 * Notify the node of the hook's demise. This may result in more actions
847 * (e.g. shutdown) but we don't do that ourselves and don't know what
848 * happens there. If there is no appropriate handler, then just remove it
849 * (and decrement the reference count of it's node which in turn might
850 * make something happen).
853 ng_disconnect_hook(hook_p hook)
855 node_p node = hook->node;
858 * Remove the hook from the node's list to avoid possible recursion
859 * in case the disconnection results in node shutdown.
861 LIST_REMOVE(hook, hooks);
863 if (node->type->disconnect) {
865 * The type handler may elect to destroy the peer so don't
866 * trust its existance after this point.
868 (*node->type->disconnect) (hook);
870 ng_unref(node); /* might be the last reference */
872 FREE(hook->name, M_NETGRAPH);
873 hook->node = NULL; /* may still be referenced elsewhere */
878 * Take two hooks on a node and merge the connection so that the given node
879 * is effectively bypassed.
882 ng_bypass(hook_p hook1, hook_p hook2)
884 if (hook1->node != hook2->node)
886 hook1->peer->peer = hook2->peer;
887 hook2->peer->peer = hook1->peer;
889 /* XXX If we ever cache methods on hooks update them as well */
892 ng_destroy_hook(hook1);
893 ng_destroy_hook(hook2);
898 * Install a new netgraph type
901 ng_newtype(struct ng_type *tp)
903 const size_t namelen = strlen(tp->name);
905 /* Check version and type name fields */
906 if (tp->version != NG_VERSION || namelen == 0 || namelen >= NG_TYPESIZ) {
911 /* Check for name collision */
912 if (ng_findtype(tp->name) != NULL) {
917 /* Link in new type */
918 LIST_INSERT_HEAD(&typelist, tp, types);
919 tp->refs = 1; /* first ref is linked list */
924 * Look for a type of the name given
927 ng_findtype(const char *typename)
929 struct ng_type *type;
931 LIST_FOREACH(type, &typelist, types) {
932 if (strcmp(type->name, typename) == 0)
939 /************************************************************************
941 ************************************************************************/
944 * Make a peer and connect. The order is arranged to minimise
945 * the work needed to back out in case of error.
948 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
955 if ((error = ng_add_hook(node, name, &hook)))
958 /* make sure we have the module needed */
959 if (ng_findtype(type) == NULL) {
960 /* Not found, try to load it as a loadable module */
961 error = ng_load_module(type);
963 kprintf("required netgraph module ng_%s not loaded\n",
968 if ((error = ng_make_node(type, &node2))) {
969 ng_destroy_hook(hook);
972 if ((error = ng_add_hook(node2, name2, &hook2))) {
974 ng_destroy_hook(hook);
979 * Actually link the two hooks together.. on failure they are
980 * destroyed so we don't have to do that here.
982 if ((error = ng_connect(hook, hook2)))
988 * Connect two nodes using the specified hooks
991 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
997 if ((error = ng_add_hook(node, name, &hook)))
999 if ((error = ng_add_hook(node2, name2, &hook2))) {
1000 ng_destroy_hook(hook);
1003 return (ng_connect(hook, hook2));
1007 * Parse and verify a string of the form: <NODE:><PATH>
1009 * Such a string can refer to a specific node or a specific hook
1010 * on a specific node, depending on how you look at it. In the
1011 * latter case, the PATH component must not end in a dot.
1013 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1014 * of hook names separated by dots. This breaks out the original
1015 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1016 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1017 * the final hook component of <PATH>, if any, otherwise NULL.
1019 * This returns -1 if the path is malformed. The char ** are optional.
1023 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1025 char *node, *path, *hook;
1029 * Extract absolute NODE, if any
1031 for (path = addr; *path && *path != ':'; path++);
1033 node = addr; /* Here's the NODE */
1034 *path++ = '\0'; /* Here's the PATH */
1036 /* Node name must not be empty */
1040 /* A name of "." is OK; otherwise '.' not allowed */
1041 if (strcmp(node, ".") != 0) {
1042 for (k = 0; node[k]; k++)
1047 node = NULL; /* No absolute NODE */
1048 path = addr; /* Here's the PATH */
1051 /* Snoop for illegal characters in PATH */
1052 for (k = 0; path[k]; k++)
1056 /* Check for no repeated dots in PATH */
1057 for (k = 0; path[k]; k++)
1058 if (path[k] == '.' && path[k + 1] == '.')
1061 /* Remove extra (degenerate) dots from beginning or end of PATH */
1064 if (*path && path[strlen(path) - 1] == '.')
1065 path[strlen(path) - 1] = 0;
1067 /* If PATH has a dot, then we're not talking about a hook */
1069 for (hook = path, k = 0; path[k]; k++)
1070 if (path[k] == '.') {
1088 * Given a path, which may be absolute or relative, and a starting node,
1089 * return the destination node. Compute the "return address" if desired.
1092 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1094 const node_p start = here;
1095 char fullpath[NG_PATHSIZ];
1096 char *nodename, *path, pbuf[2];
1107 /* Make a writable copy of address for ng_path_parse() */
1108 strncpy(fullpath, address, sizeof(fullpath) - 1);
1109 fullpath[sizeof(fullpath) - 1] = '\0';
1111 /* Parse out node and sequence of hooks */
1112 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1117 pbuf[0] = '.'; /* Needs to be writable */
1122 /* For an absolute address, jump to the starting node */
1124 node = ng_findname(here, nodename);
1132 /* Now follow the sequence of hooks */
1133 for (cp = path; node != NULL && *cp != '\0'; ) {
1138 * Break out the next path segment. Replace the dot we just
1139 * found with a NUL; "cp" points to the next segment (or the
1142 for (segment = cp; *cp != '\0'; cp++) {
1150 if (*segment == '\0')
1153 /* We have a segment, so look for a hook by that name */
1154 hook = ng_findhook(node, segment);
1156 /* Can't get there from here... */
1158 || hook->peer == NULL
1159 || (hook->flags & HK_INVALID) != 0) {
1164 /* Hop on over to the next node */
1165 node = hook->peer->node;
1168 /* If node somehow missing, fail here (probably this is not needed) */
1174 /* Now compute return address, i.e., the path to the sender */
1176 MALLOC(*rtnp, char *, NG_NODESIZ + 1, M_NETGRAPH, M_NOWAIT);
1177 if (*rtnp == NULL) {
1181 if (start->name != NULL)
1182 ksprintf(*rtnp, "%s:", start->name);
1184 ksprintf(*rtnp, "[%x]:", ng_node2ID(start));
1193 * Call the appropriate message handler for the object.
1194 * It is up to the message handler to free the message.
1195 * If it's a generic message, handle it generically, otherwise
1196 * call the type's message handler (if it exists)
1197 * XXX (race). Remember that a queued message may reference a node
1198 * or hook that has just been invalidated. It will exist
1199 * as the queue code is holding a reference, but..
1202 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1204 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1205 (error) = ng_generic_msg((node), (msg), \
1206 (retaddr), (resp)); \
1208 if ((node)->type->rcvmsg != NULL) { \
1209 (error) = (*(node)->type->rcvmsg)((node), \
1210 (msg), (retaddr), (resp)); \
1213 FREE((msg), M_NETGRAPH); \
1221 * Send a control message to a node
1224 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1225 struct ng_mesg **rptr)
1228 char *retaddr = NULL;
1231 /* Find the target node */
1232 error = ng_path2node(here, address, &dest, &retaddr);
1234 FREE(msg, M_NETGRAPH);
1238 /* Make sure the resp field is null before we start */
1242 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1244 /* Make sure that if there is a response, it has the RESP bit set */
1245 if ((error == 0) && rptr && *rptr)
1246 (*rptr)->header.flags |= NGF_RESP;
1249 * If we had a return address it is up to us to free it. They should
1250 * have taken a copy if they needed to make a delayed response.
1253 FREE(retaddr, M_NETGRAPH);
1258 * Implement the 'generic' control messages
1261 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1262 struct ng_mesg **resp)
1266 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1268 FREE(msg, M_NETGRAPH);
1271 switch (msg->header.cmd) {
1277 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1279 if (msg->header.arglen != sizeof(*mkp)) {
1283 mkp->type[sizeof(mkp->type) - 1] = '\0';
1284 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1285 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1286 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1291 struct ngm_connect *const con =
1292 (struct ngm_connect *) msg->data;
1295 if (msg->header.arglen != sizeof(*con)) {
1299 con->path[sizeof(con->path) - 1] = '\0';
1300 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1301 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1302 error = ng_path2node(here, con->path, &node2, NULL);
1305 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1310 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1312 if (msg->header.arglen != sizeof(*nam)) {
1316 nam->name[sizeof(nam->name) - 1] = '\0';
1317 error = ng_name_node(here, nam->name);
1322 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1325 if (msg->header.arglen != sizeof(*rmh)) {
1329 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1330 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1331 ng_destroy_hook(hook);
1336 struct nodeinfo *ni;
1339 /* Get response struct */
1344 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1350 /* Fill in node info */
1351 ni = (struct nodeinfo *) rp->data;
1352 if (here->name != NULL)
1353 strlcpy(ni->name, here->name, NG_NODESIZ);
1354 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1355 ni->id = ng_node2ID(here);
1356 ni->hooks = here->numhooks;
1362 const int nhooks = here->numhooks;
1363 struct hooklist *hl;
1364 struct nodeinfo *ni;
1368 /* Get response struct */
1373 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1374 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1379 hl = (struct hooklist *) rp->data;
1382 /* Fill in node info */
1384 strlcpy(ni->name, here->name, NG_NODESIZ);
1385 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1386 ni->id = ng_node2ID(here);
1388 /* Cycle through the linked list of hooks */
1390 LIST_FOREACH(hook, &here->hooks, hooks) {
1391 struct linkinfo *const link = &hl->link[ni->hooks];
1393 if (ni->hooks >= nhooks) {
1394 log(LOG_ERR, "%s: number of %s changed\n",
1398 if ((hook->flags & HK_INVALID) != 0)
1400 strlcpy(link->ourhook, hook->name, NG_HOOKSIZ);
1401 strlcpy(link->peerhook, hook->peer->name, NG_HOOKSIZ);
1402 if (hook->peer->node->name != NULL)
1403 strlcpy(link->nodeinfo.name,
1404 hook->peer->node->name, NG_NODESIZ);
1405 strlcpy(link->nodeinfo.type,
1406 hook->peer->node->type->name, NG_TYPESIZ);
1407 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1408 link->nodeinfo.hooks = hook->peer->node->numhooks;
1418 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1419 struct namelist *nl;
1429 /* Count number of nodes */
1430 LIST_FOREACH(node, &nodelist, nodes) {
1431 if ((node->flags & NG_INVALID) == 0
1432 && (unnamed || node->name != NULL))
1436 /* Get response struct */
1441 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1442 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1447 nl = (struct namelist *) rp->data;
1449 /* Cycle through the linked list of nodes */
1451 LIST_FOREACH(node, &nodelist, nodes) {
1452 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1454 if (nl->numnames >= num) {
1455 log(LOG_ERR, "%s: number of %s changed\n",
1459 if ((node->flags & NG_INVALID) != 0)
1461 if (!unnamed && node->name == NULL)
1463 if (node->name != NULL)
1464 strlcpy(np->name, node->name, NG_NODESIZ);
1465 strlcpy(np->type, node->type->name, NG_TYPESIZ);
1466 np->id = ng_node2ID(node);
1467 np->hooks = node->numhooks;
1476 struct typelist *tl;
1478 struct ng_type *type;
1486 /* Count number of types */
1487 LIST_FOREACH(type, &typelist, types)
1490 /* Get response struct */
1495 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1496 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1501 tl = (struct typelist *) rp->data;
1503 /* Cycle through the linked list of types */
1505 LIST_FOREACH(type, &typelist, types) {
1506 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1508 if (tl->numtypes >= num) {
1509 log(LOG_ERR, "%s: number of %s changed\n",
1513 strlcpy(tp->type_name, type->name, NG_TYPESIZ);
1514 tp->numnodes = type->refs - 1; /* don't count list */
1521 case NGM_BINARY2ASCII:
1523 int bufSize = 20 * 1024; /* XXX hard coded constant */
1524 const struct ng_parse_type *argstype;
1525 const struct ng_cmdlist *c;
1526 struct ng_mesg *rp, *binary, *ascii;
1528 /* Data area must contain a valid netgraph message */
1529 binary = (struct ng_mesg *)msg->data;
1530 if (msg->header.arglen < sizeof(struct ng_mesg)
1531 || msg->header.arglen - sizeof(struct ng_mesg)
1532 < binary->header.arglen) {
1537 /* Get a response message with lots of room */
1538 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1543 ascii = (struct ng_mesg *)rp->data;
1545 /* Copy binary message header to response message payload */
1546 bcopy(binary, ascii, sizeof(*binary));
1548 /* Find command by matching typecookie and command number */
1549 for (c = here->type->cmdlist;
1550 c != NULL && c->name != NULL; c++) {
1551 if (binary->header.typecookie == c->cookie
1552 && binary->header.cmd == c->cmd)
1555 if (c == NULL || c->name == NULL) {
1556 for (c = ng_generic_cmds; c->name != NULL; c++) {
1557 if (binary->header.typecookie == c->cookie
1558 && binary->header.cmd == c->cmd)
1561 if (c->name == NULL) {
1562 FREE(rp, M_NETGRAPH);
1568 /* Convert command name to ASCII */
1569 ksnprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1572 /* Convert command arguments to ASCII */
1573 argstype = (binary->header.flags & NGF_RESP) ?
1574 c->respType : c->mesgType;
1575 if (argstype == NULL)
1576 *ascii->data = '\0';
1578 if ((error = ng_unparse(argstype,
1579 (u_char *)binary->data,
1580 ascii->data, bufSize)) != 0) {
1581 FREE(rp, M_NETGRAPH);
1586 /* Return the result as struct ng_mesg plus ASCII string */
1587 bufSize = strlen(ascii->data) + 1;
1588 ascii->header.arglen = bufSize;
1589 rp->header.arglen = sizeof(*ascii) + bufSize;
1594 case NGM_ASCII2BINARY:
1596 int bufSize = 2000; /* XXX hard coded constant */
1597 const struct ng_cmdlist *c;
1598 const struct ng_parse_type *argstype;
1599 struct ng_mesg *rp, *ascii, *binary;
1602 /* Data area must contain at least a struct ng_mesg + '\0' */
1603 ascii = (struct ng_mesg *)msg->data;
1604 if (msg->header.arglen < sizeof(*ascii) + 1
1605 || ascii->header.arglen < 1
1606 || msg->header.arglen
1607 < sizeof(*ascii) + ascii->header.arglen) {
1611 ascii->data[ascii->header.arglen - 1] = '\0';
1613 /* Get a response message with lots of room */
1614 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1619 binary = (struct ng_mesg *)rp->data;
1621 /* Copy ASCII message header to response message payload */
1622 bcopy(ascii, binary, sizeof(*ascii));
1624 /* Find command by matching ASCII command string */
1625 for (c = here->type->cmdlist;
1626 c != NULL && c->name != NULL; c++) {
1627 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1630 if (c == NULL || c->name == NULL) {
1631 for (c = ng_generic_cmds; c->name != NULL; c++) {
1632 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1635 if (c->name == NULL) {
1636 FREE(rp, M_NETGRAPH);
1642 /* Convert command name to binary */
1643 binary->header.cmd = c->cmd;
1644 binary->header.typecookie = c->cookie;
1646 /* Convert command arguments to binary */
1647 argstype = (binary->header.flags & NGF_RESP) ?
1648 c->respType : c->mesgType;
1649 if (argstype == NULL)
1652 if ((error = ng_parse(argstype, ascii->data,
1653 &off, (u_char *)binary->data, &bufSize)) != 0) {
1654 FREE(rp, M_NETGRAPH);
1659 /* Return the result */
1660 binary->header.arglen = bufSize;
1661 rp->header.arglen = sizeof(*binary) + bufSize;
1666 case NGM_TEXT_CONFIG:
1667 case NGM_TEXT_STATUS:
1669 * This one is tricky as it passes the command down to the
1670 * actual node, even though it is a generic type command.
1671 * This means we must assume that the msg is already freed
1672 * when control passes back to us.
1678 if (here->type->rcvmsg != NULL)
1679 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1680 /* Fall through if rcvmsg not supported */
1685 FREE(msg, M_NETGRAPH);
1690 * Send a data packet to a node. If the recipient has no
1691 * 'receive data' method, then silently discard the packet.
1694 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1696 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1700 if (hook && (hook->flags & HK_INVALID) == 0) {
1701 rcvdata = hook->peer->node->type->rcvdata;
1702 if (rcvdata != NULL)
1703 error = (*rcvdata)(hook->peer, m, meta);
1706 NG_FREE_DATA(m, meta);
1711 NG_FREE_DATA(m, meta);
1717 * Send a queued data packet to a node. If the recipient has no
1718 * 'receive queued data' method, then try the 'receive data' method above.
1721 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1723 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1727 if (hook && (hook->flags & HK_INVALID) == 0) {
1728 rcvdataq = hook->peer->node->type->rcvdataq;
1729 if (rcvdataq != NULL)
1730 error = (*rcvdataq)(hook->peer, m, meta);
1732 error = ng_send_data(hook, m, meta);
1737 NG_FREE_DATA(m, meta);
1745 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1748 ng_copy_meta(meta_p meta)
1754 MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1757 meta2->allocated_len = meta->used_len;
1758 bcopy(meta, meta2, meta->used_len);
1762 /************************************************************************
1764 ************************************************************************/
1767 * Handle the loading/unloading of a netgraph node type module
1770 ng_mod_event(module_t mod, int event, void *data)
1772 struct ng_type *const type = data;
1778 /* Register new netgraph node type */
1780 if ((error = ng_newtype(type)) != 0) {
1785 /* Call type specific code */
1786 if (type->mod_event != NULL)
1787 if ((error = (*type->mod_event)(mod, event, data))) {
1788 type->refs--; /* undo it */
1789 LIST_REMOVE(type, types);
1796 if (type->refs > 1) { /* make sure no nodes exist! */
1799 if (type->refs == 0) {
1800 /* failed load, nothing to undo */
1804 if (type->mod_event != NULL) { /* check with type */
1805 error = (*type->mod_event)(mod, event, data);
1806 if (error != 0) { /* type refuses.. */
1811 LIST_REMOVE(type, types);
1817 if (type->mod_event != NULL)
1818 error = (*type->mod_event)(mod, event, data);
1820 error = 0; /* XXX ? */
1827 * Handle loading and unloading for this code.
1828 * The only thing we need to link into is the NETISR strucure.
1831 ngb_mod_event(module_t mod, int event, void *data)
1837 /* Register line discipline */
1839 error = ng_load_module("ksocket");
1844 netisr_register(NETISR_NETGRAPH, cpu0_portfn, ngintr);
1849 ng_unload_module("ksocket");
1850 /* You cant unload it because an interface may be using it. */
1860 static moduledata_t netgraph_mod = {
1865 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1866 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1867 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1868 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1870 /************************************************************************
1872 ************************************************************************/
1874 /* The structure for queueing across ISR switches */
1875 struct ng_queue_entry {
1877 struct ng_queue_entry *next;
1880 hook_p da_hook; /* target hook */
1885 struct ng_mesg *msg_msg;
1891 #define NGQF_DATA 0x01 /* the queue element is data */
1892 #define NGQF_MESG 0x02 /* the queue element is a message */
1894 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1895 static struct ng_queue_entry *ngqlast; /* last item queued */
1896 static const int ngqroom = 256; /* max items to queue */
1897 static int ngqsize; /* number of items in queue */
1899 static struct ng_queue_entry *ngqfree; /* free ones */
1900 static const int ngqfreemax = 256;/* cache at most this many */
1901 static int ngqfreesize; /* number of cached entries */
1906 static struct ng_queue_entry *
1909 struct ng_queue_entry *q;
1911 /* Could be guarding against tty ints or whatever */
1914 /* Try get a cached queue block, or else allocate a new one */
1915 if ((q = ngqfree) == NULL) {
1917 if (ngqsize < ngqroom) { /* don't worry about races */
1918 MALLOC(q, struct ng_queue_entry *,
1919 sizeof(*q), M_NETGRAPH, M_NOWAIT);
1930 * Release a queue entry
1932 #define RETURN_QBLK(q) \
1934 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1936 (q)->next = ngqfree; \
1941 FREE((q), M_NETGRAPH); \
1946 * Running at a raised (but we don't know which) processor priority level,
1947 * put the data onto a queue to be picked up by another PPL (probably splnet)
1950 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1952 struct ng_queue_entry *q;
1955 NG_FREE_DATA(m, meta);
1958 if ((q = ng_getqblk()) == NULL) {
1959 NG_FREE_DATA(m, meta);
1963 /* Fill out the contents */
1964 q->flags = NGQF_DATA;
1966 q->body.data.da_hook = hook;
1967 q->body.data.da_m = m;
1968 q->body.data.da_meta = meta;
1969 crit_enter(); /* protect refs and queue */
1970 hook->refs++; /* don't let it go away while on the queue */
1972 /* Put it on the queue */
1982 /* Schedule software interrupt to handle it later */
1983 schednetisr(NETISR_NETGRAPH);
1988 * Running at a raised (but we don't know which) processor priority level,
1989 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1992 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1994 struct ng_queue_entry *q;
1996 char *retaddr = NULL;
1999 /* Find the target node. */
2000 error = ng_path2node(here, address, &dest, &retaddr);
2002 FREE(msg, M_NETGRAPH);
2005 if ((q = ng_getqblk()) == NULL) {
2006 FREE(msg, M_NETGRAPH);
2008 FREE(retaddr, M_NETGRAPH);
2012 /* Fill out the contents */
2013 q->flags = NGQF_MESG;
2015 q->body.msg.msg_node = dest;
2016 q->body.msg.msg_msg = msg;
2017 q->body.msg.msg_retaddr = retaddr;
2018 crit_enter(); /* protect refs and queue */
2019 dest->refs++; /* don't let it go away while on the queue */
2021 /* Put it on the queue */
2031 /* Schedule software interrupt to handle it later */
2032 schednetisr(NETISR_NETGRAPH);
2037 * Pick an item off the queue, process it, and dispose of the queue entry.
2040 ngintr(struct netmsg *pmsg)
2044 struct ng_queue_entry *ngq;
2047 struct ng_mesg *msg;
2052 * Packets are never sent to this netisr so the message must always
2053 * be replied. Interlock processing and notification by replying
2054 * the message first.
2056 lwkt_replymsg(&pmsg->nm_lmsg, 0);
2060 if ((ngq = ngqbase)) {
2061 ngqbase = ngq->next;
2067 switch (ngq->flags) {
2069 hook = ngq->body.data.da_hook;
2070 m = ngq->body.data.da_m;
2071 meta = ngq->body.data.da_meta;
2073 NG_SEND_DATAQ(error, hook, m, meta);
2074 ng_unref_hook(hook);
2077 node = ngq->body.msg.msg_node;
2078 msg = ngq->body.msg.msg_msg;
2079 retaddr = ngq->body.msg.msg_retaddr;
2081 if (node->flags & NG_INVALID) {
2082 FREE(msg, M_NETGRAPH);
2084 CALL_MSG_HANDLER(error, node, msg,
2089 FREE(retaddr, M_NETGRAPH);