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.14 2005/02/17 13:59:59 joerg Exp $
42 * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
46 * This file implements the base netgraph code.
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/errno.h>
52 #include <sys/kernel.h>
53 #include <sys/malloc.h>
54 #include <sys/syslog.h>
55 #include <sys/linker.h>
56 #include <sys/queue.h>
58 #include <sys/ctype.h>
59 #include <sys/sysctl.h>
60 #include <machine/limits.h>
62 #include <sys/thread2.h>
63 #include <sys/msgport2.h>
65 #include <net/netisr.h>
67 #include <netgraph/ng_message.h>
68 #include <netgraph/netgraph.h>
69 #include <netgraph/ng_parse.h>
71 /* List of all nodes */
72 static LIST_HEAD(, ng_node) nodelist;
74 /* List of installed types */
75 static LIST_HEAD(, ng_type) typelist;
77 /* Hash releted definitions */
78 #define ID_HASH_SIZE 32 /* most systems wont need even this many */
79 static LIST_HEAD(, ng_node) ID_hash[ID_HASH_SIZE];
80 /* Don't nead to initialise them because it's a LIST */
82 /* Internal functions */
83 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
84 static int ng_connect(hook_p hook1, hook_p hook2);
85 static void ng_disconnect_hook(hook_p hook);
86 static int ng_generic_msg(node_p here, struct ng_mesg *msg,
87 const char *retaddr, struct ng_mesg ** resp);
88 static ng_ID_t ng_decodeidname(const char *name);
89 static int ngb_mod_event(module_t mod, int event, void *data);
90 static int ngintr(struct netmsg *);
92 /* Our own netgraph malloc type */
93 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
95 /* Set this to Debugger("X") to catch all errors as they occur */
100 static ng_ID_t nextID = 1;
103 #define CHECK_DATA_MBUF(m) do { \
107 if (((m)->m_flags & M_PKTHDR) == 0) \
108 panic("%s: !PKTHDR", __func__); \
109 for (total = 0, n = (m); n != NULL; n = n->m_next) \
111 if ((m)->m_pkthdr.len != total) { \
112 panic("%s: %d != %d", \
113 __func__, (m)->m_pkthdr.len, total); \
117 #define CHECK_DATA_MBUF(m)
121 /************************************************************************
122 Parse type definitions for generic messages
123 ************************************************************************/
125 /* Handy structure parse type defining macro */
126 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
127 static const struct ng_parse_struct_field \
128 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
129 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
130 &ng_parse_struct_type, \
131 &ng_ ## lo ## _type_fields \
134 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
135 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
136 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
137 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
138 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
139 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
140 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
142 /* Get length of an array when the length is stored as a 32 bit
143 value immediately preceeding the array -- as with struct namelist
144 and struct typelist. */
146 ng_generic_list_getLength(const struct ng_parse_type *type,
147 const u_char *start, const u_char *buf)
149 return *((const u_int32_t *)(buf - 4));
152 /* Get length of the array of struct linkinfo inside a struct hooklist */
154 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
155 const u_char *start, const u_char *buf)
157 const struct hooklist *hl = (const struct hooklist *)start;
159 return hl->nodeinfo.hooks;
162 /* Array type for a variable length array of struct namelist */
163 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
164 &ng_generic_nodeinfo_type,
165 &ng_generic_list_getLength
167 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
168 &ng_parse_array_type,
169 &ng_nodeinfoarray_type_info
172 /* Array type for a variable length array of struct typelist */
173 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
174 &ng_generic_typeinfo_type,
175 &ng_generic_list_getLength
177 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
178 &ng_parse_array_type,
179 &ng_typeinfoarray_type_info
182 /* Array type for array of struct linkinfo in struct hooklist */
183 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
184 &ng_generic_linkinfo_type,
185 &ng_generic_linkinfo_getLength
187 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
188 &ng_parse_array_type,
189 &ng_generic_linkinfo_array_type_info
192 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
193 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
194 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
195 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
196 (&ng_generic_nodeinfoarray_type));
198 /* List of commands and how to convert arguments to/from ASCII */
199 static const struct ng_cmdlist ng_generic_cmds[] = {
211 &ng_generic_mkpeer_type,
218 &ng_generic_connect_type,
225 &ng_generic_name_type,
232 &ng_generic_rmhook_type,
240 &ng_generic_nodeinfo_type
247 &ng_generic_hooklist_type
254 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
261 &ng_generic_listnodes_type
268 &ng_generic_typeinfo_type
275 &ng_parse_string_type
282 &ng_parse_string_type
288 &ng_parse_ng_mesg_type,
289 &ng_parse_ng_mesg_type
295 &ng_parse_ng_mesg_type,
296 &ng_parse_ng_mesg_type
301 /************************************************************************
303 ************************************************************************/
306 * Instantiate a node of the requested type
309 ng_make_node(const char *typename, node_p *nodepp)
311 struct ng_type *type;
313 /* Check that the type makes sense */
314 if (typename == NULL) {
319 /* Locate the node type */
320 if ((type = ng_findtype(typename)) == NULL) {
321 char *path, filename[NG_TYPELEN + 4];
325 /* Not found, try to load it as a loadable module */
326 snprintf(filename, sizeof(filename), "ng_%s.ko", typename);
327 if ((path = linker_search_path(filename)) == NULL)
329 error = linker_load_file(path, &lf);
330 FREE(path, M_LINKER);
333 lf->userrefs++; /* pretend loaded by the syscall */
335 /* Try again, as now the type should have linked itself in */
336 if ((type = ng_findtype(typename)) == NULL)
340 /* Call the constructor */
341 if (type->constructor != NULL)
342 return ((*type->constructor)(nodepp));
344 return (ng_make_node_common(type, nodepp));
348 * Generic node creation. Called by node constructors.
349 * The returned node has a reference count of 1.
352 ng_make_node_common(struct ng_type *type, node_p *nodepp)
356 /* Require the node type to have been already installed */
357 if (ng_findtype(type->name) == NULL) {
362 /* Make a node and try attach it to the type */
363 MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_NOWAIT);
368 bzero(node, sizeof(*node));
370 node->refs++; /* note reference */
373 /* Link us into the node linked list */
374 LIST_INSERT_HEAD(&nodelist, node, nodes);
376 /* Initialize hook list for new node */
377 LIST_INIT(&node->hooks);
379 /* get an ID and put us in the hash chain */
380 node->ID = nextID++; /* 137 per second for 1 year before wrap */
381 LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
389 * Forceably start the shutdown process on a node. Either call
390 * it's shutdown method, or do the default shutdown if there is
391 * no type-specific method.
393 * Persistent nodes must have a type-specific method which
394 * resets the NG_INVALID flag.
397 ng_rmnode(node_p node)
399 /* Check if it's already shutting down */
400 if ((node->flags & NG_INVALID) != 0)
403 /* Add an extra reference so it doesn't go away during this */
406 /* Mark it invalid so any newcomers know not to try use it */
407 node->flags |= NG_INVALID;
409 /* Ask the type if it has anything to do in this case */
410 if (node->type && node->type->shutdown)
411 (*node->type->shutdown)(node);
412 else { /* do the default thing */
418 /* Remove extra reference, possibly the last */
423 * Called by the destructor to remove any STANDARD external references
426 ng_cutlinks(node_p node)
430 /* Make sure that this is set to stop infinite loops */
431 node->flags |= NG_INVALID;
433 /* If we have sleepers, wake them up; they'll see NG_INVALID */
437 /* Notify all remaining connected nodes to disconnect */
438 while ((hook = LIST_FIRST(&node->hooks)) != NULL)
439 ng_destroy_hook(hook);
443 * Remove a reference to the node, possibly the last
446 ng_unref(node_p node)
451 if (--node->refs <= 0) {
453 LIST_REMOVE(node, nodes);
454 LIST_REMOVE(node, idnodes);
455 FREE(node, M_NETGRAPH);
461 * Wait for a node to come ready. Returns a node with a reference count;
462 * don't forget to drop it when we are done with it using ng_release_node().
465 ng_wait_node(node_p node, char *msg)
473 node->refs++; /* the sleeping process counts as a reference */
474 while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
475 error = tsleep(node, PCATCH, msg, 0);
477 if (node->flags & NG_INVALID) {
481 KASSERT(node->refs > 1,
482 ("%s: refs=%d", __func__, node->refs));
483 node->flags |= NG_BUSY;
487 /* Release the reference we had on it */
494 * Release a node acquired via ng_wait_node()
497 ng_release_node(node_p node)
499 /* Declare that we don't want it */
500 node->flags &= ~NG_BUSY;
502 /* If we have sleepers, then wake them up */
506 /* We also have a reference.. drop it too */
510 /************************************************************************
512 ************************************************************************/
514 ng_ID2node(ng_ID_t ID)
517 LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
518 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
525 ng_node2ID(node_p node)
530 /************************************************************************
532 ************************************************************************/
535 * Assign a node a name. Once assigned, the name cannot be changed.
538 ng_name_node(node_p node, const char *name)
542 /* Check the name is valid */
543 for (i = 0; i < NG_NODELEN + 1; i++) {
544 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
547 if (i == 0 || name[i] != '\0') {
551 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
556 /* Check the node isn't already named */
557 if (node->name != NULL) {
562 /* Check the name isn't already being used */
563 if (ng_findname(node, name) != NULL) {
568 /* Allocate space and copy it */
569 MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
570 if (node->name == NULL) {
574 strcpy(node->name, name);
576 /* The name counts as a reference */
582 * Find a node by absolute name. The name should NOT end with ':'
583 * The name "." means "this node" and "[xxx]" means "the node
584 * with ID (ie, at address) xxx".
586 * Returns the node if found, else NULL.
589 ng_findname(node_p this, const char *name)
594 /* "." means "this node" */
595 if (strcmp(name, ".") == 0)
598 /* Check for name-by-ID */
599 if ((temp = ng_decodeidname(name)) != 0) {
600 return (ng_ID2node(temp));
603 /* Find node by name */
604 LIST_FOREACH(node, &nodelist, nodes) {
605 if ((node->name != NULL)
606 && (strcmp(node->name, name) == 0)
607 && ((node->flags & NG_INVALID) == 0))
614 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
615 * string is not valid, otherwise returns the value.
618 ng_decodeidname(const char *name)
620 const int len = strlen(name);
624 /* Check for proper length, brackets, no leading junk */
625 if (len < 3 || name[0] != '[' || name[len - 1] != ']'
626 || !isxdigit(name[1]))
630 val = strtoul(name + 1, &eptr, 16);
631 if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
637 * Remove a name from a node. This should only be called
638 * when shutting down and removing the node.
641 ng_unname(node_p node)
644 FREE(node->name, M_NETGRAPH);
650 /************************************************************************
653 Names are not optional. Hooks are always connected, except for a
654 brief moment within these routines.
656 ************************************************************************/
659 * Remove a hook reference
662 ng_unref_hook(hook_p hook)
667 if (--hook->refs == 0)
668 FREE(hook, M_NETGRAPH);
673 * Add an unconnected hook to a node. Only used internally.
676 ng_add_hook(node_p node, const char *name, hook_p *hookp)
681 /* Check that the given name is good */
686 if (ng_findhook(node, name) != NULL) {
691 /* Allocate the hook and link it up */
692 MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_NOWAIT);
697 bzero(hook, sizeof(*hook));
699 hook->flags = HK_INVALID;
701 node->refs++; /* each hook counts as a reference */
703 /* Check if the node type code has something to say about it */
704 if (node->type->newhook != NULL)
705 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
709 * The 'type' agrees so far, so go ahead and link it in.
710 * We'll ask again later when we actually connect the hooks.
712 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
716 MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
717 if (hook->name == NULL) {
719 LIST_REMOVE(hook, hooks);
724 ng_unref_hook(hook); /* this frees the hook */
727 strcpy(hook->name, name);
734 * Connect a pair of hooks. Only used internally.
737 ng_connect(hook_p hook1, hook_p hook2)
744 /* Give each node the opportunity to veto the impending connection */
745 if (hook1->node->type->connect) {
746 if ((error = (*hook1->node->type->connect) (hook1))) {
747 ng_destroy_hook(hook1); /* also zaps hook2 */
751 if (hook2->node->type->connect) {
752 if ((error = (*hook2->node->type->connect) (hook2))) {
753 ng_destroy_hook(hook2); /* also zaps hook1 */
757 hook1->flags &= ~HK_INVALID;
758 hook2->flags &= ~HK_INVALID;
765 * Node types may supply their own optimized routines for finding
766 * hooks. If none is supplied, we just do a linear search.
769 ng_findhook(node_p node, const char *name)
773 if (node->type->findhook != NULL)
774 return (*node->type->findhook)(node, name);
775 LIST_FOREACH(hook, &node->hooks, hooks) {
776 if (hook->name != NULL
777 && strcmp(hook->name, name) == 0
778 && (hook->flags & HK_INVALID) == 0)
787 * As hooks are always attached, this really destroys two hooks.
788 * The one given, and the one attached to it. Disconnect the hooks
789 * from each other first.
792 ng_destroy_hook(hook_p hook)
794 hook_p peer = hook->peer;
796 hook->flags |= HK_INVALID; /* as soon as possible */
798 peer->flags |= HK_INVALID; /* as soon as possible */
801 ng_disconnect_hook(peer);
803 ng_disconnect_hook(hook);
807 * Notify the node of the hook's demise. This may result in more actions
808 * (e.g. shutdown) but we don't do that ourselves and don't know what
809 * happens there. If there is no appropriate handler, then just remove it
810 * (and decrement the reference count of it's node which in turn might
811 * make something happen).
814 ng_disconnect_hook(hook_p hook)
816 node_p node = hook->node;
819 * Remove the hook from the node's list to avoid possible recursion
820 * in case the disconnection results in node shutdown.
822 LIST_REMOVE(hook, hooks);
824 if (node->type->disconnect) {
826 * The type handler may elect to destroy the peer so don't
827 * trust its existance after this point.
829 (*node->type->disconnect) (hook);
831 ng_unref(node); /* might be the last reference */
833 FREE(hook->name, M_NETGRAPH);
834 hook->node = NULL; /* may still be referenced elsewhere */
839 * Take two hooks on a node and merge the connection so that the given node
840 * is effectively bypassed.
843 ng_bypass(hook_p hook1, hook_p hook2)
845 if (hook1->node != hook2->node)
847 hook1->peer->peer = hook2->peer;
848 hook2->peer->peer = hook1->peer;
850 /* XXX If we ever cache methods on hooks update them as well */
853 ng_destroy_hook(hook1);
854 ng_destroy_hook(hook2);
859 * Install a new netgraph type
862 ng_newtype(struct ng_type *tp)
864 const size_t namelen = strlen(tp->name);
866 /* Check version and type name fields */
867 if (tp->version != NG_VERSION || namelen == 0 || namelen > NG_TYPELEN) {
872 /* Check for name collision */
873 if (ng_findtype(tp->name) != NULL) {
878 /* Link in new type */
879 LIST_INSERT_HEAD(&typelist, tp, types);
880 tp->refs = 1; /* first ref is linked list */
885 * Look for a type of the name given
888 ng_findtype(const char *typename)
890 struct ng_type *type;
892 LIST_FOREACH(type, &typelist, types) {
893 if (strcmp(type->name, typename) == 0)
900 /************************************************************************
902 ************************************************************************/
905 * Make a peer and connect. The order is arranged to minimise
906 * the work needed to back out in case of error.
909 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
916 if ((error = ng_add_hook(node, name, &hook)))
918 if ((error = ng_make_node(type, &node2))) {
919 ng_destroy_hook(hook);
922 if ((error = ng_add_hook(node2, name2, &hook2))) {
924 ng_destroy_hook(hook);
929 * Actually link the two hooks together.. on failure they are
930 * destroyed so we don't have to do that here.
932 if ((error = ng_connect(hook, hook2)))
938 * Connect two nodes using the specified hooks
941 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
947 if ((error = ng_add_hook(node, name, &hook)))
949 if ((error = ng_add_hook(node2, name2, &hook2))) {
950 ng_destroy_hook(hook);
953 return (ng_connect(hook, hook2));
957 * Parse and verify a string of the form: <NODE:><PATH>
959 * Such a string can refer to a specific node or a specific hook
960 * on a specific node, depending on how you look at it. In the
961 * latter case, the PATH component must not end in a dot.
963 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
964 * of hook names separated by dots. This breaks out the original
965 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
966 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
967 * the final hook component of <PATH>, if any, otherwise NULL.
969 * This returns -1 if the path is malformed. The char ** are optional.
973 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
975 char *node, *path, *hook;
979 * Extract absolute NODE, if any
981 for (path = addr; *path && *path != ':'; path++);
983 node = addr; /* Here's the NODE */
984 *path++ = '\0'; /* Here's the PATH */
986 /* Node name must not be empty */
990 /* A name of "." is OK; otherwise '.' not allowed */
991 if (strcmp(node, ".") != 0) {
992 for (k = 0; node[k]; k++)
997 node = NULL; /* No absolute NODE */
998 path = addr; /* Here's the PATH */
1001 /* Snoop for illegal characters in PATH */
1002 for (k = 0; path[k]; k++)
1006 /* Check for no repeated dots in PATH */
1007 for (k = 0; path[k]; k++)
1008 if (path[k] == '.' && path[k + 1] == '.')
1011 /* Remove extra (degenerate) dots from beginning or end of PATH */
1014 if (*path && path[strlen(path) - 1] == '.')
1015 path[strlen(path) - 1] = 0;
1017 /* If PATH has a dot, then we're not talking about a hook */
1019 for (hook = path, k = 0; path[k]; k++)
1020 if (path[k] == '.') {
1038 * Given a path, which may be absolute or relative, and a starting node,
1039 * return the destination node. Compute the "return address" if desired.
1042 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1044 const node_p start = here;
1045 char fullpath[NG_PATHLEN + 1];
1046 char *nodename, *path, pbuf[2];
1057 /* Make a writable copy of address for ng_path_parse() */
1058 strncpy(fullpath, address, sizeof(fullpath) - 1);
1059 fullpath[sizeof(fullpath) - 1] = '\0';
1061 /* Parse out node and sequence of hooks */
1062 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1067 pbuf[0] = '.'; /* Needs to be writable */
1072 /* For an absolute address, jump to the starting node */
1074 node = ng_findname(here, nodename);
1082 /* Now follow the sequence of hooks */
1083 for (cp = path; node != NULL && *cp != '\0'; ) {
1088 * Break out the next path segment. Replace the dot we just
1089 * found with a NUL; "cp" points to the next segment (or the
1092 for (segment = cp; *cp != '\0'; cp++) {
1100 if (*segment == '\0')
1103 /* We have a segment, so look for a hook by that name */
1104 hook = ng_findhook(node, segment);
1106 /* Can't get there from here... */
1108 || hook->peer == NULL
1109 || (hook->flags & HK_INVALID) != 0) {
1114 /* Hop on over to the next node */
1115 node = hook->peer->node;
1118 /* If node somehow missing, fail here (probably this is not needed) */
1124 /* Now compute return address, i.e., the path to the sender */
1126 MALLOC(*rtnp, char *, NG_NODELEN + 2, M_NETGRAPH, M_NOWAIT);
1127 if (*rtnp == NULL) {
1131 if (start->name != NULL)
1132 sprintf(*rtnp, "%s:", start->name);
1134 sprintf(*rtnp, "[%x]:", ng_node2ID(start));
1143 * Call the appropriate message handler for the object.
1144 * It is up to the message handler to free the message.
1145 * If it's a generic message, handle it generically, otherwise
1146 * call the type's message handler (if it exists)
1147 * XXX (race). Remember that a queued message may reference a node
1148 * or hook that has just been invalidated. It will exist
1149 * as the queue code is holding a reference, but..
1152 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1154 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1155 (error) = ng_generic_msg((node), (msg), \
1156 (retaddr), (resp)); \
1158 if ((node)->type->rcvmsg != NULL) { \
1159 (error) = (*(node)->type->rcvmsg)((node), \
1160 (msg), (retaddr), (resp)); \
1163 FREE((msg), M_NETGRAPH); \
1171 * Send a control message to a node
1174 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1175 struct ng_mesg **rptr)
1178 char *retaddr = NULL;
1181 /* Find the target node */
1182 error = ng_path2node(here, address, &dest, &retaddr);
1184 FREE(msg, M_NETGRAPH);
1188 /* Make sure the resp field is null before we start */
1192 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1194 /* Make sure that if there is a response, it has the RESP bit set */
1195 if ((error == 0) && rptr && *rptr)
1196 (*rptr)->header.flags |= NGF_RESP;
1199 * If we had a return address it is up to us to free it. They should
1200 * have taken a copy if they needed to make a delayed response.
1203 FREE(retaddr, M_NETGRAPH);
1208 * Implement the 'generic' control messages
1211 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1212 struct ng_mesg **resp)
1216 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1218 FREE(msg, M_NETGRAPH);
1221 switch (msg->header.cmd) {
1227 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1229 if (msg->header.arglen != sizeof(*mkp)) {
1233 mkp->type[sizeof(mkp->type) - 1] = '\0';
1234 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1235 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1236 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1241 struct ngm_connect *const con =
1242 (struct ngm_connect *) msg->data;
1245 if (msg->header.arglen != sizeof(*con)) {
1249 con->path[sizeof(con->path) - 1] = '\0';
1250 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1251 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1252 error = ng_path2node(here, con->path, &node2, NULL);
1255 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1260 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1262 if (msg->header.arglen != sizeof(*nam)) {
1266 nam->name[sizeof(nam->name) - 1] = '\0';
1267 error = ng_name_node(here, nam->name);
1272 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1275 if (msg->header.arglen != sizeof(*rmh)) {
1279 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1280 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1281 ng_destroy_hook(hook);
1286 struct nodeinfo *ni;
1289 /* Get response struct */
1294 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1300 /* Fill in node info */
1301 ni = (struct nodeinfo *) rp->data;
1302 if (here->name != NULL)
1303 strncpy(ni->name, here->name, NG_NODELEN);
1304 strncpy(ni->type, here->type->name, NG_TYPELEN);
1305 ni->id = ng_node2ID(here);
1306 ni->hooks = here->numhooks;
1312 const int nhooks = here->numhooks;
1313 struct hooklist *hl;
1314 struct nodeinfo *ni;
1318 /* Get response struct */
1323 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1324 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1329 hl = (struct hooklist *) rp->data;
1332 /* Fill in node info */
1334 strncpy(ni->name, here->name, NG_NODELEN);
1335 strncpy(ni->type, here->type->name, NG_TYPELEN);
1336 ni->id = ng_node2ID(here);
1338 /* Cycle through the linked list of hooks */
1340 LIST_FOREACH(hook, &here->hooks, hooks) {
1341 struct linkinfo *const link = &hl->link[ni->hooks];
1343 if (ni->hooks >= nhooks) {
1344 log(LOG_ERR, "%s: number of %s changed\n",
1348 if ((hook->flags & HK_INVALID) != 0)
1350 strncpy(link->ourhook, hook->name, NG_HOOKLEN);
1351 strncpy(link->peerhook, hook->peer->name, NG_HOOKLEN);
1352 if (hook->peer->node->name != NULL)
1353 strncpy(link->nodeinfo.name,
1354 hook->peer->node->name, NG_NODELEN);
1355 strncpy(link->nodeinfo.type,
1356 hook->peer->node->type->name, NG_TYPELEN);
1357 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1358 link->nodeinfo.hooks = hook->peer->node->numhooks;
1368 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1369 struct namelist *nl;
1379 /* Count number of nodes */
1380 LIST_FOREACH(node, &nodelist, nodes) {
1381 if ((node->flags & NG_INVALID) == 0
1382 && (unnamed || node->name != NULL))
1386 /* Get response struct */
1391 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1392 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1397 nl = (struct namelist *) rp->data;
1399 /* Cycle through the linked list of nodes */
1401 LIST_FOREACH(node, &nodelist, nodes) {
1402 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1404 if (nl->numnames >= num) {
1405 log(LOG_ERR, "%s: number of %s changed\n",
1409 if ((node->flags & NG_INVALID) != 0)
1411 if (!unnamed && node->name == NULL)
1413 if (node->name != NULL)
1414 strncpy(np->name, node->name, NG_NODELEN);
1415 strncpy(np->type, node->type->name, NG_TYPELEN);
1416 np->id = ng_node2ID(node);
1417 np->hooks = node->numhooks;
1426 struct typelist *tl;
1428 struct ng_type *type;
1436 /* Count number of types */
1437 LIST_FOREACH(type, &typelist, types)
1440 /* Get response struct */
1445 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1446 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1451 tl = (struct typelist *) rp->data;
1453 /* Cycle through the linked list of types */
1455 LIST_FOREACH(type, &typelist, types) {
1456 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1458 if (tl->numtypes >= num) {
1459 log(LOG_ERR, "%s: number of %s changed\n",
1463 strncpy(tp->type_name, type->name, NG_TYPELEN);
1464 tp->numnodes = type->refs - 1; /* don't count list */
1471 case NGM_BINARY2ASCII:
1473 int bufSize = 20 * 1024; /* XXX hard coded constant */
1474 const struct ng_parse_type *argstype;
1475 const struct ng_cmdlist *c;
1476 struct ng_mesg *rp, *binary, *ascii;
1478 /* Data area must contain a valid netgraph message */
1479 binary = (struct ng_mesg *)msg->data;
1480 if (msg->header.arglen < sizeof(struct ng_mesg)
1481 || msg->header.arglen - sizeof(struct ng_mesg)
1482 < binary->header.arglen) {
1487 /* Get a response message with lots of room */
1488 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1493 ascii = (struct ng_mesg *)rp->data;
1495 /* Copy binary message header to response message payload */
1496 bcopy(binary, ascii, sizeof(*binary));
1498 /* Find command by matching typecookie and command number */
1499 for (c = here->type->cmdlist;
1500 c != NULL && c->name != NULL; c++) {
1501 if (binary->header.typecookie == c->cookie
1502 && binary->header.cmd == c->cmd)
1505 if (c == NULL || c->name == NULL) {
1506 for (c = ng_generic_cmds; c->name != NULL; c++) {
1507 if (binary->header.typecookie == c->cookie
1508 && binary->header.cmd == c->cmd)
1511 if (c->name == NULL) {
1512 FREE(rp, M_NETGRAPH);
1518 /* Convert command name to ASCII */
1519 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1522 /* Convert command arguments to ASCII */
1523 argstype = (binary->header.flags & NGF_RESP) ?
1524 c->respType : c->mesgType;
1525 if (argstype == NULL)
1526 *ascii->data = '\0';
1528 if ((error = ng_unparse(argstype,
1529 (u_char *)binary->data,
1530 ascii->data, bufSize)) != 0) {
1531 FREE(rp, M_NETGRAPH);
1536 /* Return the result as struct ng_mesg plus ASCII string */
1537 bufSize = strlen(ascii->data) + 1;
1538 ascii->header.arglen = bufSize;
1539 rp->header.arglen = sizeof(*ascii) + bufSize;
1544 case NGM_ASCII2BINARY:
1546 int bufSize = 2000; /* XXX hard coded constant */
1547 const struct ng_cmdlist *c;
1548 const struct ng_parse_type *argstype;
1549 struct ng_mesg *rp, *ascii, *binary;
1552 /* Data area must contain at least a struct ng_mesg + '\0' */
1553 ascii = (struct ng_mesg *)msg->data;
1554 if (msg->header.arglen < sizeof(*ascii) + 1
1555 || ascii->header.arglen < 1
1556 || msg->header.arglen
1557 < sizeof(*ascii) + ascii->header.arglen) {
1561 ascii->data[ascii->header.arglen - 1] = '\0';
1563 /* Get a response message with lots of room */
1564 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1569 binary = (struct ng_mesg *)rp->data;
1571 /* Copy ASCII message header to response message payload */
1572 bcopy(ascii, binary, sizeof(*ascii));
1574 /* Find command by matching ASCII command string */
1575 for (c = here->type->cmdlist;
1576 c != NULL && c->name != NULL; c++) {
1577 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1580 if (c == NULL || c->name == NULL) {
1581 for (c = ng_generic_cmds; c->name != NULL; c++) {
1582 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1585 if (c->name == NULL) {
1586 FREE(rp, M_NETGRAPH);
1592 /* Convert command name to binary */
1593 binary->header.cmd = c->cmd;
1594 binary->header.typecookie = c->cookie;
1596 /* Convert command arguments to binary */
1597 argstype = (binary->header.flags & NGF_RESP) ?
1598 c->respType : c->mesgType;
1599 if (argstype == NULL)
1602 if ((error = ng_parse(argstype, ascii->data,
1603 &off, (u_char *)binary->data, &bufSize)) != 0) {
1604 FREE(rp, M_NETGRAPH);
1609 /* Return the result */
1610 binary->header.arglen = bufSize;
1611 rp->header.arglen = sizeof(*binary) + bufSize;
1616 case NGM_TEXT_CONFIG:
1617 case NGM_TEXT_STATUS:
1619 * This one is tricky as it passes the command down to the
1620 * actual node, even though it is a generic type command.
1621 * This means we must assume that the msg is already freed
1622 * when control passes back to us.
1628 if (here->type->rcvmsg != NULL)
1629 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1630 /* Fall through if rcvmsg not supported */
1635 FREE(msg, M_NETGRAPH);
1640 * Send a data packet to a node. If the recipient has no
1641 * 'receive data' method, then silently discard the packet.
1644 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1646 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1650 if (hook && (hook->flags & HK_INVALID) == 0) {
1651 rcvdata = hook->peer->node->type->rcvdata;
1652 if (rcvdata != NULL)
1653 error = (*rcvdata)(hook->peer, m, meta);
1656 NG_FREE_DATA(m, meta);
1661 NG_FREE_DATA(m, meta);
1667 * Send a queued data packet to a node. If the recipient has no
1668 * 'receive queued data' method, then try the 'receive data' method above.
1671 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1673 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1677 if (hook && (hook->flags & HK_INVALID) == 0) {
1678 rcvdataq = hook->peer->node->type->rcvdataq;
1679 if (rcvdataq != NULL)
1680 error = (*rcvdataq)(hook->peer, m, meta);
1682 error = ng_send_data(hook, m, meta);
1687 NG_FREE_DATA(m, meta);
1695 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1698 ng_copy_meta(meta_p meta)
1704 MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1707 meta2->allocated_len = meta->used_len;
1708 bcopy(meta, meta2, meta->used_len);
1712 /************************************************************************
1714 ************************************************************************/
1717 * Handle the loading/unloading of a netgraph node type module
1720 ng_mod_event(module_t mod, int event, void *data)
1722 struct ng_type *const type = data;
1728 /* Register new netgraph node type */
1730 if ((error = ng_newtype(type)) != 0) {
1735 /* Call type specific code */
1736 if (type->mod_event != NULL)
1737 if ((error = (*type->mod_event)(mod, event, data))) {
1738 type->refs--; /* undo it */
1739 LIST_REMOVE(type, types);
1746 if (type->refs > 1) { /* make sure no nodes exist! */
1749 if (type->refs == 0) {
1750 /* failed load, nothing to undo */
1754 if (type->mod_event != NULL) { /* check with type */
1755 error = (*type->mod_event)(mod, event, data);
1756 if (error != 0) { /* type refuses.. */
1761 LIST_REMOVE(type, types);
1767 if (type->mod_event != NULL)
1768 error = (*type->mod_event)(mod, event, data);
1770 error = 0; /* XXX ? */
1777 * Handle loading and unloading for this code.
1778 * The only thing we need to link into is the NETISR strucure.
1781 ngb_mod_event(module_t mod, int event, void *data)
1787 /* Register line discipline */
1789 netisr_register(NETISR_NETGRAPH, cpu0_portfn, ngintr);
1794 /* You cant unload it because an interface may be using it. */
1804 static moduledata_t netgraph_mod = {
1809 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1810 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1811 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1812 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1814 /************************************************************************
1816 ************************************************************************/
1818 /* The structure for queueing across ISR switches */
1819 struct ng_queue_entry {
1821 struct ng_queue_entry *next;
1824 hook_p da_hook; /* target hook */
1829 struct ng_mesg *msg_msg;
1835 #define NGQF_DATA 0x01 /* the queue element is data */
1836 #define NGQF_MESG 0x02 /* the queue element is a message */
1838 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1839 static struct ng_queue_entry *ngqlast; /* last item queued */
1840 static const int ngqroom = 256; /* max items to queue */
1841 static int ngqsize; /* number of items in queue */
1843 static struct ng_queue_entry *ngqfree; /* free ones */
1844 static const int ngqfreemax = 256;/* cache at most this many */
1845 static int ngqfreesize; /* number of cached entries */
1850 static struct ng_queue_entry *
1853 struct ng_queue_entry *q;
1856 /* Could be guarding against tty ints or whatever */
1859 /* Try get a cached queue block, or else allocate a new one */
1860 if ((q = ngqfree) == NULL) {
1862 if (ngqsize < ngqroom) { /* don't worry about races */
1863 MALLOC(q, struct ng_queue_entry *,
1864 sizeof(*q), M_NETGRAPH, M_NOWAIT);
1875 * Release a queue entry
1877 #define RETURN_QBLK(q) \
1880 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1882 (q)->next = ngqfree; \
1887 FREE((q), M_NETGRAPH); \
1892 * Running at a raised (but we don't know which) processor priority level,
1893 * put the data onto a queue to be picked up by another PPL (probably splnet)
1896 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1898 struct ng_queue_entry *q;
1902 NG_FREE_DATA(m, meta);
1905 if ((q = ng_getqblk()) == NULL) {
1906 NG_FREE_DATA(m, meta);
1910 /* Fill out the contents */
1911 q->flags = NGQF_DATA;
1913 q->body.data.da_hook = hook;
1914 q->body.data.da_m = m;
1915 q->body.data.da_meta = meta;
1916 s = splhigh(); /* protect refs and queue */
1917 hook->refs++; /* don't let it go away while on the queue */
1919 /* Put it on the queue */
1929 /* Schedule software interrupt to handle it later */
1930 schednetisr(NETISR_NETGRAPH);
1935 * Running at a raised (but we don't know which) processor priority level,
1936 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1939 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1941 struct ng_queue_entry *q;
1944 char *retaddr = NULL;
1947 /* Find the target node. */
1948 error = ng_path2node(here, address, &dest, &retaddr);
1950 FREE(msg, M_NETGRAPH);
1953 if ((q = ng_getqblk()) == NULL) {
1954 FREE(msg, M_NETGRAPH);
1956 FREE(retaddr, M_NETGRAPH);
1960 /* Fill out the contents */
1961 q->flags = NGQF_MESG;
1963 q->body.msg.msg_node = dest;
1964 q->body.msg.msg_msg = msg;
1965 q->body.msg.msg_retaddr = retaddr;
1966 s = splhigh(); /* protect refs and queue */
1967 dest->refs++; /* don't let it go away while on the queue */
1969 /* Put it on the queue */
1979 /* Schedule software interrupt to handle it later */
1980 schednetisr(NETISR_NETGRAPH);
1985 * Pick an item off the queue, process it, and dispose of the queue entry.
1986 * Should be running at splnet.
1989 ngintr(struct netmsg *pmsg)
1991 struct mbuf *m = ((struct netmsg_packet *)pmsg)->nm_packet;
1993 struct ng_queue_entry *ngq;
1996 struct ng_mesg *msg;
2003 if ((ngq = ngqbase)) {
2004 ngqbase = ngq->next;
2010 switch (ngq->flags) {
2012 hook = ngq->body.data.da_hook;
2013 m = ngq->body.data.da_m;
2014 meta = ngq->body.data.da_meta;
2016 NG_SEND_DATAQ(error, hook, m, meta);
2017 ng_unref_hook(hook);
2020 node = ngq->body.msg.msg_node;
2021 msg = ngq->body.msg.msg_msg;
2022 retaddr = ngq->body.msg.msg_retaddr;
2024 if (node->flags & NG_INVALID) {
2025 FREE(msg, M_NETGRAPH);
2027 CALL_MSG_HANDLER(error, node, msg,
2032 FREE(retaddr, M_NETGRAPH);
2039 lwkt_replymsg(&pmsg->nm_lmsg, 0);