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.15 2005/06/02 22:11:46 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 <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)
449 if (--node->refs <= 0) {
451 LIST_REMOVE(node, nodes);
452 LIST_REMOVE(node, idnodes);
453 FREE(node, M_NETGRAPH);
459 * Wait for a node to come ready. Returns a node with a reference count;
460 * don't forget to drop it when we are done with it using ng_release_node().
463 ng_wait_node(node_p node, char *msg)
471 node->refs++; /* the sleeping process counts as a reference */
472 while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
473 error = tsleep(node, PCATCH, msg, 0);
475 if (node->flags & NG_INVALID) {
479 KASSERT(node->refs > 1,
480 ("%s: refs=%d", __func__, node->refs));
481 node->flags |= NG_BUSY;
485 /* Release the reference we had on it */
492 * Release a node acquired via ng_wait_node()
495 ng_release_node(node_p node)
497 /* Declare that we don't want it */
498 node->flags &= ~NG_BUSY;
500 /* If we have sleepers, then wake them up */
504 /* We also have a reference.. drop it too */
508 /************************************************************************
510 ************************************************************************/
512 ng_ID2node(ng_ID_t ID)
515 LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
516 if ((np->flags & NG_INVALID) == 0 && np->ID == ID)
523 ng_node2ID(node_p node)
528 /************************************************************************
530 ************************************************************************/
533 * Assign a node a name. Once assigned, the name cannot be changed.
536 ng_name_node(node_p node, const char *name)
540 /* Check the name is valid */
541 for (i = 0; i < NG_NODELEN + 1; i++) {
542 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
545 if (i == 0 || name[i] != '\0') {
549 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
554 /* Check the node isn't already named */
555 if (node->name != NULL) {
560 /* Check the name isn't already being used */
561 if (ng_findname(node, name) != NULL) {
566 /* Allocate space and copy it */
567 MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
568 if (node->name == NULL) {
572 strcpy(node->name, name);
574 /* The name counts as a reference */
580 * Find a node by absolute name. The name should NOT end with ':'
581 * The name "." means "this node" and "[xxx]" means "the node
582 * with ID (ie, at address) xxx".
584 * Returns the node if found, else NULL.
587 ng_findname(node_p this, const char *name)
592 /* "." means "this node" */
593 if (strcmp(name, ".") == 0)
596 /* Check for name-by-ID */
597 if ((temp = ng_decodeidname(name)) != 0) {
598 return (ng_ID2node(temp));
601 /* Find node by name */
602 LIST_FOREACH(node, &nodelist, nodes) {
603 if ((node->name != NULL)
604 && (strcmp(node->name, name) == 0)
605 && ((node->flags & NG_INVALID) == 0))
612 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
613 * string is not valid, otherwise returns the value.
616 ng_decodeidname(const char *name)
618 const int len = strlen(name);
622 /* Check for proper length, brackets, no leading junk */
623 if (len < 3 || name[0] != '[' || name[len - 1] != ']'
624 || !isxdigit(name[1]))
628 val = strtoul(name + 1, &eptr, 16);
629 if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
635 * Remove a name from a node. This should only be called
636 * when shutting down and removing the node.
639 ng_unname(node_p node)
642 FREE(node->name, M_NETGRAPH);
648 /************************************************************************
651 Names are not optional. Hooks are always connected, except for a
652 brief moment within these routines.
654 ************************************************************************/
657 * Remove a hook reference
660 ng_unref_hook(hook_p hook)
663 if (--hook->refs == 0)
664 FREE(hook, M_NETGRAPH);
669 * Add an unconnected hook to a node. Only used internally.
672 ng_add_hook(node_p node, const char *name, hook_p *hookp)
677 /* Check that the given name is good */
682 if (ng_findhook(node, name) != NULL) {
687 /* Allocate the hook and link it up */
688 MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_NOWAIT);
693 bzero(hook, sizeof(*hook));
695 hook->flags = HK_INVALID;
697 node->refs++; /* each hook counts as a reference */
699 /* Check if the node type code has something to say about it */
700 if (node->type->newhook != NULL)
701 if ((error = (*node->type->newhook)(node, hook, name)) != 0)
705 * The 'type' agrees so far, so go ahead and link it in.
706 * We'll ask again later when we actually connect the hooks.
708 LIST_INSERT_HEAD(&node->hooks, hook, hooks);
712 MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_NOWAIT);
713 if (hook->name == NULL) {
715 LIST_REMOVE(hook, hooks);
720 ng_unref_hook(hook); /* this frees the hook */
723 strcpy(hook->name, name);
730 * Connect a pair of hooks. Only used internally.
733 ng_connect(hook_p hook1, hook_p hook2)
740 /* Give each node the opportunity to veto the impending connection */
741 if (hook1->node->type->connect) {
742 if ((error = (*hook1->node->type->connect) (hook1))) {
743 ng_destroy_hook(hook1); /* also zaps hook2 */
747 if (hook2->node->type->connect) {
748 if ((error = (*hook2->node->type->connect) (hook2))) {
749 ng_destroy_hook(hook2); /* also zaps hook1 */
753 hook1->flags &= ~HK_INVALID;
754 hook2->flags &= ~HK_INVALID;
761 * Node types may supply their own optimized routines for finding
762 * hooks. If none is supplied, we just do a linear search.
765 ng_findhook(node_p node, const char *name)
769 if (node->type->findhook != NULL)
770 return (*node->type->findhook)(node, name);
771 LIST_FOREACH(hook, &node->hooks, hooks) {
772 if (hook->name != NULL
773 && strcmp(hook->name, name) == 0
774 && (hook->flags & HK_INVALID) == 0)
783 * As hooks are always attached, this really destroys two hooks.
784 * The one given, and the one attached to it. Disconnect the hooks
785 * from each other first.
788 ng_destroy_hook(hook_p hook)
790 hook_p peer = hook->peer;
792 hook->flags |= HK_INVALID; /* as soon as possible */
794 peer->flags |= HK_INVALID; /* as soon as possible */
797 ng_disconnect_hook(peer);
799 ng_disconnect_hook(hook);
803 * Notify the node of the hook's demise. This may result in more actions
804 * (e.g. shutdown) but we don't do that ourselves and don't know what
805 * happens there. If there is no appropriate handler, then just remove it
806 * (and decrement the reference count of it's node which in turn might
807 * make something happen).
810 ng_disconnect_hook(hook_p hook)
812 node_p node = hook->node;
815 * Remove the hook from the node's list to avoid possible recursion
816 * in case the disconnection results in node shutdown.
818 LIST_REMOVE(hook, hooks);
820 if (node->type->disconnect) {
822 * The type handler may elect to destroy the peer so don't
823 * trust its existance after this point.
825 (*node->type->disconnect) (hook);
827 ng_unref(node); /* might be the last reference */
829 FREE(hook->name, M_NETGRAPH);
830 hook->node = NULL; /* may still be referenced elsewhere */
835 * Take two hooks on a node and merge the connection so that the given node
836 * is effectively bypassed.
839 ng_bypass(hook_p hook1, hook_p hook2)
841 if (hook1->node != hook2->node)
843 hook1->peer->peer = hook2->peer;
844 hook2->peer->peer = hook1->peer;
846 /* XXX If we ever cache methods on hooks update them as well */
849 ng_destroy_hook(hook1);
850 ng_destroy_hook(hook2);
855 * Install a new netgraph type
858 ng_newtype(struct ng_type *tp)
860 const size_t namelen = strlen(tp->name);
862 /* Check version and type name fields */
863 if (tp->version != NG_VERSION || namelen == 0 || namelen > NG_TYPELEN) {
868 /* Check for name collision */
869 if (ng_findtype(tp->name) != NULL) {
874 /* Link in new type */
875 LIST_INSERT_HEAD(&typelist, tp, types);
876 tp->refs = 1; /* first ref is linked list */
881 * Look for a type of the name given
884 ng_findtype(const char *typename)
886 struct ng_type *type;
888 LIST_FOREACH(type, &typelist, types) {
889 if (strcmp(type->name, typename) == 0)
896 /************************************************************************
898 ************************************************************************/
901 * Make a peer and connect. The order is arranged to minimise
902 * the work needed to back out in case of error.
905 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
912 if ((error = ng_add_hook(node, name, &hook)))
914 if ((error = ng_make_node(type, &node2))) {
915 ng_destroy_hook(hook);
918 if ((error = ng_add_hook(node2, name2, &hook2))) {
920 ng_destroy_hook(hook);
925 * Actually link the two hooks together.. on failure they are
926 * destroyed so we don't have to do that here.
928 if ((error = ng_connect(hook, hook2)))
934 * Connect two nodes using the specified hooks
937 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
943 if ((error = ng_add_hook(node, name, &hook)))
945 if ((error = ng_add_hook(node2, name2, &hook2))) {
946 ng_destroy_hook(hook);
949 return (ng_connect(hook, hook2));
953 * Parse and verify a string of the form: <NODE:><PATH>
955 * Such a string can refer to a specific node or a specific hook
956 * on a specific node, depending on how you look at it. In the
957 * latter case, the PATH component must not end in a dot.
959 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
960 * of hook names separated by dots. This breaks out the original
961 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
962 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
963 * the final hook component of <PATH>, if any, otherwise NULL.
965 * This returns -1 if the path is malformed. The char ** are optional.
969 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
971 char *node, *path, *hook;
975 * Extract absolute NODE, if any
977 for (path = addr; *path && *path != ':'; path++);
979 node = addr; /* Here's the NODE */
980 *path++ = '\0'; /* Here's the PATH */
982 /* Node name must not be empty */
986 /* A name of "." is OK; otherwise '.' not allowed */
987 if (strcmp(node, ".") != 0) {
988 for (k = 0; node[k]; k++)
993 node = NULL; /* No absolute NODE */
994 path = addr; /* Here's the PATH */
997 /* Snoop for illegal characters in PATH */
998 for (k = 0; path[k]; k++)
1002 /* Check for no repeated dots in PATH */
1003 for (k = 0; path[k]; k++)
1004 if (path[k] == '.' && path[k + 1] == '.')
1007 /* Remove extra (degenerate) dots from beginning or end of PATH */
1010 if (*path && path[strlen(path) - 1] == '.')
1011 path[strlen(path) - 1] = 0;
1013 /* If PATH has a dot, then we're not talking about a hook */
1015 for (hook = path, k = 0; path[k]; k++)
1016 if (path[k] == '.') {
1034 * Given a path, which may be absolute or relative, and a starting node,
1035 * return the destination node. Compute the "return address" if desired.
1038 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
1040 const node_p start = here;
1041 char fullpath[NG_PATHLEN + 1];
1042 char *nodename, *path, pbuf[2];
1053 /* Make a writable copy of address for ng_path_parse() */
1054 strncpy(fullpath, address, sizeof(fullpath) - 1);
1055 fullpath[sizeof(fullpath) - 1] = '\0';
1057 /* Parse out node and sequence of hooks */
1058 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1063 pbuf[0] = '.'; /* Needs to be writable */
1068 /* For an absolute address, jump to the starting node */
1070 node = ng_findname(here, nodename);
1078 /* Now follow the sequence of hooks */
1079 for (cp = path; node != NULL && *cp != '\0'; ) {
1084 * Break out the next path segment. Replace the dot we just
1085 * found with a NUL; "cp" points to the next segment (or the
1088 for (segment = cp; *cp != '\0'; cp++) {
1096 if (*segment == '\0')
1099 /* We have a segment, so look for a hook by that name */
1100 hook = ng_findhook(node, segment);
1102 /* Can't get there from here... */
1104 || hook->peer == NULL
1105 || (hook->flags & HK_INVALID) != 0) {
1110 /* Hop on over to the next node */
1111 node = hook->peer->node;
1114 /* If node somehow missing, fail here (probably this is not needed) */
1120 /* Now compute return address, i.e., the path to the sender */
1122 MALLOC(*rtnp, char *, NG_NODELEN + 2, M_NETGRAPH, M_NOWAIT);
1123 if (*rtnp == NULL) {
1127 if (start->name != NULL)
1128 sprintf(*rtnp, "%s:", start->name);
1130 sprintf(*rtnp, "[%x]:", ng_node2ID(start));
1139 * Call the appropriate message handler for the object.
1140 * It is up to the message handler to free the message.
1141 * If it's a generic message, handle it generically, otherwise
1142 * call the type's message handler (if it exists)
1143 * XXX (race). Remember that a queued message may reference a node
1144 * or hook that has just been invalidated. It will exist
1145 * as the queue code is holding a reference, but..
1148 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp) \
1150 if((msg)->header.typecookie == NGM_GENERIC_COOKIE) { \
1151 (error) = ng_generic_msg((node), (msg), \
1152 (retaddr), (resp)); \
1154 if ((node)->type->rcvmsg != NULL) { \
1155 (error) = (*(node)->type->rcvmsg)((node), \
1156 (msg), (retaddr), (resp)); \
1159 FREE((msg), M_NETGRAPH); \
1167 * Send a control message to a node
1170 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
1171 struct ng_mesg **rptr)
1174 char *retaddr = NULL;
1177 /* Find the target node */
1178 error = ng_path2node(here, address, &dest, &retaddr);
1180 FREE(msg, M_NETGRAPH);
1184 /* Make sure the resp field is null before we start */
1188 CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
1190 /* Make sure that if there is a response, it has the RESP bit set */
1191 if ((error == 0) && rptr && *rptr)
1192 (*rptr)->header.flags |= NGF_RESP;
1195 * If we had a return address it is up to us to free it. They should
1196 * have taken a copy if they needed to make a delayed response.
1199 FREE(retaddr, M_NETGRAPH);
1204 * Implement the 'generic' control messages
1207 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
1208 struct ng_mesg **resp)
1212 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
1214 FREE(msg, M_NETGRAPH);
1217 switch (msg->header.cmd) {
1223 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
1225 if (msg->header.arglen != sizeof(*mkp)) {
1229 mkp->type[sizeof(mkp->type) - 1] = '\0';
1230 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1231 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1232 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1237 struct ngm_connect *const con =
1238 (struct ngm_connect *) msg->data;
1241 if (msg->header.arglen != sizeof(*con)) {
1245 con->path[sizeof(con->path) - 1] = '\0';
1246 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1247 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1248 error = ng_path2node(here, con->path, &node2, NULL);
1251 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1256 struct ngm_name *const nam = (struct ngm_name *) msg->data;
1258 if (msg->header.arglen != sizeof(*nam)) {
1262 nam->name[sizeof(nam->name) - 1] = '\0';
1263 error = ng_name_node(here, nam->name);
1268 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1271 if (msg->header.arglen != sizeof(*rmh)) {
1275 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1276 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
1277 ng_destroy_hook(hook);
1282 struct nodeinfo *ni;
1285 /* Get response struct */
1290 NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1296 /* Fill in node info */
1297 ni = (struct nodeinfo *) rp->data;
1298 if (here->name != NULL)
1299 strncpy(ni->name, here->name, NG_NODELEN);
1300 strncpy(ni->type, here->type->name, NG_TYPELEN);
1301 ni->id = ng_node2ID(here);
1302 ni->hooks = here->numhooks;
1308 const int nhooks = here->numhooks;
1309 struct hooklist *hl;
1310 struct nodeinfo *ni;
1314 /* Get response struct */
1319 NG_MKRESPONSE(rp, msg, sizeof(*hl)
1320 + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1325 hl = (struct hooklist *) rp->data;
1328 /* Fill in node info */
1330 strncpy(ni->name, here->name, NG_NODELEN);
1331 strncpy(ni->type, here->type->name, NG_TYPELEN);
1332 ni->id = ng_node2ID(here);
1334 /* Cycle through the linked list of hooks */
1336 LIST_FOREACH(hook, &here->hooks, hooks) {
1337 struct linkinfo *const link = &hl->link[ni->hooks];
1339 if (ni->hooks >= nhooks) {
1340 log(LOG_ERR, "%s: number of %s changed\n",
1344 if ((hook->flags & HK_INVALID) != 0)
1346 strncpy(link->ourhook, hook->name, NG_HOOKLEN);
1347 strncpy(link->peerhook, hook->peer->name, NG_HOOKLEN);
1348 if (hook->peer->node->name != NULL)
1349 strncpy(link->nodeinfo.name,
1350 hook->peer->node->name, NG_NODELEN);
1351 strncpy(link->nodeinfo.type,
1352 hook->peer->node->type->name, NG_TYPELEN);
1353 link->nodeinfo.id = ng_node2ID(hook->peer->node);
1354 link->nodeinfo.hooks = hook->peer->node->numhooks;
1364 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1365 struct namelist *nl;
1375 /* Count number of nodes */
1376 LIST_FOREACH(node, &nodelist, nodes) {
1377 if ((node->flags & NG_INVALID) == 0
1378 && (unnamed || node->name != NULL))
1382 /* Get response struct */
1387 NG_MKRESPONSE(rp, msg, sizeof(*nl)
1388 + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1393 nl = (struct namelist *) rp->data;
1395 /* Cycle through the linked list of nodes */
1397 LIST_FOREACH(node, &nodelist, nodes) {
1398 struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1400 if (nl->numnames >= num) {
1401 log(LOG_ERR, "%s: number of %s changed\n",
1405 if ((node->flags & NG_INVALID) != 0)
1407 if (!unnamed && node->name == NULL)
1409 if (node->name != NULL)
1410 strncpy(np->name, node->name, NG_NODELEN);
1411 strncpy(np->type, node->type->name, NG_TYPELEN);
1412 np->id = ng_node2ID(node);
1413 np->hooks = node->numhooks;
1422 struct typelist *tl;
1424 struct ng_type *type;
1432 /* Count number of types */
1433 LIST_FOREACH(type, &typelist, types)
1436 /* Get response struct */
1441 NG_MKRESPONSE(rp, msg, sizeof(*tl)
1442 + (num * sizeof(struct typeinfo)), M_NOWAIT);
1447 tl = (struct typelist *) rp->data;
1449 /* Cycle through the linked list of types */
1451 LIST_FOREACH(type, &typelist, types) {
1452 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1454 if (tl->numtypes >= num) {
1455 log(LOG_ERR, "%s: number of %s changed\n",
1459 strncpy(tp->type_name, type->name, NG_TYPELEN);
1460 tp->numnodes = type->refs - 1; /* don't count list */
1467 case NGM_BINARY2ASCII:
1469 int bufSize = 20 * 1024; /* XXX hard coded constant */
1470 const struct ng_parse_type *argstype;
1471 const struct ng_cmdlist *c;
1472 struct ng_mesg *rp, *binary, *ascii;
1474 /* Data area must contain a valid netgraph message */
1475 binary = (struct ng_mesg *)msg->data;
1476 if (msg->header.arglen < sizeof(struct ng_mesg)
1477 || msg->header.arglen - sizeof(struct ng_mesg)
1478 < binary->header.arglen) {
1483 /* Get a response message with lots of room */
1484 NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
1489 ascii = (struct ng_mesg *)rp->data;
1491 /* Copy binary message header to response message payload */
1492 bcopy(binary, ascii, sizeof(*binary));
1494 /* Find command by matching typecookie and command number */
1495 for (c = here->type->cmdlist;
1496 c != NULL && c->name != NULL; c++) {
1497 if (binary->header.typecookie == c->cookie
1498 && binary->header.cmd == c->cmd)
1501 if (c == NULL || c->name == NULL) {
1502 for (c = ng_generic_cmds; c->name != NULL; c++) {
1503 if (binary->header.typecookie == c->cookie
1504 && binary->header.cmd == c->cmd)
1507 if (c->name == NULL) {
1508 FREE(rp, M_NETGRAPH);
1514 /* Convert command name to ASCII */
1515 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
1518 /* Convert command arguments to ASCII */
1519 argstype = (binary->header.flags & NGF_RESP) ?
1520 c->respType : c->mesgType;
1521 if (argstype == NULL)
1522 *ascii->data = '\0';
1524 if ((error = ng_unparse(argstype,
1525 (u_char *)binary->data,
1526 ascii->data, bufSize)) != 0) {
1527 FREE(rp, M_NETGRAPH);
1532 /* Return the result as struct ng_mesg plus ASCII string */
1533 bufSize = strlen(ascii->data) + 1;
1534 ascii->header.arglen = bufSize;
1535 rp->header.arglen = sizeof(*ascii) + bufSize;
1540 case NGM_ASCII2BINARY:
1542 int bufSize = 2000; /* XXX hard coded constant */
1543 const struct ng_cmdlist *c;
1544 const struct ng_parse_type *argstype;
1545 struct ng_mesg *rp, *ascii, *binary;
1548 /* Data area must contain at least a struct ng_mesg + '\0' */
1549 ascii = (struct ng_mesg *)msg->data;
1550 if (msg->header.arglen < sizeof(*ascii) + 1
1551 || ascii->header.arglen < 1
1552 || msg->header.arglen
1553 < sizeof(*ascii) + ascii->header.arglen) {
1557 ascii->data[ascii->header.arglen - 1] = '\0';
1559 /* Get a response message with lots of room */
1560 NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
1565 binary = (struct ng_mesg *)rp->data;
1567 /* Copy ASCII message header to response message payload */
1568 bcopy(ascii, binary, sizeof(*ascii));
1570 /* Find command by matching ASCII command string */
1571 for (c = here->type->cmdlist;
1572 c != NULL && c->name != NULL; c++) {
1573 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1576 if (c == NULL || c->name == NULL) {
1577 for (c = ng_generic_cmds; c->name != NULL; c++) {
1578 if (strcmp(ascii->header.cmdstr, c->name) == 0)
1581 if (c->name == NULL) {
1582 FREE(rp, M_NETGRAPH);
1588 /* Convert command name to binary */
1589 binary->header.cmd = c->cmd;
1590 binary->header.typecookie = c->cookie;
1592 /* Convert command arguments to binary */
1593 argstype = (binary->header.flags & NGF_RESP) ?
1594 c->respType : c->mesgType;
1595 if (argstype == NULL)
1598 if ((error = ng_parse(argstype, ascii->data,
1599 &off, (u_char *)binary->data, &bufSize)) != 0) {
1600 FREE(rp, M_NETGRAPH);
1605 /* Return the result */
1606 binary->header.arglen = bufSize;
1607 rp->header.arglen = sizeof(*binary) + bufSize;
1612 case NGM_TEXT_CONFIG:
1613 case NGM_TEXT_STATUS:
1615 * This one is tricky as it passes the command down to the
1616 * actual node, even though it is a generic type command.
1617 * This means we must assume that the msg is already freed
1618 * when control passes back to us.
1624 if (here->type->rcvmsg != NULL)
1625 return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1626 /* Fall through if rcvmsg not supported */
1631 FREE(msg, M_NETGRAPH);
1636 * Send a data packet to a node. If the recipient has no
1637 * 'receive data' method, then silently discard the packet.
1640 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1642 int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1646 if (hook && (hook->flags & HK_INVALID) == 0) {
1647 rcvdata = hook->peer->node->type->rcvdata;
1648 if (rcvdata != NULL)
1649 error = (*rcvdata)(hook->peer, m, meta);
1652 NG_FREE_DATA(m, meta);
1657 NG_FREE_DATA(m, meta);
1663 * Send a queued data packet to a node. If the recipient has no
1664 * 'receive queued data' method, then try the 'receive data' method above.
1667 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1669 int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1673 if (hook && (hook->flags & HK_INVALID) == 0) {
1674 rcvdataq = hook->peer->node->type->rcvdataq;
1675 if (rcvdataq != NULL)
1676 error = (*rcvdataq)(hook->peer, m, meta);
1678 error = ng_send_data(hook, m, meta);
1683 NG_FREE_DATA(m, meta);
1691 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
1694 ng_copy_meta(meta_p meta)
1700 MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
1703 meta2->allocated_len = meta->used_len;
1704 bcopy(meta, meta2, meta->used_len);
1708 /************************************************************************
1710 ************************************************************************/
1713 * Handle the loading/unloading of a netgraph node type module
1716 ng_mod_event(module_t mod, int event, void *data)
1718 struct ng_type *const type = data;
1724 /* Register new netgraph node type */
1726 if ((error = ng_newtype(type)) != 0) {
1731 /* Call type specific code */
1732 if (type->mod_event != NULL)
1733 if ((error = (*type->mod_event)(mod, event, data))) {
1734 type->refs--; /* undo it */
1735 LIST_REMOVE(type, types);
1742 if (type->refs > 1) { /* make sure no nodes exist! */
1745 if (type->refs == 0) {
1746 /* failed load, nothing to undo */
1750 if (type->mod_event != NULL) { /* check with type */
1751 error = (*type->mod_event)(mod, event, data);
1752 if (error != 0) { /* type refuses.. */
1757 LIST_REMOVE(type, types);
1763 if (type->mod_event != NULL)
1764 error = (*type->mod_event)(mod, event, data);
1766 error = 0; /* XXX ? */
1773 * Handle loading and unloading for this code.
1774 * The only thing we need to link into is the NETISR strucure.
1777 ngb_mod_event(module_t mod, int event, void *data)
1783 /* Register line discipline */
1785 netisr_register(NETISR_NETGRAPH, cpu0_portfn, ngintr);
1790 /* You cant unload it because an interface may be using it. */
1800 static moduledata_t netgraph_mod = {
1805 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1806 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
1807 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
1808 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
1810 /************************************************************************
1812 ************************************************************************/
1814 /* The structure for queueing across ISR switches */
1815 struct ng_queue_entry {
1817 struct ng_queue_entry *next;
1820 hook_p da_hook; /* target hook */
1825 struct ng_mesg *msg_msg;
1831 #define NGQF_DATA 0x01 /* the queue element is data */
1832 #define NGQF_MESG 0x02 /* the queue element is a message */
1834 static struct ng_queue_entry *ngqbase; /* items to be unqueued */
1835 static struct ng_queue_entry *ngqlast; /* last item queued */
1836 static const int ngqroom = 256; /* max items to queue */
1837 static int ngqsize; /* number of items in queue */
1839 static struct ng_queue_entry *ngqfree; /* free ones */
1840 static const int ngqfreemax = 256;/* cache at most this many */
1841 static int ngqfreesize; /* number of cached entries */
1846 static struct ng_queue_entry *
1849 struct ng_queue_entry *q;
1851 /* Could be guarding against tty ints or whatever */
1854 /* Try get a cached queue block, or else allocate a new one */
1855 if ((q = ngqfree) == NULL) {
1857 if (ngqsize < ngqroom) { /* don't worry about races */
1858 MALLOC(q, struct ng_queue_entry *,
1859 sizeof(*q), M_NETGRAPH, M_NOWAIT);
1870 * Release a queue entry
1872 #define RETURN_QBLK(q) \
1874 if (ngqfreesize < ngqfreemax) { /* don't worry about races */ \
1876 (q)->next = ngqfree; \
1881 FREE((q), M_NETGRAPH); \
1886 * Running at a raised (but we don't know which) processor priority level,
1887 * put the data onto a queue to be picked up by another PPL (probably splnet)
1890 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1892 struct ng_queue_entry *q;
1895 NG_FREE_DATA(m, meta);
1898 if ((q = ng_getqblk()) == NULL) {
1899 NG_FREE_DATA(m, meta);
1903 /* Fill out the contents */
1904 q->flags = NGQF_DATA;
1906 q->body.data.da_hook = hook;
1907 q->body.data.da_m = m;
1908 q->body.data.da_meta = meta;
1909 crit_enter(); /* protect refs and queue */
1910 hook->refs++; /* don't let it go away while on the queue */
1912 /* Put it on the queue */
1922 /* Schedule software interrupt to handle it later */
1923 schednetisr(NETISR_NETGRAPH);
1928 * Running at a raised (but we don't know which) processor priority level,
1929 * put the msg onto a queue to be picked up by another PPL (probably splnet)
1932 ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
1934 struct ng_queue_entry *q;
1936 char *retaddr = NULL;
1939 /* Find the target node. */
1940 error = ng_path2node(here, address, &dest, &retaddr);
1942 FREE(msg, M_NETGRAPH);
1945 if ((q = ng_getqblk()) == NULL) {
1946 FREE(msg, M_NETGRAPH);
1948 FREE(retaddr, M_NETGRAPH);
1952 /* Fill out the contents */
1953 q->flags = NGQF_MESG;
1955 q->body.msg.msg_node = dest;
1956 q->body.msg.msg_msg = msg;
1957 q->body.msg.msg_retaddr = retaddr;
1958 crit_enter(); /* protect refs and queue */
1959 dest->refs++; /* don't let it go away while on the queue */
1961 /* Put it on the queue */
1971 /* Schedule software interrupt to handle it later */
1972 schednetisr(NETISR_NETGRAPH);
1977 * Pick an item off the queue, process it, and dispose of the queue entry.
1978 * Should be running at splnet.
1981 ngintr(struct netmsg *pmsg)
1983 struct mbuf *m = ((struct netmsg_packet *)pmsg)->nm_packet;
1985 struct ng_queue_entry *ngq;
1988 struct ng_mesg *msg;
1994 if ((ngq = ngqbase)) {
1995 ngqbase = ngq->next;
2001 switch (ngq->flags) {
2003 hook = ngq->body.data.da_hook;
2004 m = ngq->body.data.da_m;
2005 meta = ngq->body.data.da_meta;
2007 NG_SEND_DATAQ(error, hook, m, meta);
2008 ng_unref_hook(hook);
2011 node = ngq->body.msg.msg_node;
2012 msg = ngq->body.msg.msg_msg;
2013 retaddr = ngq->body.msg.msg_retaddr;
2015 if (node->flags & NG_INVALID) {
2016 FREE(msg, M_NETGRAPH);
2018 CALL_MSG_HANDLER(error, node, msg,
2023 FREE(retaddr, M_NETGRAPH);
2030 lwkt_replymsg(&pmsg->nm_lmsg, 0);