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.28 2008/09/24 14:26:39 sephe 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 lf->userrefs--; /* pretend kldunload'ed */
359 error = linker_file_unload(lf);
367 * Instantiate a node of the requested type
370 ng_make_node(const char *typename, node_p *nodepp)
372 struct ng_type *type;
374 /* Check that the type makes sense */
375 if (typename == NULL) {
380 /* Locate the node type */
381 if ((type = ng_findtype(typename)) == NULL)
384 /* Call the constructor */
385 if (type->constructor != NULL)
386 return ((*type->constructor)(nodepp));
388 return (ng_make_node_common(type, nodepp));
392 * Generic node creation. Called by node constructors.
393 * The returned node has a reference count of 1.
396 ng_make_node_common(struct ng_type *type, node_p *nodepp)
400 /* Require the node type to have been already installed */
401 if (ng_findtype(type->name) == NULL) {
406 /* Make a node and try attach it to the type */
407 MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_NOWAIT | M_ZERO);
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 | M_ZERO);
737 hook->flags = HK_INVALID;
739 node->refs++; /* each hook counts as a reference */
741 /* Check if the node type code has something to say about it */
742 if (node->type->newhook != NULL)
743 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
747 * The 'type' agrees so far, so go ahead and link it in.
748 * We'll ask again later when we actually connect the hooks.
750 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
754 MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
755 if (hook->name == NULL) {
757 LIST_REMOVE(hook, hooks);
762 ng_unref_hook(hook); /* this frees the hook */
765 strcpy(hook->name, name);
772 * Connect a pair of hooks. Only used internally.
775 ng_connect(hook_p hook1, hook_p hook2)
782 /* Give each node the opportunity to veto the impending connection */
783 if (hook1->node->type->connect) {
784 if ((error = (*hook1->node->type->connect) (hook1))) {
785 ng_destroy_hook(hook1); /* also zaps hook2 */
789 if (hook2->node->type->connect) {
790 if ((error = (*hook2->node->type->connect) (hook2))) {
791 ng_destroy_hook(hook2); /* also zaps hook1 */
795 hook1->flags &= ~HK_INVALID;
796 hook2->flags &= ~HK_INVALID;
803 * Node types may supply their own optimized routines for finding
804 * hooks. If none is supplied, we just do a linear search.
807 ng_findhook(node_p node, const char *name)
811 if (node->type->findhook != NULL)
812 return (*node->type->findhook)(node, name);
813 LIST_FOREACH(hook, &node->hooks, hooks) {
814 if (hook->name != NULL
815 && strcmp(hook->name, name) == 0
816 && (hook->flags & HK_INVALID) == 0)
825 * As hooks are always attached, this really destroys two hooks.
826 * The one given, and the one attached to it. Disconnect the hooks
827 * from each other first.
830 ng_destroy_hook(hook_p hook)
832 hook_p peer = hook->peer;
834 hook->flags |= HK_INVALID; /* as soon as possible */
836 peer->flags |= HK_INVALID; /* as soon as possible */
839 ng_disconnect_hook(peer);
841 ng_disconnect_hook(hook);
845 * Notify the node of the hook's demise. This may result in more actions
846 * (e.g. shutdown) but we don't do that ourselves and don't know what
847 * happens there. If there is no appropriate handler, then just remove it
848 * (and decrement the reference count of it's node which in turn might
849 * make something happen).
852 ng_disconnect_hook(hook_p hook)
854 node_p node = hook->node;
857 * Remove the hook from the node's list to avoid possible recursion
858 * in case the disconnection results in node shutdown.
860 LIST_REMOVE(hook, hooks);
862 if (node->type->disconnect) {
864 * The type handler may elect to destroy the peer so don't
865 * trust its existance after this point.
867 (*node->type->disconnect) (hook);
869 ng_unref(node); /* might be the last reference */
871 FREE(hook->name, M_NETGRAPH);
872 hook->node = NULL; /* may still be referenced elsewhere */
877 * Take two hooks on a node and merge the connection so that the given node
878 * is effectively bypassed.
881 ng_bypass(hook_p hook1, hook_p hook2)
883 if (hook1->node != hook2->node)
885 hook1->peer->peer = hook2->peer;
886 hook2->peer->peer = hook1->peer;
888 /* XXX If we ever cache methods on hooks update them as well */
891 ng_destroy_hook(hook1);
892 ng_destroy_hook(hook2);
897 * Install a new netgraph type
900 ng_newtype(struct ng_type *tp)
902 const size_t namelen = strlen(tp->name);
904 /* Check version and type name fields */
905 if (tp->version != NG_VERSION || namelen == 0 || namelen >= NG_TYPESIZ) {
910 /* Check for name collision */
911 if (ng_findtype(tp->name) != NULL) {
916 /* Link in new type */
917 LIST_INSERT_HEAD(&typelist, tp, types);
918 tp->refs = 1; /* first ref is linked list */
923 * Look for a type of the name given
926 ng_findtype(const char *typename)
928 struct ng_type *type;
930 LIST_FOREACH(type, &typelist, types) {
931 if (strcmp(type->name, typename) == 0)
938 /************************************************************************
940 ************************************************************************/
943 * Make a peer and connect. The order is arranged to minimise
944 * the work needed to back out in case of error.
947 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
954 if ((error = ng_add_hook(node, name, &hook)))
957 /* make sure we have the module needed */
958 if (ng_findtype(type) == NULL) {
959 /* Not found, try to load it as a loadable module */
960 error = ng_load_module(type);
962 kprintf("required netgraph module ng_%s not loaded\n",
967 if ((error = ng_make_node(type, &node2))) {
968 ng_destroy_hook(hook);
971 if ((error = ng_add_hook(node2, name2, &hook2))) {
973 ng_destroy_hook(hook);
978 * Actually link the two hooks together.. on failure they are
979 * destroyed so we don't have to do that here.
981 if ((error = ng_connect(hook, hook2)))
987 * Connect two nodes using the specified hooks
990 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
996 if ((error = ng_add_hook(node, name, &hook)))
998 if ((error = ng_add_hook(node2, name2, &hook2))) {
999 ng_destroy_hook(hook);
1002 return (ng_connect(hook, hook2));
1006 * Parse and verify a string of the form: <NODE:><PATH>
1008 * Such a string can refer to a specific node or a specific hook
1009 * on a specific node, depending on how you look at it. In the
1010 * latter case, the PATH component must not end in a dot.
1012 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1013 * of hook names separated by dots. This breaks out the original
1014 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1015 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1016 * the final hook component of <PATH>, if any, otherwise NULL.
1018 * This returns -1 if the path is malformed. The char ** are optional.
1022 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1024 char *node, *path, *hook;
1028 * Extract absolute NODE, if any
1030 for (path = addr; *path && *path != ':'; path++);
1032 node = addr; /* Here's the NODE */
1033 *path++ = '\0'; /* Here's the PATH */
1035 /* Node name must not be empty */
1039 /* A name of "." is OK; otherwise '.' not allowed */
1040 if (strcmp(node, ".") != 0) {
1041 for (k = 0; node[k]; k++)
1046 node = NULL; /* No absolute NODE */
1047 path = addr; /* Here's the PATH */
1050 /* Snoop for illegal characters in PATH */
1051 for (k = 0; path[k]; k++)
1055 /* Check for no repeated dots in PATH */
1056 for (k = 0; path[k]; k++)
1057 if (path[k] == '.' && path[k + 1] == '.')
1060 /* Remove extra (degenerate) dots from beginning or end of PATH */
1063 if (*path && path[strlen(path) - 1] == '.')
1064 path[strlen(path) - 1] = 0;
1066 /* If PATH has a dot, then we're not talking about a hook */
1068 for (hook = path, k = 0; path[k]; k++)
1069 if (path[k] == '.') {
1087 * Given a path, which may be absolute or relative, and a starting node,
1088 * return the destination node. Compute the "return address" if desired.
1091 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1093 const node_p start = here;
1094 char fullpath[NG_PATHSIZ];
1095 char *nodename, *path, pbuf[2];
1106 /* Make a writable copy of address for ng_path_parse() */
1107 strncpy(fullpath, address, sizeof(fullpath) - 1);
1108 fullpath[sizeof(fullpath) - 1] = '\0';
1110 /* Parse out node and sequence of hooks */
1111 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1116 pbuf[0] = '.'; /* Needs to be writable */
1121 /* For an absolute address, jump to the starting node */
1123 node = ng_findname(here, nodename);
1131 /* Now follow the sequence of hooks */
1132 for (cp = path; node != NULL && *cp != '\0'; ) {
1137 * Break out the next path segment. Replace the dot we just
1138 * found with a NUL; "cp" points to the next segment (or the
1141 for (segment = cp; *cp != '\0'; cp++) {
1149 if (*segment == '\0')
1152 /* We have a segment, so look for a hook by that name */
1153 hook = ng_findhook(node, segment);
1155 /* Can't get there from here... */
1157 || hook->peer == NULL
1158 || (hook->flags & HK_INVALID) != 0) {
1163 /* Hop on over to the next node */
1164 node = hook->peer->node;
1167 /* If node somehow missing, fail here (probably this is not needed) */
1173 /* Now compute return address, i.e., the path to the sender */
1175 MALLOC(*rtnp, char *, NG_NODESIZ + 1, M_NETGRAPH, M_NOWAIT);
1176 if (*rtnp == NULL) {
1180 if (start->name != NULL)
1181 ksprintf(*rtnp, "%s:", start->name);
1183 ksprintf(*rtnp, "[%x]:", ng_node2ID(start));
1192 * Call the appropriate message handler for the object.
1193 * It is up to the message handler to free the message.
1194 * If it's a generic message, handle it generically, otherwise
1195 * call the type's message handler (if it exists)
1196 * XXX (race). Remember that a queued message may reference a node
1197 * or hook that has just been invalidated. It will exist
1198 * as the queue code is holding a reference, but..
1201 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1203 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1204 (error) = ng_generic_msg((node), (msg), \
1205 (retaddr), (resp)); \
1207 if ((node)->type->rcvmsg != NULL) { \
1208 (error) = (*(node)->type->rcvmsg)((node), \
1209 (msg), (retaddr), (resp)); \
1212 FREE((msg), M_NETGRAPH); \
1220 * Send a control message to a node
1223 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1224 struct ng_mesg **rptr)
1227 char *retaddr = NULL;
1230 /* Find the target node */
1231 error = ng_path2node(here, address, &dest, &retaddr);
1233 FREE(msg, M_NETGRAPH);
1237 /* Make sure the resp field is null before we start */
1241 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1243 /* Make sure that if there is a response, it has the RESP bit set */
1244 if ((error == 0) && rptr && *rptr)
1245 (*rptr)->header.flags |= NGF_RESP;
1248 * If we had a return address it is up to us to free it. They should
1249 * have taken a copy if they needed to make a delayed response.
1252 FREE(retaddr, M_NETGRAPH);
1257 * Implement the 'generic' control messages
1260 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1261 struct ng_mesg **resp)
1265 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1267 FREE(msg, M_NETGRAPH);
1270 switch (msg->header.cmd) {
1276 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1278 if (msg->header.arglen != sizeof(*mkp)) {
1282 mkp->type[sizeof(mkp->type) - 1] = '\0';
1283 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1284 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1285 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1290 struct ngm_connect *const con =
1291 (struct ngm_connect *) msg->data;
1294 if (msg->header.arglen != sizeof(*con)) {
1298 con->path[sizeof(con->path) - 1] = '\0';
1299 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1300 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1301 error = ng_path2node(here, con->path, &node2, NULL);
1304 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1309 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1311 if (msg->header.arglen != sizeof(*nam)) {
1315 nam->name[sizeof(nam->name) - 1] = '\0';
1316 error = ng_name_node(here, nam->name);
1321 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1324 if (msg->header.arglen != sizeof(*rmh)) {
1328 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1329 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1330 ng_destroy_hook(hook);
1335 struct nodeinfo *ni;
1338 /* Get response struct */
1343 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1349 /* Fill in node info */
1350 ni = (struct nodeinfo *) rp->data;
1351 if (here->name != NULL)
1352 strlcpy(ni->name, here->name, NG_NODESIZ);
1353 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1354 ni->id = ng_node2ID(here);
1355 ni->hooks = here->numhooks;
1361 const int nhooks = here->numhooks;
1362 struct hooklist *hl;
1363 struct nodeinfo *ni;
1367 /* Get response struct */
1372 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1373 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1378 hl = (struct hooklist *) rp->data;
1381 /* Fill in node info */
1383 strlcpy(ni->name, here->name, NG_NODESIZ);
1384 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1385 ni->id = ng_node2ID(here);
1387 /* Cycle through the linked list of hooks */
1389 LIST_FOREACH(hook, &here->hooks, hooks) {
1390 struct linkinfo *const link = &hl->link[ni->hooks];
1392 if (ni->hooks >= nhooks) {
1393 log(LOG_ERR, "%s: number of %s changed\n",
1397 if ((hook->flags & HK_INVALID) != 0)
1399 strlcpy(link->ourhook, hook->name, NG_HOOKSIZ);
1400 strlcpy(link->peerhook, hook->peer->name, NG_HOOKSIZ);
1401 if (hook->peer->node->name != NULL)
1402 strlcpy(link->nodeinfo.name,
1403 hook->peer->node->name, NG_NODESIZ);
1404 strlcpy(link->nodeinfo.type,
1405 hook->peer->node->type->name, NG_TYPESIZ);
1406 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1407 link->nodeinfo.hooks = hook->peer->node->numhooks;
1417 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1418 struct namelist *nl;
1428 /* Count number of nodes */
1429 LIST_FOREACH(node, &nodelist, nodes) {
1430 if ((node->flags & NG_INVALID) == 0
1431 && (unnamed || node->name != NULL))
1435 /* Get response struct */
1440 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1441 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1446 nl = (struct namelist *) rp->data;
1448 /* Cycle through the linked list of nodes */
1450 LIST_FOREACH(node, &nodelist, nodes) {
1451 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1453 if (nl->numnames >= num) {
1454 log(LOG_ERR, "%s: number of %s changed\n",
1458 if ((node->flags & NG_INVALID) != 0)
1460 if (!unnamed && node->name == NULL)
1462 if (node->name != NULL)
1463 strlcpy(np->name, node->name, NG_NODESIZ);
1464 strlcpy(np->type, node->type->name, NG_TYPESIZ);
1465 np->id = ng_node2ID(node);
1466 np->hooks = node->numhooks;
1475 struct typelist *tl;
1477 struct ng_type *type;
1485 /* Count number of types */
1486 LIST_FOREACH(type, &typelist, types)
1489 /* Get response struct */
1494 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1495 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1500 tl = (struct typelist *) rp->data;
1502 /* Cycle through the linked list of types */
1504 LIST_FOREACH(type, &typelist, types) {
1505 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1507 if (tl->numtypes >= num) {
1508 log(LOG_ERR, "%s: number of %s changed\n",
1512 strlcpy(tp->type_name, type->name, NG_TYPESIZ);
1513 tp->numnodes = type->refs - 1; /* don't count list */
1520 case NGM_BINARY2ASCII:
1522 int bufSize = 20 * 1024; /* XXX hard coded constant */
1523 const struct ng_parse_type *argstype;
1524 const struct ng_cmdlist *c;
1525 struct ng_mesg *rp, *binary, *ascii;
1527 /* Data area must contain a valid netgraph message */
1528 binary = (struct ng_mesg *)msg->data;
1529 if (msg->header.arglen < sizeof(struct ng_mesg)
1530 || msg->header.arglen - sizeof(struct ng_mesg)
1531 < binary->header.arglen) {
1536 /* Get a response message with lots of room */
1537 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1542 ascii = (struct ng_mesg *)rp->data;
1544 /* Copy binary message header to response message payload */
1545 bcopy(binary, ascii, sizeof(*binary));
1547 /* Find command by matching typecookie and command number */
1548 for (c = here->type->cmdlist;
1549 c != NULL && c->name != NULL; c++) {
1550 if (binary->header.typecookie == c->cookie
1551 && binary->header.cmd == c->cmd)
1554 if (c == NULL || c->name == NULL) {
1555 for (c = ng_generic_cmds; c->name != NULL; c++) {
1556 if (binary->header.typecookie == c->cookie
1557 && binary->header.cmd == c->cmd)
1560 if (c->name == NULL) {
1561 FREE(rp, M_NETGRAPH);
1567 /* Convert command name to ASCII */
1568 ksnprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1571 /* Convert command arguments to ASCII */
1572 argstype = (binary->header.flags & NGF_RESP) ?
1573 c->respType : c->mesgType;
1574 if (argstype == NULL)
1575 *ascii->data = '\0';
1577 if ((error = ng_unparse(argstype,
1578 (u_char *)binary->data,
1579 ascii->data, bufSize)) != 0) {
1580 FREE(rp, M_NETGRAPH);
1585 /* Return the result as struct ng_mesg plus ASCII string */
1586 bufSize = strlen(ascii->data) + 1;
1587 ascii->header.arglen = bufSize;
1588 rp->header.arglen = sizeof(*ascii) + bufSize;
1593 case NGM_ASCII2BINARY:
1595 int bufSize = 2000; /* XXX hard coded constant */
1596 const struct ng_cmdlist *c;
1597 const struct ng_parse_type *argstype;
1598 struct ng_mesg *rp, *ascii, *binary;
1601 /* Data area must contain at least a struct ng_mesg + '\0' */
1602 ascii = (struct ng_mesg *)msg->data;
1603 if (msg->header.arglen < sizeof(*ascii) + 1
1604 || ascii->header.arglen < 1
1605 || msg->header.arglen
1606 < sizeof(*ascii) + ascii->header.arglen) {
1610 ascii->data[ascii->header.arglen - 1] = '\0';
1612 /* Get a response message with lots of room */
1613 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1618 binary = (struct ng_mesg *)rp->data;
1620 /* Copy ASCII message header to response message payload */
1621 bcopy(ascii, binary, sizeof(*ascii));
1623 /* Find command by matching ASCII command string */
1624 for (c = here->type->cmdlist;
1625 c != NULL && c->name != NULL; c++) {
1626 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1629 if (c == NULL || c->name == NULL) {
1630 for (c = ng_generic_cmds; c->name != NULL; c++) {
1631 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1634 if (c->name == NULL) {
1635 FREE(rp, M_NETGRAPH);
1641 /* Convert command name to binary */
1642 binary->header.cmd = c->cmd;
1643 binary->header.typecookie = c->cookie;
1645 /* Convert command arguments to binary */
1646 argstype = (binary->header.flags & NGF_RESP) ?
1647 c->respType : c->mesgType;
1648 if (argstype == NULL)
1651 if ((error = ng_parse(argstype, ascii->data,
1652 &off, (u_char *)binary->data, &bufSize)) != 0) {
1653 FREE(rp, M_NETGRAPH);
1658 /* Return the result */
1659 binary->header.arglen = bufSize;
1660 rp->header.arglen = sizeof(*binary) + bufSize;
1665 case NGM_TEXT_CONFIG:
1666 case NGM_TEXT_STATUS:
1668 * This one is tricky as it passes the command down to the
1669 * actual node, even though it is a generic type command.
1670 * This means we must assume that the msg is already freed
1671 * when control passes back to us.
1677 if (here->type->rcvmsg != NULL)
1678 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1679 /* Fall through if rcvmsg not supported */
1684 FREE(msg, M_NETGRAPH);
1689 * Send a data packet to a node. If the recipient has no
1690 * 'receive data' method, then silently discard the packet.
1693 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1695 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1699 if (hook && (hook->flags & HK_INVALID) == 0) {
1700 rcvdata = hook->peer->node->type->rcvdata;
1701 if (rcvdata != NULL)
1702 error = (*rcvdata)(hook->peer, m, meta);
1705 NG_FREE_DATA(m, meta);
1710 NG_FREE_DATA(m, meta);
1716 * Send a queued data packet to a node. If the recipient has no
1717 * 'receive queued data' method, then try the 'receive data' method above.
1720 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1722 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1726 if (hook && (hook->flags & HK_INVALID) == 0) {
1727 rcvdataq = hook->peer->node->type->rcvdataq;
1728 if (rcvdataq != NULL)
1729 error = (*rcvdataq)(hook->peer, m, meta);
1731 error = ng_send_data(hook, m, meta);
1736 NG_FREE_DATA(m, meta);
1744 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1747 ng_copy_meta(meta_p meta)
1753 MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1756 meta2->allocated_len = meta->used_len;
1757 bcopy(meta, meta2, meta->used_len);
1761 /************************************************************************
1763 ************************************************************************/
1766 * Handle the loading/unloading of a netgraph node type module
1769 ng_mod_event(module_t mod, int event, void *data)
1771 struct ng_type *const type = data;
1777 /* Register new netgraph node type */
1779 if ((error = ng_newtype(type)) != 0) {
1784 /* Call type specific code */
1785 if (type->mod_event != NULL)
1786 if ((error = (*type->mod_event)(mod, event, data))) {
1787 type->refs--; /* undo it */
1788 LIST_REMOVE(type, types);
1795 if (type->refs > 1) { /* make sure no nodes exist! */
1798 if (type->refs == 0) {
1799 /* failed load, nothing to undo */
1803 if (type->mod_event != NULL) { /* check with type */
1804 error = (*type->mod_event)(mod, event, data);
1805 if (error != 0) { /* type refuses.. */
1810 LIST_REMOVE(type, types);
1816 if (type->mod_event != NULL)
1817 error = (*type->mod_event)(mod, event, data);
1819 error = 0; /* XXX ? */
1826 * Handle loading and unloading for this code.
1827 * The only thing we need to link into is the NETISR strucure.
1830 ngb_mod_event(module_t mod, int event, void *data)
1836 /* Register line discipline */
1838 error = ng_load_module("ksocket");
1843 netisr_register(NETISR_NETGRAPH, cpu0_portfn,
1844 pktinfo_portfn_notsupp, ngintr,
1845 NETISR_FLAG_NOTMPSAFE);
1850 ng_unload_module("ksocket");
1851 /* You cant unload it because an interface may be using it. */
1861 static moduledata_t netgraph_mod = {
1866 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1867 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1868 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1869 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1871 /************************************************************************
1873 ************************************************************************/
1875 /* The structure for queueing across ISR switches */
1876 struct ng_queue_entry {
1878 struct ng_queue_entry *next;
1881 hook_p da_hook; /* target hook */
1886 struct ng_mesg *msg_msg;
1892 #define NGQF_DATA 0x01 /* the queue element is data */
1893 #define NGQF_MESG 0x02 /* the queue element is a message */
1895 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1896 static struct ng_queue_entry *ngqlast; /* last item queued */
1897 static const int ngqroom = 256; /* max items to queue */
1898 static int ngqsize; /* number of items in queue */
1900 static struct ng_queue_entry *ngqfree; /* free ones */
1901 static const int ngqfreemax = 256;/* cache at most this many */
1902 static int ngqfreesize; /* number of cached entries */
1907 static struct ng_queue_entry *
1910 struct ng_queue_entry *q;
1912 /* Could be guarding against tty ints or whatever */
1915 /* Try get a cached queue block, or else allocate a new one */
1916 if ((q = ngqfree) == NULL) {
1918 if (ngqsize < ngqroom) { /* don't worry about races */
1919 MALLOC(q, struct ng_queue_entry *,
1920 sizeof(*q), M_NETGRAPH, M_NOWAIT);
1931 * Release a queue entry
1933 #define RETURN_QBLK(q) \
1935 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1937 (q)->next = ngqfree; \
1942 FREE((q), M_NETGRAPH); \
1947 * Running at a raised (but we don't know which) processor priority level,
1948 * put the data onto a queue to be picked up by another PPL (probably splnet)
1951 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1953 struct ng_queue_entry *q;
1956 NG_FREE_DATA(m, meta);
1959 if ((q = ng_getqblk()) == NULL) {
1960 NG_FREE_DATA(m, meta);
1964 /* Fill out the contents */
1965 q->flags = NGQF_DATA;
1967 q->body.data.da_hook = hook;
1968 q->body.data.da_m = m;
1969 q->body.data.da_meta = meta;
1970 crit_enter(); /* protect refs and queue */
1971 hook->refs++; /* don't let it go away while on the queue */
1973 /* Put it on the queue */
1983 /* Schedule software interrupt to handle it later */
1984 schednetisr(NETISR_NETGRAPH);
1989 * Running at a raised (but we don't know which) processor priority level,
1990 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1993 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1995 struct ng_queue_entry *q;
1997 char *retaddr = NULL;
2000 /* Find the target node. */
2001 error = ng_path2node(here, address, &dest, &retaddr);
2003 FREE(msg, M_NETGRAPH);
2006 if ((q = ng_getqblk()) == NULL) {
2007 FREE(msg, M_NETGRAPH);
2009 FREE(retaddr, M_NETGRAPH);
2013 /* Fill out the contents */
2014 q->flags = NGQF_MESG;
2016 q->body.msg.msg_node = dest;
2017 q->body.msg.msg_msg = msg;
2018 q->body.msg.msg_retaddr = retaddr;
2019 crit_enter(); /* protect refs and queue */
2020 dest->refs++; /* don't let it go away while on the queue */
2022 /* Put it on the queue */
2032 /* Schedule software interrupt to handle it later */
2033 schednetisr(NETISR_NETGRAPH);
2038 * Pick an item off the queue, process it, and dispose of the queue entry.
2041 ngintr(struct netmsg *pmsg)
2045 struct ng_queue_entry *ngq;
2048 struct ng_mesg *msg;
2053 * Packets are never sent to this netisr so the message must always
2054 * be replied. Interlock processing and notification by replying
2055 * the message first.
2057 lwkt_replymsg(&pmsg->nm_lmsg, 0);
2061 if ((ngq = ngqbase)) {
2062 ngqbase = ngq->next;
2068 switch (ngq->flags) {
2070 hook = ngq->body.data.da_hook;
2071 m = ngq->body.data.da_m;
2072 meta = ngq->body.data.da_meta;
2074 NG_SEND_DATAQ(error, hook, m, meta);
2075 ng_unref_hook(hook);
2078 node = ngq->body.msg.msg_node;
2079 msg = ngq->body.msg.msg_msg;
2080 retaddr = ngq->body.msg.msg_retaddr;
2082 if (node->flags & NG_INVALID) {
2083 FREE(msg, M_NETGRAPH);
2085 CALL_MSG_HANDLER(error, node, msg,
2090 FREE(retaddr, M_NETGRAPH);