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.26 2008/01/05 14:02:39 swildner 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 | M_ZERO);
412 node->refs++; /* note reference */
415 /* Link us into the node linked list */
416 LIST_INSERT_HEAD(&nodelist, node, nodes);
418 /* Initialize hook list for new node */
419 LIST_INIT(&node->hooks);
421 /* get an ID and put us in the hash chain */
422 node->ID = nextID++; /* 137 per second for 1 year before wrap */
423 LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
431 * Forceably start the shutdown process on a node. Either call
432 * it's shutdown method, or do the default shutdown if there is
433 * no type-specific method.
435 * Persistent nodes must have a type-specific method which
436 * resets the NG_INVALID flag.
439 ng_rmnode(node_p node)
441 /* Check if it's already shutting down */
442 if ((node->flags & NG_INVALID) != 0)
445 /* Add an extra reference so it doesn't go away during this */
448 /* Mark it invalid so any newcomers know not to try use it */
449 node->flags |= NG_INVALID;
451 /* Ask the type if it has anything to do in this case */
452 if (node->type && node->type->shutdown)
453 (*node->type->shutdown)(node);
454 else { /* do the default thing */
460 /* Remove extra reference, possibly the last */
465 * Called by the destructor to remove any STANDARD external references
468 ng_cutlinks(node_p node)
472 /* Make sure that this is set to stop infinite loops */
473 node->flags |= NG_INVALID;
475 /* If we have sleepers, wake them up; they'll see NG_INVALID */
479 /* Notify all remaining connected nodes to disconnect */
480 while ((hook = LIST_FIRST(&node->hooks)) != NULL)
481 ng_destroy_hook(hook);
485 * Remove a reference to the node, possibly the last
488 ng_unref(node_p node)
491 if (--node->refs <= 0) {
493 LIST_REMOVE(node, nodes);
494 LIST_REMOVE(node, idnodes);
495 FREE(node, M_NETGRAPH);
501 * Wait for a node to come ready. Returns a node with a reference count;
502 * don't forget to drop it when we are done with it using ng_release_node().
505 ng_wait_node(node_p node, char *msg)
513 node->refs++; /* the sleeping process counts as a reference */
514 while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
515 error = tsleep(node, PCATCH, msg, 0);
517 if (node->flags & NG_INVALID) {
521 KASSERT(node->refs > 1,
522 ("%s: refs=%d", __func__, node->refs));
523 node->flags |= NG_BUSY;
527 /* Release the reference we had on it */
534 * Release a node acquired via ng_wait_node()
537 ng_release_node(node_p node)
539 /* Declare that we don't want it */
540 node->flags &= ~NG_BUSY;
542 /* If we have sleepers, then wake them up */
546 /* We also have a reference.. drop it too */
550 /************************************************************************
552 ************************************************************************/
554 ng_ID2node(ng_ID_t ID)
557 LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
558 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
565 ng_node2ID(node_p node)
570 /************************************************************************
572 ************************************************************************/
575 * Assign a node a name. Once assigned, the name cannot be changed.
578 ng_name_node(node_p node, const char *name)
582 /* Check the name is valid */
583 for (i = 0; i < NG_NODESIZ; i++) {
584 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
587 if (i == 0 || name[i] != '\0') {
591 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
596 /* Check the node isn't already named */
597 if (node->name != NULL) {
602 /* Check the name isn't already being used */
603 if (ng_findname(node, name) != NULL) {
608 /* Allocate space and copy it */
609 MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
610 if (node->name == NULL) {
614 strcpy(node->name, name);
616 /* The name counts as a reference */
622 * Find a node by absolute name. The name should NOT end with ':'
623 * The name "." means "this node" and "[xxx]" means "the node
624 * with ID (ie, at address) xxx".
626 * Returns the node if found, else NULL.
629 ng_findname(node_p this, const char *name)
634 /* "." means "this node" */
635 if (strcmp(name, ".") == 0)
638 /* Check for name-by-ID */
639 if ((temp = ng_decodeidname(name)) != 0) {
640 return (ng_ID2node(temp));
643 /* Find node by name */
644 LIST_FOREACH(node, &nodelist, nodes) {
645 if ((node->name != NULL)
646 && (strcmp(node->name, name) == 0)
647 && ((node->flags & NG_INVALID) == 0))
654 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
655 * string is not valid, otherwise returns the value.
658 ng_decodeidname(const char *name)
660 const int len = strlen(name);
664 /* Check for proper length, brackets, no leading junk */
665 if (len < 3 || name[0] != '[' || name[len - 1] != ']'
666 || !isxdigit(name[1]))
670 val = strtoul(name + 1, &eptr, 16);
671 if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
677 * Remove a name from a node. This should only be called
678 * when shutting down and removing the node.
681 ng_unname(node_p node)
684 FREE(node->name, M_NETGRAPH);
690 /************************************************************************
693 Names are not optional. Hooks are always connected, except for a
694 brief moment within these routines.
696 ************************************************************************/
699 * Remove a hook reference
702 ng_unref_hook(hook_p hook)
705 if (--hook->refs == 0)
706 FREE(hook, M_NETGRAPH);
711 * Add an unconnected hook to a node. Only used internally.
714 ng_add_hook(node_p node, const char *name, hook_p *hookp)
719 /* Check that the given name is good */
724 if (ng_findhook(node, name) != NULL) {
729 /* Allocate the hook and link it up */
730 MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_NOWAIT | M_ZERO);
736 hook->flags = HK_INVALID;
738 node->refs++; /* each hook counts as a reference */
740 /* Check if the node type code has something to say about it */
741 if (node->type->newhook != NULL)
742 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
746 * The 'type' agrees so far, so go ahead and link it in.
747 * We'll ask again later when we actually connect the hooks.
749 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
753 MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
754 if (hook->name == NULL) {
756 LIST_REMOVE(hook, hooks);
761 ng_unref_hook(hook); /* this frees the hook */
764 strcpy(hook->name, name);
771 * Connect a pair of hooks. Only used internally.
774 ng_connect(hook_p hook1, hook_p hook2)
781 /* Give each node the opportunity to veto the impending connection */
782 if (hook1->node->type->connect) {
783 if ((error = (*hook1->node->type->connect) (hook1))) {
784 ng_destroy_hook(hook1); /* also zaps hook2 */
788 if (hook2->node->type->connect) {
789 if ((error = (*hook2->node->type->connect) (hook2))) {
790 ng_destroy_hook(hook2); /* also zaps hook1 */
794 hook1->flags &= ~HK_INVALID;
795 hook2->flags &= ~HK_INVALID;
802 * Node types may supply their own optimized routines for finding
803 * hooks. If none is supplied, we just do a linear search.
806 ng_findhook(node_p node, const char *name)
810 if (node->type->findhook != NULL)
811 return (*node->type->findhook)(node, name);
812 LIST_FOREACH(hook, &node->hooks, hooks) {
813 if (hook->name != NULL
814 && strcmp(hook->name, name) == 0
815 && (hook->flags & HK_INVALID) == 0)
824 * As hooks are always attached, this really destroys two hooks.
825 * The one given, and the one attached to it. Disconnect the hooks
826 * from each other first.
829 ng_destroy_hook(hook_p hook)
831 hook_p peer = hook->peer;
833 hook->flags |= HK_INVALID; /* as soon as possible */
835 peer->flags |= HK_INVALID; /* as soon as possible */
838 ng_disconnect_hook(peer);
840 ng_disconnect_hook(hook);
844 * Notify the node of the hook's demise. This may result in more actions
845 * (e.g. shutdown) but we don't do that ourselves and don't know what
846 * happens there. If there is no appropriate handler, then just remove it
847 * (and decrement the reference count of it's node which in turn might
848 * make something happen).
851 ng_disconnect_hook(hook_p hook)
853 node_p node = hook->node;
856 * Remove the hook from the node's list to avoid possible recursion
857 * in case the disconnection results in node shutdown.
859 LIST_REMOVE(hook, hooks);
861 if (node->type->disconnect) {
863 * The type handler may elect to destroy the peer so don't
864 * trust its existance after this point.
866 (*node->type->disconnect) (hook);
868 ng_unref(node); /* might be the last reference */
870 FREE(hook->name, M_NETGRAPH);
871 hook->node = NULL; /* may still be referenced elsewhere */
876 * Take two hooks on a node and merge the connection so that the given node
877 * is effectively bypassed.
880 ng_bypass(hook_p hook1, hook_p hook2)
882 if (hook1->node != hook2->node)
884 hook1->peer->peer = hook2->peer;
885 hook2->peer->peer = hook1->peer;
887 /* XXX If we ever cache methods on hooks update them as well */
890 ng_destroy_hook(hook1);
891 ng_destroy_hook(hook2);
896 * Install a new netgraph type
899 ng_newtype(struct ng_type *tp)
901 const size_t namelen = strlen(tp->name);
903 /* Check version and type name fields */
904 if (tp->version != NG_VERSION || namelen == 0 || namelen >= NG_TYPESIZ) {
909 /* Check for name collision */
910 if (ng_findtype(tp->name) != NULL) {
915 /* Link in new type */
916 LIST_INSERT_HEAD(&typelist, tp, types);
917 tp->refs = 1; /* first ref is linked list */
922 * Look for a type of the name given
925 ng_findtype(const char *typename)
927 struct ng_type *type;
929 LIST_FOREACH(type, &typelist, types) {
930 if (strcmp(type->name, typename) == 0)
937 /************************************************************************
939 ************************************************************************/
942 * Make a peer and connect. The order is arranged to minimise
943 * the work needed to back out in case of error.
946 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
953 if ((error = ng_add_hook(node, name, &hook)))
956 /* make sure we have the module needed */
957 if (ng_findtype(type) == NULL) {
958 /* Not found, try to load it as a loadable module */
959 error = ng_load_module(type);
961 kprintf("required netgraph module ng_%s not loaded\n",
966 if ((error = ng_make_node(type, &node2))) {
967 ng_destroy_hook(hook);
970 if ((error = ng_add_hook(node2, name2, &hook2))) {
972 ng_destroy_hook(hook);
977 * Actually link the two hooks together.. on failure they are
978 * destroyed so we don't have to do that here.
980 if ((error = ng_connect(hook, hook2)))
986 * Connect two nodes using the specified hooks
989 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
995 if ((error = ng_add_hook(node, name, &hook)))
997 if ((error = ng_add_hook(node2, name2, &hook2))) {
998 ng_destroy_hook(hook);
1001 return (ng_connect(hook, hook2));
1005 * Parse and verify a string of the form: <NODE:><PATH>
1007 * Such a string can refer to a specific node or a specific hook
1008 * on a specific node, depending on how you look at it. In the
1009 * latter case, the PATH component must not end in a dot.
1011 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1012 * of hook names separated by dots. This breaks out the original
1013 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1014 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1015 * the final hook component of <PATH>, if any, otherwise NULL.
1017 * This returns -1 if the path is malformed. The char ** are optional.
1021 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1023 char *node, *path, *hook;
1027 * Extract absolute NODE, if any
1029 for (path = addr; *path && *path != ':'; path++);
1031 node = addr; /* Here's the NODE */
1032 *path++ = '\0'; /* Here's the PATH */
1034 /* Node name must not be empty */
1038 /* A name of "." is OK; otherwise '.' not allowed */
1039 if (strcmp(node, ".") != 0) {
1040 for (k = 0; node[k]; k++)
1045 node = NULL; /* No absolute NODE */
1046 path = addr; /* Here's the PATH */
1049 /* Snoop for illegal characters in PATH */
1050 for (k = 0; path[k]; k++)
1054 /* Check for no repeated dots in PATH */
1055 for (k = 0; path[k]; k++)
1056 if (path[k] == '.' && path[k + 1] == '.')
1059 /* Remove extra (degenerate) dots from beginning or end of PATH */
1062 if (*path && path[strlen(path) - 1] == '.')
1063 path[strlen(path) - 1] = 0;
1065 /* If PATH has a dot, then we're not talking about a hook */
1067 for (hook = path, k = 0; path[k]; k++)
1068 if (path[k] == '.') {
1086 * Given a path, which may be absolute or relative, and a starting node,
1087 * return the destination node. Compute the "return address" if desired.
1090 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1092 const node_p start = here;
1093 char fullpath[NG_PATHSIZ];
1094 char *nodename, *path, pbuf[2];
1105 /* Make a writable copy of address for ng_path_parse() */
1106 strncpy(fullpath, address, sizeof(fullpath) - 1);
1107 fullpath[sizeof(fullpath) - 1] = '\0';
1109 /* Parse out node and sequence of hooks */
1110 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1115 pbuf[0] = '.'; /* Needs to be writable */
1120 /* For an absolute address, jump to the starting node */
1122 node = ng_findname(here, nodename);
1130 /* Now follow the sequence of hooks */
1131 for (cp = path; node != NULL && *cp != '\0'; ) {
1136 * Break out the next path segment. Replace the dot we just
1137 * found with a NUL; "cp" points to the next segment (or the
1140 for (segment = cp; *cp != '\0'; cp++) {
1148 if (*segment == '\0')
1151 /* We have a segment, so look for a hook by that name */
1152 hook = ng_findhook(node, segment);
1154 /* Can't get there from here... */
1156 || hook->peer == NULL
1157 || (hook->flags & HK_INVALID) != 0) {
1162 /* Hop on over to the next node */
1163 node = hook->peer->node;
1166 /* If node somehow missing, fail here (probably this is not needed) */
1172 /* Now compute return address, i.e., the path to the sender */
1174 MALLOC(*rtnp, char *, NG_NODESIZ + 1, M_NETGRAPH, M_NOWAIT);
1175 if (*rtnp == NULL) {
1179 if (start->name != NULL)
1180 ksprintf(*rtnp, "%s:", start->name);
1182 ksprintf(*rtnp, "[%x]:", ng_node2ID(start));
1191 * Call the appropriate message handler for the object.
1192 * It is up to the message handler to free the message.
1193 * If it's a generic message, handle it generically, otherwise
1194 * call the type's message handler (if it exists)
1195 * XXX (race). Remember that a queued message may reference a node
1196 * or hook that has just been invalidated. It will exist
1197 * as the queue code is holding a reference, but..
1200 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1202 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1203 (error) = ng_generic_msg((node), (msg), \
1204 (retaddr), (resp)); \
1206 if ((node)->type->rcvmsg != NULL) { \
1207 (error) = (*(node)->type->rcvmsg)((node), \
1208 (msg), (retaddr), (resp)); \
1211 FREE((msg), M_NETGRAPH); \
1219 * Send a control message to a node
1222 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1223 struct ng_mesg **rptr)
1226 char *retaddr = NULL;
1229 /* Find the target node */
1230 error = ng_path2node(here, address, &dest, &retaddr);
1232 FREE(msg, M_NETGRAPH);
1236 /* Make sure the resp field is null before we start */
1240 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1242 /* Make sure that if there is a response, it has the RESP bit set */
1243 if ((error == 0) && rptr && *rptr)
1244 (*rptr)->header.flags |= NGF_RESP;
1247 * If we had a return address it is up to us to free it. They should
1248 * have taken a copy if they needed to make a delayed response.
1251 FREE(retaddr, M_NETGRAPH);
1256 * Implement the 'generic' control messages
1259 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1260 struct ng_mesg **resp)
1264 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1266 FREE(msg, M_NETGRAPH);
1269 switch (msg->header.cmd) {
1275 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1277 if (msg->header.arglen != sizeof(*mkp)) {
1281 mkp->type[sizeof(mkp->type) - 1] = '\0';
1282 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1283 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1284 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1289 struct ngm_connect *const con =
1290 (struct ngm_connect *) msg->data;
1293 if (msg->header.arglen != sizeof(*con)) {
1297 con->path[sizeof(con->path) - 1] = '\0';
1298 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1299 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1300 error = ng_path2node(here, con->path, &node2, NULL);
1303 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1308 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1310 if (msg->header.arglen != sizeof(*nam)) {
1314 nam->name[sizeof(nam->name) - 1] = '\0';
1315 error = ng_name_node(here, nam->name);
1320 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1323 if (msg->header.arglen != sizeof(*rmh)) {
1327 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1328 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1329 ng_destroy_hook(hook);
1334 struct nodeinfo *ni;
1337 /* Get response struct */
1342 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1348 /* Fill in node info */
1349 ni = (struct nodeinfo *) rp->data;
1350 if (here->name != NULL)
1351 strlcpy(ni->name, here->name, NG_NODESIZ);
1352 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1353 ni->id = ng_node2ID(here);
1354 ni->hooks = here->numhooks;
1360 const int nhooks = here->numhooks;
1361 struct hooklist *hl;
1362 struct nodeinfo *ni;
1366 /* Get response struct */
1371 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1372 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1377 hl = (struct hooklist *) rp->data;
1380 /* Fill in node info */
1382 strlcpy(ni->name, here->name, NG_NODESIZ);
1383 strlcpy(ni->type, here->type->name, NG_TYPESIZ);
1384 ni->id = ng_node2ID(here);
1386 /* Cycle through the linked list of hooks */
1388 LIST_FOREACH(hook, &here->hooks, hooks) {
1389 struct linkinfo *const link = &hl->link[ni->hooks];
1391 if (ni->hooks >= nhooks) {
1392 log(LOG_ERR, "%s: number of %s changed\n",
1396 if ((hook->flags & HK_INVALID) != 0)
1398 strlcpy(link->ourhook, hook->name, NG_HOOKSIZ);
1399 strlcpy(link->peerhook, hook->peer->name, NG_HOOKSIZ);
1400 if (hook->peer->node->name != NULL)
1401 strlcpy(link->nodeinfo.name,
1402 hook->peer->node->name, NG_NODESIZ);
1403 strlcpy(link->nodeinfo.type,
1404 hook->peer->node->type->name, NG_TYPESIZ);
1405 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1406 link->nodeinfo.hooks = hook->peer->node->numhooks;
1416 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1417 struct namelist *nl;
1427 /* Count number of nodes */
1428 LIST_FOREACH(node, &nodelist, nodes) {
1429 if ((node->flags & NG_INVALID) == 0
1430 && (unnamed || node->name != NULL))
1434 /* Get response struct */
1439 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1440 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1445 nl = (struct namelist *) rp->data;
1447 /* Cycle through the linked list of nodes */
1449 LIST_FOREACH(node, &nodelist, nodes) {
1450 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1452 if (nl->numnames >= num) {
1453 log(LOG_ERR, "%s: number of %s changed\n",
1457 if ((node->flags & NG_INVALID) != 0)
1459 if (!unnamed && node->name == NULL)
1461 if (node->name != NULL)
1462 strlcpy(np->name, node->name, NG_NODESIZ);
1463 strlcpy(np->type, node->type->name, NG_TYPESIZ);
1464 np->id = ng_node2ID(node);
1465 np->hooks = node->numhooks;
1474 struct typelist *tl;
1476 struct ng_type *type;
1484 /* Count number of types */
1485 LIST_FOREACH(type, &typelist, types)
1488 /* Get response struct */
1493 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1494 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1499 tl = (struct typelist *) rp->data;
1501 /* Cycle through the linked list of types */
1503 LIST_FOREACH(type, &typelist, types) {
1504 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1506 if (tl->numtypes >= num) {
1507 log(LOG_ERR, "%s: number of %s changed\n",
1511 strlcpy(tp->type_name, type->name, NG_TYPESIZ);
1512 tp->numnodes = type->refs - 1; /* don't count list */
1519 case NGM_BINARY2ASCII:
1521 int bufSize = 20 * 1024; /* XXX hard coded constant */
1522 const struct ng_parse_type *argstype;
1523 const struct ng_cmdlist *c;
1524 struct ng_mesg *rp, *binary, *ascii;
1526 /* Data area must contain a valid netgraph message */
1527 binary = (struct ng_mesg *)msg->data;
1528 if (msg->header.arglen < sizeof(struct ng_mesg)
1529 || msg->header.arglen - sizeof(struct ng_mesg)
1530 < binary->header.arglen) {
1535 /* Get a response message with lots of room */
1536 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1541 ascii = (struct ng_mesg *)rp->data;
1543 /* Copy binary message header to response message payload */
1544 bcopy(binary, ascii, sizeof(*binary));
1546 /* Find command by matching typecookie and command number */
1547 for (c = here->type->cmdlist;
1548 c != NULL && c->name != NULL; c++) {
1549 if (binary->header.typecookie == c->cookie
1550 && binary->header.cmd == c->cmd)
1553 if (c == NULL || c->name == NULL) {
1554 for (c = ng_generic_cmds; c->name != NULL; c++) {
1555 if (binary->header.typecookie == c->cookie
1556 && binary->header.cmd == c->cmd)
1559 if (c->name == NULL) {
1560 FREE(rp, M_NETGRAPH);
1566 /* Convert command name to ASCII */
1567 ksnprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1570 /* Convert command arguments to ASCII */
1571 argstype = (binary->header.flags & NGF_RESP) ?
1572 c->respType : c->mesgType;
1573 if (argstype == NULL)
1574 *ascii->data = '\0';
1576 if ((error = ng_unparse(argstype,
1577 (u_char *)binary->data,
1578 ascii->data, bufSize)) != 0) {
1579 FREE(rp, M_NETGRAPH);
1584 /* Return the result as struct ng_mesg plus ASCII string */
1585 bufSize = strlen(ascii->data) + 1;
1586 ascii->header.arglen = bufSize;
1587 rp->header.arglen = sizeof(*ascii) + bufSize;
1592 case NGM_ASCII2BINARY:
1594 int bufSize = 2000; /* XXX hard coded constant */
1595 const struct ng_cmdlist *c;
1596 const struct ng_parse_type *argstype;
1597 struct ng_mesg *rp, *ascii, *binary;
1600 /* Data area must contain at least a struct ng_mesg + '\0' */
1601 ascii = (struct ng_mesg *)msg->data;
1602 if (msg->header.arglen < sizeof(*ascii) + 1
1603 || ascii->header.arglen < 1
1604 || msg->header.arglen
1605 < sizeof(*ascii) + ascii->header.arglen) {
1609 ascii->data[ascii->header.arglen - 1] = '\0';
1611 /* Get a response message with lots of room */
1612 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1617 binary = (struct ng_mesg *)rp->data;
1619 /* Copy ASCII message header to response message payload */
1620 bcopy(ascii, binary, sizeof(*ascii));
1622 /* Find command by matching ASCII command string */
1623 for (c = here->type->cmdlist;
1624 c != NULL && c->name != NULL; c++) {
1625 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1628 if (c == NULL || c->name == NULL) {
1629 for (c = ng_generic_cmds; c->name != NULL; c++) {
1630 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1633 if (c->name == NULL) {
1634 FREE(rp, M_NETGRAPH);
1640 /* Convert command name to binary */
1641 binary->header.cmd = c->cmd;
1642 binary->header.typecookie = c->cookie;
1644 /* Convert command arguments to binary */
1645 argstype = (binary->header.flags & NGF_RESP) ?
1646 c->respType : c->mesgType;
1647 if (argstype == NULL)
1650 if ((error = ng_parse(argstype, ascii->data,
1651 &off, (u_char *)binary->data, &bufSize)) != 0) {
1652 FREE(rp, M_NETGRAPH);
1657 /* Return the result */
1658 binary->header.arglen = bufSize;
1659 rp->header.arglen = sizeof(*binary) + bufSize;
1664 case NGM_TEXT_CONFIG:
1665 case NGM_TEXT_STATUS:
1667 * This one is tricky as it passes the command down to the
1668 * actual node, even though it is a generic type command.
1669 * This means we must assume that the msg is already freed
1670 * when control passes back to us.
1676 if (here->type->rcvmsg != NULL)
1677 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1678 /* Fall through if rcvmsg not supported */
1683 FREE(msg, M_NETGRAPH);
1688 * Send a data packet to a node. If the recipient has no
1689 * 'receive data' method, then silently discard the packet.
1692 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1694 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1698 if (hook && (hook->flags & HK_INVALID) == 0) {
1699 rcvdata = hook->peer->node->type->rcvdata;
1700 if (rcvdata != NULL)
1701 error = (*rcvdata)(hook->peer, m, meta);
1704 NG_FREE_DATA(m, meta);
1709 NG_FREE_DATA(m, meta);
1715 * Send a queued data packet to a node. If the recipient has no
1716 * 'receive queued data' method, then try the 'receive data' method above.
1719 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1721 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1725 if (hook && (hook->flags & HK_INVALID) == 0) {
1726 rcvdataq = hook->peer->node->type->rcvdataq;
1727 if (rcvdataq != NULL)
1728 error = (*rcvdataq)(hook->peer, m, meta);
1730 error = ng_send_data(hook, m, meta);
1735 NG_FREE_DATA(m, meta);
1743 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1746 ng_copy_meta(meta_p meta)
1752 MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1755 meta2->allocated_len = meta->used_len;
1756 bcopy(meta, meta2, meta->used_len);
1760 /************************************************************************
1762 ************************************************************************/
1765 * Handle the loading/unloading of a netgraph node type module
1768 ng_mod_event(module_t mod, int event, void *data)
1770 struct ng_type *const type = data;
1776 /* Register new netgraph node type */
1778 if ((error = ng_newtype(type)) != 0) {
1783 /* Call type specific code */
1784 if (type->mod_event != NULL)
1785 if ((error = (*type->mod_event)(mod, event, data))) {
1786 type->refs--; /* undo it */
1787 LIST_REMOVE(type, types);
1794 if (type->refs > 1) { /* make sure no nodes exist! */
1797 if (type->refs == 0) {
1798 /* failed load, nothing to undo */
1802 if (type->mod_event != NULL) { /* check with type */
1803 error = (*type->mod_event)(mod, event, data);
1804 if (error != 0) { /* type refuses.. */
1809 LIST_REMOVE(type, types);
1815 if (type->mod_event != NULL)
1816 error = (*type->mod_event)(mod, event, data);
1818 error = 0; /* XXX ? */
1825 * Handle loading and unloading for this code.
1826 * The only thing we need to link into is the NETISR strucure.
1829 ngb_mod_event(module_t mod, int event, void *data)
1835 /* Register line discipline */
1837 error = ng_load_module("ksocket");
1842 netisr_register(NETISR_NETGRAPH, cpu0_portfn, ngintr);
1847 ng_unload_module("ksocket");
1848 /* You cant unload it because an interface may be using it. */
1858 static moduledata_t netgraph_mod = {
1863 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1864 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1865 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1866 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1868 /************************************************************************
1870 ************************************************************************/
1872 /* The structure for queueing across ISR switches */
1873 struct ng_queue_entry {
1875 struct ng_queue_entry *next;
1878 hook_p da_hook; /* target hook */
1883 struct ng_mesg *msg_msg;
1889 #define NGQF_DATA 0x01 /* the queue element is data */
1890 #define NGQF_MESG 0x02 /* the queue element is a message */
1892 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1893 static struct ng_queue_entry *ngqlast; /* last item queued */
1894 static const int ngqroom = 256; /* max items to queue */
1895 static int ngqsize; /* number of items in queue */
1897 static struct ng_queue_entry *ngqfree; /* free ones */
1898 static const int ngqfreemax = 256;/* cache at most this many */
1899 static int ngqfreesize; /* number of cached entries */
1904 static struct ng_queue_entry *
1907 struct ng_queue_entry *q;
1909 /* Could be guarding against tty ints or whatever */
1912 /* Try get a cached queue block, or else allocate a new one */
1913 if ((q = ngqfree) == NULL) {
1915 if (ngqsize < ngqroom) { /* don't worry about races */
1916 MALLOC(q, struct ng_queue_entry *,
1917 sizeof(*q), M_NETGRAPH, M_NOWAIT);
1928 * Release a queue entry
1930 #define RETURN_QBLK(q) \
1932 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1934 (q)->next = ngqfree; \
1939 FREE((q), M_NETGRAPH); \
1944 * Running at a raised (but we don't know which) processor priority level,
1945 * put the data onto a queue to be picked up by another PPL (probably splnet)
1948 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1950 struct ng_queue_entry *q;
1953 NG_FREE_DATA(m, meta);
1956 if ((q = ng_getqblk()) == NULL) {
1957 NG_FREE_DATA(m, meta);
1961 /* Fill out the contents */
1962 q->flags = NGQF_DATA;
1964 q->body.data.da_hook = hook;
1965 q->body.data.da_m = m;
1966 q->body.data.da_meta = meta;
1967 crit_enter(); /* protect refs and queue */
1968 hook->refs++; /* don't let it go away while on the queue */
1970 /* Put it on the queue */
1980 /* Schedule software interrupt to handle it later */
1981 schednetisr(NETISR_NETGRAPH);
1986 * Running at a raised (but we don't know which) processor priority level,
1987 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1990 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1992 struct ng_queue_entry *q;
1994 char *retaddr = NULL;
1997 /* Find the target node. */
1998 error = ng_path2node(here, address, &dest, &retaddr);
2000 FREE(msg, M_NETGRAPH);
2003 if ((q = ng_getqblk()) == NULL) {
2004 FREE(msg, M_NETGRAPH);
2006 FREE(retaddr, M_NETGRAPH);
2010 /* Fill out the contents */
2011 q->flags = NGQF_MESG;
2013 q->body.msg.msg_node = dest;
2014 q->body.msg.msg_msg = msg;
2015 q->body.msg.msg_retaddr = retaddr;
2016 crit_enter(); /* protect refs and queue */
2017 dest->refs++; /* don't let it go away while on the queue */
2019 /* Put it on the queue */
2029 /* Schedule software interrupt to handle it later */
2030 schednetisr(NETISR_NETGRAPH);
2035 * Pick an item off the queue, process it, and dispose of the queue entry.
2038 ngintr(struct netmsg *pmsg)
2042 struct ng_queue_entry *ngq;
2045 struct ng_mesg *msg;
2050 * Packets are never sent to this netisr so the message must always
2051 * be replied. Interlock processing and notification by replying
2052 * the message first.
2054 lwkt_replymsg(&pmsg->nm_lmsg, 0);
2058 if ((ngq = ngqbase)) {
2059 ngqbase = ngq->next;
2065 switch (ngq->flags) {
2067 hook = ngq->body.data.da_hook;
2068 m = ngq->body.data.da_m;
2069 meta = ngq->body.data.da_meta;
2071 NG_SEND_DATAQ(error, hook, m, meta);
2072 ng_unref_hook(hook);
2075 node = ngq->body.msg.msg_node;
2076 msg = ngq->body.msg.msg_msg;
2077 retaddr = ngq->body.msg.msg_retaddr;
2079 if (node->flags & NG_INVALID) {
2080 FREE(msg, M_NETGRAPH);
2082 CALL_MSG_HANDLER(error, node, msg,
2087 FREE(retaddr, M_NETGRAPH);