The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netgraph/ng_base.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*
    2  * ng_base.c
    3  */
    4 
    5 /*-
    6  * Copyright (c) 1996-1999 Whistle Communications, Inc.
    7  * All rights reserved.
    8  *
    9  * Subject to the following obligations and disclaimer of warranty, use and
   10  * redistribution of this software, in source or object code forms, with or
   11  * without modifications are expressly permitted by Whistle Communications;
   12  * provided, however, that:
   13  * 1. Any and all reproductions of the source or object code must include the
   14  *    copyright notice above and the following disclaimer of warranties; and
   15  * 2. No rights are granted, in any manner or form, to use Whistle
   16  *    Communications, Inc. trademarks, including the mark "WHISTLE
   17  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
   18  *    such appears in the above copyright notice or in the software.
   19  *
   20  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
   21  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
   22  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
   23  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
   24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
   25  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
   26  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
   27  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
   28  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
   29  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
   30  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
   31  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
   32  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
   33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   35  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
   36  * OF SUCH DAMAGE.
   37  *
   38  * Authors: Julian Elischer <julian@freebsd.org>
   39  *          Archie Cobbs <archie@freebsd.org>
   40  *
   41  * $FreeBSD: releng/6.2/sys/netgraph/ng_base.c 163294 2006-10-13 08:09:44Z glebius $
   42  * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
   43  */
   44 
   45 /*
   46  * This file implements the base netgraph code.
   47  */
   48 
   49 #include <sys/param.h>
   50 #include <sys/systm.h>
   51 #include <sys/ctype.h>
   52 #include <sys/errno.h>
   53 #include <sys/kdb.h>
   54 #include <sys/kernel.h>
   55 #include <sys/ktr.h>
   56 #include <sys/limits.h>
   57 #include <sys/malloc.h>
   58 #include <sys/mbuf.h>
   59 #include <sys/queue.h>
   60 #include <sys/sysctl.h>
   61 #include <sys/syslog.h>
   62 
   63 #include <net/netisr.h>
   64 
   65 #include <netgraph/ng_message.h>
   66 #include <netgraph/netgraph.h>
   67 #include <netgraph/ng_parse.h>
   68 
   69 MODULE_VERSION(netgraph, NG_ABI_VERSION);
   70 
   71 /* List of all active nodes */
   72 static LIST_HEAD(, ng_node) ng_nodelist;
   73 static struct mtx       ng_nodelist_mtx;
   74 
   75 /* Mutex to protect topology events. */
   76 static struct mtx       ng_topo_mtx;
   77 
   78 #ifdef  NETGRAPH_DEBUG
   79 static struct mtx       ngq_mtx;        /* protects the queue item list */
   80 
   81 static SLIST_HEAD(, ng_node) ng_allnodes;
   82 static LIST_HEAD(, ng_node) ng_freenodes; /* in debug, we never free() them */
   83 static SLIST_HEAD(, ng_hook) ng_allhooks;
   84 static LIST_HEAD(, ng_hook) ng_freehooks; /* in debug, we never free() them */
   85 
   86 static void ng_dumpitems(void);
   87 static void ng_dumpnodes(void);
   88 static void ng_dumphooks(void);
   89 
   90 #endif  /* NETGRAPH_DEBUG */
   91 /*
   92  * DEAD versions of the structures.
   93  * In order to avoid races, it is sometimes neccesary to point
   94  * at SOMETHING even though theoretically, the current entity is
   95  * INVALID. Use these to avoid these races.
   96  */
   97 struct ng_type ng_deadtype = {
   98         NG_ABI_VERSION,
   99         "dead",
  100         NULL,   /* modevent */
  101         NULL,   /* constructor */
  102         NULL,   /* rcvmsg */
  103         NULL,   /* shutdown */
  104         NULL,   /* newhook */
  105         NULL,   /* findhook */
  106         NULL,   /* connect */
  107         NULL,   /* rcvdata */
  108         NULL,   /* disconnect */
  109         NULL,   /* cmdlist */
  110 };
  111 
  112 struct ng_node ng_deadnode = {
  113         "dead",
  114         &ng_deadtype,   
  115         NGF_INVALID,
  116         1,      /* refs */
  117         0,      /* numhooks */
  118         NULL,   /* private */
  119         0,      /* ID */
  120         LIST_HEAD_INITIALIZER(ng_deadnode.hooks),
  121         {},     /* all_nodes list entry */
  122         {},     /* id hashtable list entry */
  123         {},     /* workqueue entry */
  124         {       0,
  125                 {}, /* should never use! (should hang) */
  126                 NULL,
  127                 &ng_deadnode.nd_input_queue.queue,
  128                 &ng_deadnode
  129         },
  130 #ifdef  NETGRAPH_DEBUG
  131         ND_MAGIC,
  132         __FILE__,
  133         __LINE__,
  134         {NULL}
  135 #endif  /* NETGRAPH_DEBUG */
  136 };
  137 
  138 struct ng_hook ng_deadhook = {
  139         "dead",
  140         NULL,           /* private */
  141         HK_INVALID | HK_DEAD,
  142         1,              /* refs always >= 1 */
  143         0,              /* undefined data link type */
  144         &ng_deadhook,   /* Peer is self */
  145         &ng_deadnode,   /* attached to deadnode */
  146         {},             /* hooks list */
  147         NULL,           /* override rcvmsg() */
  148         NULL,           /* override rcvdata() */
  149 #ifdef  NETGRAPH_DEBUG
  150         HK_MAGIC,
  151         __FILE__,
  152         __LINE__,
  153         {NULL}
  154 #endif  /* NETGRAPH_DEBUG */
  155 };
  156 
  157 /*
  158  * END DEAD STRUCTURES
  159  */
  160 /* List nodes with unallocated work */
  161 static TAILQ_HEAD(, ng_node) ng_worklist = TAILQ_HEAD_INITIALIZER(ng_worklist);
  162 static struct mtx       ng_worklist_mtx;   /* MUST LOCK NODE FIRST */
  163 
  164 /* List of installed types */
  165 static LIST_HEAD(, ng_type) ng_typelist;
  166 static struct mtx       ng_typelist_mtx;
  167 
  168 /* Hash related definitions */
  169 /* XXX Don't need to initialise them because it's a LIST */
  170 #define NG_ID_HASH_SIZE 32 /* most systems wont need even this many */
  171 static LIST_HEAD(, ng_node) ng_ID_hash[NG_ID_HASH_SIZE];
  172 static struct mtx       ng_idhash_mtx;
  173 /* Method to find a node.. used twice so do it here */
  174 #define NG_IDHASH_FN(ID) ((ID) % (NG_ID_HASH_SIZE))
  175 #define NG_IDHASH_FIND(ID, node)                                        \
  176         do {                                                            \
  177                 mtx_assert(&ng_idhash_mtx, MA_OWNED);                   \
  178                 LIST_FOREACH(node, &ng_ID_hash[NG_IDHASH_FN(ID)],       \
  179                                                 nd_idnodes) {           \
  180                         if (NG_NODE_IS_VALID(node)                      \
  181                         && (NG_NODE_ID(node) == ID)) {                  \
  182                                 break;                                  \
  183                         }                                               \
  184                 }                                                       \
  185         } while (0)
  186 
  187 
  188 /* Internal functions */
  189 static int      ng_add_hook(node_p node, const char *name, hook_p * hookp);
  190 static int      ng_generic_msg(node_p here, item_p item, hook_p lasthook);
  191 static ng_ID_t  ng_decodeidname(const char *name);
  192 static int      ngb_mod_event(module_t mod, int event, void *data);
  193 static void     ng_worklist_remove(node_p node);
  194 static void     ngintr(void);
  195 static int      ng_apply_item(node_p node, item_p item, int rw);
  196 static void     ng_flush_input_queue(struct ng_queue * ngq);
  197 static void     ng_setisr(node_p node);
  198 static node_p   ng_ID2noderef(ng_ID_t ID);
  199 static int      ng_con_nodes(node_p node, const char *name, node_p node2,
  200                                                         const char *name2);
  201 static void     ng_con_part2(node_p node, hook_p hook, void *arg1, int arg2);
  202 static void     ng_con_part3(node_p node, hook_p hook, void *arg1, int arg2);
  203 static int      ng_mkpeer(node_p node, const char *name,
  204                                                 const char *name2, char *type);
  205 
  206 /* Imported, these used to be externally visible, some may go back. */
  207 void    ng_destroy_hook(hook_p hook);
  208 node_p  ng_name2noderef(node_p node, const char *name);
  209 int     ng_path2noderef(node_p here, const char *path,
  210         node_p *dest, hook_p *lasthook);
  211 int     ng_make_node(const char *type, node_p *nodepp);
  212 int     ng_path_parse(char *addr, char **node, char **path, char **hook);
  213 void    ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3);
  214 void    ng_unname(node_p node);
  215 
  216 
  217 /* Our own netgraph malloc type */
  218 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
  219 MALLOC_DEFINE(M_NETGRAPH_HOOK, "netgraph_hook", "netgraph hook structures");
  220 MALLOC_DEFINE(M_NETGRAPH_NODE, "netgraph_node", "netgraph node structures");
  221 MALLOC_DEFINE(M_NETGRAPH_ITEM, "netgraph_item", "netgraph item structures");
  222 MALLOC_DEFINE(M_NETGRAPH_MSG, "netgraph_msg", "netgraph name storage");
  223 
  224 /* Should not be visible outside this file */
  225 
  226 #define _NG_ALLOC_HOOK(hook) \
  227         MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH_HOOK, M_NOWAIT | M_ZERO)
  228 #define _NG_ALLOC_NODE(node) \
  229         MALLOC(node, node_p, sizeof(*node), M_NETGRAPH_NODE, M_NOWAIT | M_ZERO)
  230 
  231 #ifdef NETGRAPH_DEBUG /*----------------------------------------------*/
  232 /*
  233  * In debug mode:
  234  * In an attempt to help track reference count screwups
  235  * we do not free objects back to the malloc system, but keep them
  236  * in a local cache where we can examine them and keep information safely
  237  * after they have been freed.
  238  * We use this scheme for nodes and hooks, and to some extent for items.
  239  */
  240 static __inline hook_p
  241 ng_alloc_hook(void)
  242 {
  243         hook_p hook;
  244         SLIST_ENTRY(ng_hook) temp;
  245         mtx_lock(&ng_nodelist_mtx);
  246         hook = LIST_FIRST(&ng_freehooks);
  247         if (hook) {
  248                 LIST_REMOVE(hook, hk_hooks);
  249                 bcopy(&hook->hk_all, &temp, sizeof(temp));
  250                 bzero(hook, sizeof(struct ng_hook));
  251                 bcopy(&temp, &hook->hk_all, sizeof(temp));
  252                 mtx_unlock(&ng_nodelist_mtx);
  253                 hook->hk_magic = HK_MAGIC;
  254         } else {
  255                 mtx_unlock(&ng_nodelist_mtx);
  256                 _NG_ALLOC_HOOK(hook);
  257                 if (hook) {
  258                         hook->hk_magic = HK_MAGIC;
  259                         mtx_lock(&ng_nodelist_mtx);
  260                         SLIST_INSERT_HEAD(&ng_allhooks, hook, hk_all);
  261                         mtx_unlock(&ng_nodelist_mtx);
  262                 }
  263         }
  264         return (hook);
  265 }
  266 
  267 static __inline node_p
  268 ng_alloc_node(void)
  269 {
  270         node_p node;
  271         SLIST_ENTRY(ng_node) temp;
  272         mtx_lock(&ng_nodelist_mtx);
  273         node = LIST_FIRST(&ng_freenodes);
  274         if (node) {
  275                 LIST_REMOVE(node, nd_nodes);
  276                 bcopy(&node->nd_all, &temp, sizeof(temp));
  277                 bzero(node, sizeof(struct ng_node));
  278                 bcopy(&temp, &node->nd_all, sizeof(temp));
  279                 mtx_unlock(&ng_nodelist_mtx);
  280                 node->nd_magic = ND_MAGIC;
  281         } else {
  282                 mtx_unlock(&ng_nodelist_mtx);
  283                 _NG_ALLOC_NODE(node);
  284                 if (node) {
  285                         node->nd_magic = ND_MAGIC;
  286                         mtx_lock(&ng_nodelist_mtx);
  287                         SLIST_INSERT_HEAD(&ng_allnodes, node, nd_all);
  288                         mtx_unlock(&ng_nodelist_mtx);
  289                 }
  290         }
  291         return (node);
  292 }
  293 
  294 #define NG_ALLOC_HOOK(hook) do { (hook) = ng_alloc_hook(); } while (0)
  295 #define NG_ALLOC_NODE(node) do { (node) = ng_alloc_node(); } while (0)
  296 
  297 
  298 #define NG_FREE_HOOK(hook)                                              \
  299         do {                                                            \
  300                 mtx_lock(&ng_nodelist_mtx);                     \
  301                 LIST_INSERT_HEAD(&ng_freehooks, hook, hk_hooks);        \
  302                 hook->hk_magic = 0;                                     \
  303                 mtx_unlock(&ng_nodelist_mtx);                   \
  304         } while (0)
  305 
  306 #define NG_FREE_NODE(node)                                              \
  307         do {                                                            \
  308                 mtx_lock(&ng_nodelist_mtx);                     \
  309                 LIST_INSERT_HEAD(&ng_freenodes, node, nd_nodes);        \
  310                 node->nd_magic = 0;                                     \
  311                 mtx_unlock(&ng_nodelist_mtx);                   \
  312         } while (0)
  313 
  314 #else /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
  315 
  316 #define NG_ALLOC_HOOK(hook) _NG_ALLOC_HOOK(hook)
  317 #define NG_ALLOC_NODE(node) _NG_ALLOC_NODE(node)
  318 
  319 #define NG_FREE_HOOK(hook) do { FREE((hook), M_NETGRAPH_HOOK); } while (0)
  320 #define NG_FREE_NODE(node) do { FREE((node), M_NETGRAPH_NODE); } while (0)
  321 
  322 #endif /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
  323 
  324 /* Set this to kdb_enter("X") to catch all errors as they occur */
  325 #ifndef TRAP_ERROR
  326 #define TRAP_ERROR()
  327 #endif
  328 
  329 static  ng_ID_t nextID = 1;
  330 
  331 #ifdef INVARIANTS
  332 #define CHECK_DATA_MBUF(m)      do {                                    \
  333                 struct mbuf *n;                                         \
  334                 int total;                                              \
  335                                                                         \
  336                 M_ASSERTPKTHDR(m);                                      \
  337                 for (total = 0, n = (m); n != NULL; n = n->m_next) {    \
  338                         total += n->m_len;                              \
  339                         if (n->m_nextpkt != NULL)                       \
  340                                 panic("%s: m_nextpkt", __func__);       \
  341                 }                                                       \
  342                                                                         \
  343                 if ((m)->m_pkthdr.len != total) {                       \
  344                         panic("%s: %d != %d",                           \
  345                             __func__, (m)->m_pkthdr.len, total);        \
  346                 }                                                       \
  347         } while (0)
  348 #else
  349 #define CHECK_DATA_MBUF(m)
  350 #endif
  351 
  352 
  353 /************************************************************************
  354         Parse type definitions for generic messages
  355 ************************************************************************/
  356 
  357 /* Handy structure parse type defining macro */
  358 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args)                          \
  359 static const struct ng_parse_struct_field                               \
  360         ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args;  \
  361 static const struct ng_parse_type ng_generic_ ## lo ## _type = {        \
  362         &ng_parse_struct_type,                                          \
  363         &ng_ ## lo ## _type_fields                                      \
  364 }
  365 
  366 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
  367 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
  368 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
  369 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
  370 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
  371 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
  372 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
  373 
  374 /* Get length of an array when the length is stored as a 32 bit
  375    value immediately preceding the array -- as with struct namelist
  376    and struct typelist. */
  377 static int
  378 ng_generic_list_getLength(const struct ng_parse_type *type,
  379         const u_char *start, const u_char *buf)
  380 {
  381         return *((const u_int32_t *)(buf - 4));
  382 }
  383 
  384 /* Get length of the array of struct linkinfo inside a struct hooklist */
  385 static int
  386 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
  387         const u_char *start, const u_char *buf)
  388 {
  389         const struct hooklist *hl = (const struct hooklist *)start;
  390 
  391         return hl->nodeinfo.hooks;
  392 }
  393 
  394 /* Array type for a variable length array of struct namelist */
  395 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
  396         &ng_generic_nodeinfo_type,
  397         &ng_generic_list_getLength
  398 };
  399 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
  400         &ng_parse_array_type,
  401         &ng_nodeinfoarray_type_info
  402 };
  403 
  404 /* Array type for a variable length array of struct typelist */
  405 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
  406         &ng_generic_typeinfo_type,
  407         &ng_generic_list_getLength
  408 };
  409 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
  410         &ng_parse_array_type,
  411         &ng_typeinfoarray_type_info
  412 };
  413 
  414 /* Array type for array of struct linkinfo in struct hooklist */
  415 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
  416         &ng_generic_linkinfo_type,
  417         &ng_generic_linkinfo_getLength
  418 };
  419 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
  420         &ng_parse_array_type,
  421         &ng_generic_linkinfo_array_type_info
  422 };
  423 
  424 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
  425 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
  426         (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
  427 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
  428         (&ng_generic_nodeinfoarray_type));
  429 
  430 /* List of commands and how to convert arguments to/from ASCII */
  431 static const struct ng_cmdlist ng_generic_cmds[] = {
  432         {
  433           NGM_GENERIC_COOKIE,
  434           NGM_SHUTDOWN,
  435           "shutdown",
  436           NULL,
  437           NULL
  438         },
  439         {
  440           NGM_GENERIC_COOKIE,
  441           NGM_MKPEER,
  442           "mkpeer",
  443           &ng_generic_mkpeer_type,
  444           NULL
  445         },
  446         {
  447           NGM_GENERIC_COOKIE,
  448           NGM_CONNECT,
  449           "connect",
  450           &ng_generic_connect_type,
  451           NULL
  452         },
  453         {
  454           NGM_GENERIC_COOKIE,
  455           NGM_NAME,
  456           "name",
  457           &ng_generic_name_type,
  458           NULL
  459         },
  460         {
  461           NGM_GENERIC_COOKIE,
  462           NGM_RMHOOK,
  463           "rmhook",
  464           &ng_generic_rmhook_type,
  465           NULL
  466         },
  467         {
  468           NGM_GENERIC_COOKIE,
  469           NGM_NODEINFO,
  470           "nodeinfo",
  471           NULL,
  472           &ng_generic_nodeinfo_type
  473         },
  474         {
  475           NGM_GENERIC_COOKIE,
  476           NGM_LISTHOOKS,
  477           "listhooks",
  478           NULL,
  479           &ng_generic_hooklist_type
  480         },
  481         {
  482           NGM_GENERIC_COOKIE,
  483           NGM_LISTNAMES,
  484           "listnames",
  485           NULL,
  486           &ng_generic_listnodes_type    /* same as NGM_LISTNODES */
  487         },
  488         {
  489           NGM_GENERIC_COOKIE,
  490           NGM_LISTNODES,
  491           "listnodes",
  492           NULL,
  493           &ng_generic_listnodes_type
  494         },
  495         {
  496           NGM_GENERIC_COOKIE,
  497           NGM_LISTTYPES,
  498           "listtypes",
  499           NULL,
  500           &ng_generic_typeinfo_type
  501         },
  502         {
  503           NGM_GENERIC_COOKIE,
  504           NGM_TEXT_CONFIG,
  505           "textconfig",
  506           NULL,
  507           &ng_parse_string_type
  508         },
  509         {
  510           NGM_GENERIC_COOKIE,
  511           NGM_TEXT_STATUS,
  512           "textstatus",
  513           NULL,
  514           &ng_parse_string_type
  515         },
  516         {
  517           NGM_GENERIC_COOKIE,
  518           NGM_ASCII2BINARY,
  519           "ascii2binary",
  520           &ng_parse_ng_mesg_type,
  521           &ng_parse_ng_mesg_type
  522         },
  523         {
  524           NGM_GENERIC_COOKIE,
  525           NGM_BINARY2ASCII,
  526           "binary2ascii",
  527           &ng_parse_ng_mesg_type,
  528           &ng_parse_ng_mesg_type
  529         },
  530         { 0 }
  531 };
  532 
  533 /************************************************************************
  534                         Node routines
  535 ************************************************************************/
  536 
  537 /*
  538  * Instantiate a node of the requested type
  539  */
  540 int
  541 ng_make_node(const char *typename, node_p *nodepp)
  542 {
  543         struct ng_type *type;
  544         int     error;
  545 
  546         /* Check that the type makes sense */
  547         if (typename == NULL) {
  548                 TRAP_ERROR();
  549                 return (EINVAL);
  550         }
  551 
  552         /* Locate the node type. If we fail we return. Do not try to load
  553          * module.
  554          */
  555         if ((type = ng_findtype(typename)) == NULL)
  556                 return (ENXIO);
  557 
  558         /*
  559          * If we have a constructor, then make the node and
  560          * call the constructor to do type specific initialisation.
  561          */
  562         if (type->constructor != NULL) {
  563                 if ((error = ng_make_node_common(type, nodepp)) == 0) {
  564                         if ((error = ((*type->constructor)(*nodepp)) != 0)) {
  565                                 NG_NODE_UNREF(*nodepp);
  566                         }
  567                 }
  568         } else {
  569                 /*
  570                  * Node has no constructor. We cannot ask for one
  571                  * to be made. It must be brought into existance by
  572                  * some external agency. The external agency should
  573                  * call ng_make_node_common() directly to get the
  574                  * netgraph part initialised.
  575                  */
  576                 TRAP_ERROR();
  577                 error = EINVAL;
  578         }
  579         return (error);
  580 }
  581 
  582 /*
  583  * Generic node creation. Called by node initialisation for externally
  584  * instantiated nodes (e.g. hardware, sockets, etc ).
  585  * The returned node has a reference count of 1.
  586  */
  587 int
  588 ng_make_node_common(struct ng_type *type, node_p *nodepp)
  589 {
  590         node_p node;
  591 
  592         /* Require the node type to have been already installed */
  593         if (ng_findtype(type->name) == NULL) {
  594                 TRAP_ERROR();
  595                 return (EINVAL);
  596         }
  597 
  598         /* Make a node and try attach it to the type */
  599         NG_ALLOC_NODE(node);
  600         if (node == NULL) {
  601                 TRAP_ERROR();
  602                 return (ENOMEM);
  603         }
  604         node->nd_type = type;
  605         NG_NODE_REF(node);                              /* note reference */
  606         type->refs++;
  607 
  608         mtx_init(&node->nd_input_queue.q_mtx, "ng_node", NULL, MTX_SPIN);
  609         node->nd_input_queue.queue = NULL;
  610         node->nd_input_queue.last = &node->nd_input_queue.queue;
  611         node->nd_input_queue.q_flags = 0;
  612         node->nd_input_queue.q_node = node;
  613 
  614         /* Initialize hook list for new node */
  615         LIST_INIT(&node->nd_hooks);
  616 
  617         /* Link us into the node linked list */
  618         mtx_lock(&ng_nodelist_mtx);
  619         LIST_INSERT_HEAD(&ng_nodelist, node, nd_nodes);
  620         mtx_unlock(&ng_nodelist_mtx);
  621 
  622 
  623         /* get an ID and put us in the hash chain */
  624         mtx_lock(&ng_idhash_mtx);
  625         for (;;) { /* wrap protection, even if silly */
  626                 node_p node2 = NULL;
  627                 node->nd_ID = nextID++; /* 137/second for 1 year before wrap */
  628 
  629                 /* Is there a problem with the new number? */
  630                 NG_IDHASH_FIND(node->nd_ID, node2); /* already taken? */
  631                 if ((node->nd_ID != 0) && (node2 == NULL)) {
  632                         break;
  633                 }
  634         }
  635         LIST_INSERT_HEAD(&ng_ID_hash[NG_IDHASH_FN(node->nd_ID)],
  636                                                         node, nd_idnodes);
  637         mtx_unlock(&ng_idhash_mtx);
  638 
  639         /* Done */
  640         *nodepp = node;
  641         return (0);
  642 }
  643 
  644 /*
  645  * Forceably start the shutdown process on a node. Either call
  646  * it's shutdown method, or do the default shutdown if there is
  647  * no type-specific method.
  648  *
  649  * We can only be called form a shutdown message, so we know we have
  650  * a writer lock, and therefore exclusive access. It also means
  651  * that we should not be on the work queue, but we check anyhow.
  652  *
  653  * Persistent node types must have a type-specific method which
  654  * Allocates a new node in which case, this one is irretrievably going away,
  655  * or cleans up anything it needs, and just makes the node valid again,
  656  * in which case we allow the node to survive.
  657  *
  658  * XXX We need to think of how to tell a persistant node that we
  659  * REALLY need to go away because the hardware has gone or we
  660  * are rebooting.... etc.
  661  */
  662 void
  663 ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3)
  664 {
  665         hook_p hook;
  666 
  667         /* Check if it's already shutting down */
  668         if ((node->nd_flags & NGF_CLOSING) != 0)
  669                 return;
  670 
  671         if (node == &ng_deadnode) {
  672                 printf ("shutdown called on deadnode\n");
  673                 return;
  674         }
  675 
  676         /* Add an extra reference so it doesn't go away during this */
  677         NG_NODE_REF(node);
  678 
  679         /*
  680          * Mark it invalid so any newcomers know not to try use it
  681          * Also add our own mark so we can't recurse
  682          * note that NGF_INVALID does not do this as it's also set during
  683          * creation
  684          */
  685         node->nd_flags |= NGF_INVALID|NGF_CLOSING;
  686 
  687         /* If node has its pre-shutdown method, then call it first*/
  688         if (node->nd_type && node->nd_type->close)
  689                 (*node->nd_type->close)(node);
  690 
  691         /* Notify all remaining connected nodes to disconnect */
  692         while ((hook = LIST_FIRST(&node->nd_hooks)) != NULL)
  693                 ng_destroy_hook(hook);
  694 
  695         /*
  696          * Drain the input queue forceably.
  697          * it has no hooks so what's it going to do, bleed on someone?
  698          * Theoretically we came here from a queue entry that was added
  699          * Just before the queue was closed, so it should be empty anyway.
  700          * Also removes us from worklist if needed.
  701          */
  702         ng_flush_input_queue(&node->nd_input_queue);
  703 
  704         /* Ask the type if it has anything to do in this case */
  705         if (node->nd_type && node->nd_type->shutdown) {
  706                 (*node->nd_type->shutdown)(node);
  707                 if (NG_NODE_IS_VALID(node)) {
  708                         /*
  709                          * Well, blow me down if the node code hasn't declared
  710                          * that it doesn't want to die.
  711                          * Presumably it is a persistant node.
  712                          * If we REALLY want it to go away,
  713                          *  e.g. hardware going away,
  714                          * Our caller should set NGF_REALLY_DIE in nd_flags.
  715                          */
  716                         node->nd_flags &= ~(NGF_INVALID|NGF_CLOSING);
  717                         NG_NODE_UNREF(node); /* Assume they still have theirs */
  718                         return;
  719                 }
  720         } else {                                /* do the default thing */
  721                 NG_NODE_UNREF(node);
  722         }
  723 
  724         ng_unname(node); /* basically a NOP these days */
  725 
  726         /*
  727          * Remove extra reference, possibly the last
  728          * Possible other holders of references may include
  729          * timeout callouts, but theoretically the node's supposed to
  730          * have cancelled them. Possibly hardware dependencies may
  731          * force a driver to 'linger' with a reference.
  732          */
  733         NG_NODE_UNREF(node);
  734 }
  735 
  736 /*
  737  * Remove a reference to the node, possibly the last.
  738  * deadnode always acts as it it were the last.
  739  */
  740 int
  741 ng_unref_node(node_p node)
  742 {
  743         int v;
  744 
  745         if (node == &ng_deadnode) {
  746                 return (0);
  747         }
  748 
  749         do {
  750                 v = node->nd_refs - 1;
  751         } while (! atomic_cmpset_int(&node->nd_refs, v + 1, v));
  752 
  753         if (v == 0) { /* we were the last */
  754 
  755                 mtx_lock(&ng_nodelist_mtx);
  756                 node->nd_type->refs--; /* XXX maybe should get types lock? */
  757                 LIST_REMOVE(node, nd_nodes);
  758                 mtx_unlock(&ng_nodelist_mtx);
  759 
  760                 mtx_lock(&ng_idhash_mtx);
  761                 LIST_REMOVE(node, nd_idnodes);
  762                 mtx_unlock(&ng_idhash_mtx);
  763 
  764                 mtx_destroy(&node->nd_input_queue.q_mtx);
  765                 NG_FREE_NODE(node);
  766         }
  767         return (v);
  768 }
  769 
  770 /************************************************************************
  771                         Node ID handling
  772 ************************************************************************/
  773 static node_p
  774 ng_ID2noderef(ng_ID_t ID)
  775 {
  776         node_p node;
  777         mtx_lock(&ng_idhash_mtx);
  778         NG_IDHASH_FIND(ID, node);
  779         if(node)
  780                 NG_NODE_REF(node);
  781         mtx_unlock(&ng_idhash_mtx);
  782         return(node);
  783 }
  784 
  785 ng_ID_t
  786 ng_node2ID(node_p node)
  787 {
  788         return (node ? NG_NODE_ID(node) : 0);
  789 }
  790 
  791 /************************************************************************
  792                         Node name handling
  793 ************************************************************************/
  794 
  795 /*
  796  * Assign a node a name. Once assigned, the name cannot be changed.
  797  */
  798 int
  799 ng_name_node(node_p node, const char *name)
  800 {
  801         int i;
  802         node_p node2;
  803 
  804         /* Check the name is valid */
  805         for (i = 0; i < NG_NODESIZ; i++) {
  806                 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
  807                         break;
  808         }
  809         if (i == 0 || name[i] != '\0') {
  810                 TRAP_ERROR();
  811                 return (EINVAL);
  812         }
  813         if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
  814                 TRAP_ERROR();
  815                 return (EINVAL);
  816         }
  817 
  818         /* Check the name isn't already being used */
  819         if ((node2 = ng_name2noderef(node, name)) != NULL) {
  820                 NG_NODE_UNREF(node2);
  821                 TRAP_ERROR();
  822                 return (EADDRINUSE);
  823         }
  824 
  825         /* copy it */
  826         strlcpy(NG_NODE_NAME(node), name, NG_NODESIZ);
  827 
  828         return (0);
  829 }
  830 
  831 /*
  832  * Find a node by absolute name. The name should NOT end with ':'
  833  * The name "." means "this node" and "[xxx]" means "the node
  834  * with ID (ie, at address) xxx".
  835  *
  836  * Returns the node if found, else NULL.
  837  * Eventually should add something faster than a sequential search.
  838  * Note it aquires a reference on the node so you can be sure it's still there.
  839  */
  840 node_p
  841 ng_name2noderef(node_p here, const char *name)
  842 {
  843         node_p node;
  844         ng_ID_t temp;
  845 
  846         /* "." means "this node" */
  847         if (strcmp(name, ".") == 0) {
  848                 NG_NODE_REF(here);
  849                 return(here);
  850         }
  851 
  852         /* Check for name-by-ID */
  853         if ((temp = ng_decodeidname(name)) != 0) {
  854                 return (ng_ID2noderef(temp));
  855         }
  856 
  857         /* Find node by name */
  858         mtx_lock(&ng_nodelist_mtx);
  859         LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
  860                 if (NG_NODE_IS_VALID(node)
  861                 && NG_NODE_HAS_NAME(node)
  862                 && (strcmp(NG_NODE_NAME(node), name) == 0)) {
  863                         break;
  864                 }
  865         }
  866         if (node)
  867                 NG_NODE_REF(node);
  868         mtx_unlock(&ng_nodelist_mtx);
  869         return (node);
  870 }
  871 
  872 /*
  873  * Decode an ID name, eg. "[f03034de]". Returns 0 if the
  874  * string is not valid, otherwise returns the value.
  875  */
  876 static ng_ID_t
  877 ng_decodeidname(const char *name)
  878 {
  879         const int len = strlen(name);
  880         char *eptr;
  881         u_long val;
  882 
  883         /* Check for proper length, brackets, no leading junk */
  884         if ((len < 3)
  885         || (name[0] != '[')
  886         || (name[len - 1] != ']')
  887         || (!isxdigit(name[1]))) {
  888                 return ((ng_ID_t)0);
  889         }
  890 
  891         /* Decode number */
  892         val = strtoul(name + 1, &eptr, 16);
  893         if ((eptr - name != len - 1)
  894         || (val == ULONG_MAX)
  895         || (val == 0)) {
  896                 return ((ng_ID_t)0);
  897         }
  898         return (ng_ID_t)val;
  899 }
  900 
  901 /*
  902  * Remove a name from a node. This should only be called
  903  * when shutting down and removing the node.
  904  * IF we allow name changing this may be more resurected.
  905  */
  906 void
  907 ng_unname(node_p node)
  908 {
  909 }
  910 
  911 /************************************************************************
  912                         Hook routines
  913  Names are not optional. Hooks are always connected, except for a
  914  brief moment within these routines. On invalidation or during creation
  915  they are connected to the 'dead' hook.
  916 ************************************************************************/
  917 
  918 /*
  919  * Remove a hook reference
  920  */
  921 void
  922 ng_unref_hook(hook_p hook)
  923 {
  924         int v;
  925 
  926         if (hook == &ng_deadhook) {
  927                 return;
  928         }
  929         do {
  930                 v = hook->hk_refs;
  931         } while (! atomic_cmpset_int(&hook->hk_refs, v, v - 1));
  932 
  933         if (v == 1) { /* we were the last */
  934                 if (_NG_HOOK_NODE(hook)) { /* it'll probably be ng_deadnode */
  935                         _NG_NODE_UNREF((_NG_HOOK_NODE(hook)));
  936                         hook->hk_node = NULL;
  937                 }
  938                 NG_FREE_HOOK(hook);
  939         }
  940 }
  941 
  942 /*
  943  * Add an unconnected hook to a node. Only used internally.
  944  * Assumes node is locked. (XXX not yet true )
  945  */
  946 static int
  947 ng_add_hook(node_p node, const char *name, hook_p *hookp)
  948 {
  949         hook_p hook;
  950         int error = 0;
  951 
  952         /* Check that the given name is good */
  953         if (name == NULL) {
  954                 TRAP_ERROR();
  955                 return (EINVAL);
  956         }
  957         if (ng_findhook(node, name) != NULL) {
  958                 TRAP_ERROR();
  959                 return (EEXIST);
  960         }
  961 
  962         /* Allocate the hook and link it up */
  963         NG_ALLOC_HOOK(hook);
  964         if (hook == NULL) {
  965                 TRAP_ERROR();
  966                 return (ENOMEM);
  967         }
  968         hook->hk_refs = 1;              /* add a reference for us to return */
  969         hook->hk_flags = HK_INVALID;
  970         hook->hk_peer = &ng_deadhook;   /* start off this way */
  971         hook->hk_node = node;
  972         NG_NODE_REF(node);              /* each hook counts as a reference */
  973 
  974         /* Set hook name */
  975         strlcpy(NG_HOOK_NAME(hook), name, NG_HOOKSIZ);
  976 
  977         /*
  978          * Check if the node type code has something to say about it
  979          * If it fails, the unref of the hook will also unref the node.
  980          */
  981         if (node->nd_type->newhook != NULL) {
  982                 if ((error = (*node->nd_type->newhook)(node, hook, name))) {
  983                         NG_HOOK_UNREF(hook);    /* this frees the hook */
  984                         return (error);
  985                 }
  986         }
  987         /*
  988          * The 'type' agrees so far, so go ahead and link it in.
  989          * We'll ask again later when we actually connect the hooks.
  990          */
  991         LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
  992         node->nd_numhooks++;
  993         NG_HOOK_REF(hook);      /* one for the node */
  994 
  995         if (hookp)
  996                 *hookp = hook;
  997         return (0);
  998 }
  999 
 1000 /*
 1001  * Find a hook
 1002  *
 1003  * Node types may supply their own optimized routines for finding
 1004  * hooks.  If none is supplied, we just do a linear search.
 1005  * XXX Possibly we should add a reference to the hook?
 1006  */
 1007 hook_p
 1008 ng_findhook(node_p node, const char *name)
 1009 {
 1010         hook_p hook;
 1011 
 1012         if (node->nd_type->findhook != NULL)
 1013                 return (*node->nd_type->findhook)(node, name);
 1014         LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
 1015                 if (NG_HOOK_IS_VALID(hook)
 1016                 && (strcmp(NG_HOOK_NAME(hook), name) == 0))
 1017                         return (hook);
 1018         }
 1019         return (NULL);
 1020 }
 1021 
 1022 /*
 1023  * Destroy a hook
 1024  *
 1025  * As hooks are always attached, this really destroys two hooks.
 1026  * The one given, and the one attached to it. Disconnect the hooks
 1027  * from each other first. We reconnect the peer hook to the 'dead'
 1028  * hook so that it can still exist after we depart. We then
 1029  * send the peer its own destroy message. This ensures that we only
 1030  * interact with the peer's structures when it is locked processing that
 1031  * message. We hold a reference to the peer hook so we are guaranteed that
 1032  * the peer hook and node are still going to exist until
 1033  * we are finished there as the hook holds a ref on the node.
 1034  * We run this same code again on the peer hook, but that time it is already
 1035  * attached to the 'dead' hook.
 1036  *
 1037  * This routine is called at all stages of hook creation
 1038  * on error detection and must be able to handle any such stage.
 1039  */
 1040 void
 1041 ng_destroy_hook(hook_p hook)
 1042 {
 1043         hook_p peer;
 1044         node_p node;
 1045 
 1046         if (hook == &ng_deadhook) {     /* better safe than sorry */
 1047                 printf("ng_destroy_hook called on deadhook\n");
 1048                 return;
 1049         }
 1050 
 1051         /*
 1052          * Protect divorce process with mutex, to avoid races on
 1053          * simultaneous disconnect.
 1054          */
 1055         mtx_lock(&ng_topo_mtx);
 1056 
 1057         hook->hk_flags |= HK_INVALID;
 1058 
 1059         peer = NG_HOOK_PEER(hook);
 1060         node = NG_HOOK_NODE(hook);
 1061 
 1062         if (peer && (peer != &ng_deadhook)) {
 1063                 /*
 1064                  * Set the peer to point to ng_deadhook
 1065                  * from this moment on we are effectively independent it.
 1066                  * send it an rmhook message of it's own.
 1067                  */
 1068                 peer->hk_peer = &ng_deadhook;   /* They no longer know us */
 1069                 hook->hk_peer = &ng_deadhook;   /* Nor us, them */
 1070                 if (NG_HOOK_NODE(peer) == &ng_deadnode) {
 1071                         /*
 1072                          * If it's already divorced from a node,
 1073                          * just free it.
 1074                          */
 1075                         mtx_unlock(&ng_topo_mtx);
 1076                 } else {
 1077                         mtx_unlock(&ng_topo_mtx);
 1078                         ng_rmhook_self(peer);   /* Send it a surprise */
 1079                 }
 1080                 NG_HOOK_UNREF(peer);            /* account for peer link */
 1081                 NG_HOOK_UNREF(hook);            /* account for peer link */
 1082         } else
 1083                 mtx_unlock(&ng_topo_mtx);
 1084 
 1085         mtx_assert(&ng_topo_mtx, MA_NOTOWNED);
 1086 
 1087         /*
 1088          * Remove the hook from the node's list to avoid possible recursion
 1089          * in case the disconnection results in node shutdown.
 1090          */
 1091         if (node == &ng_deadnode) { /* happens if called from ng_con_nodes() */
 1092                 return;
 1093         }
 1094         LIST_REMOVE(hook, hk_hooks);
 1095         node->nd_numhooks--;
 1096         if (node->nd_type->disconnect) {
 1097                 /*
 1098                  * The type handler may elect to destroy the node so don't
 1099                  * trust its existance after this point. (except
 1100                  * that we still hold a reference on it. (which we
 1101                  * inherrited from the hook we are destroying)
 1102                  */
 1103                 (*node->nd_type->disconnect) (hook);
 1104         }
 1105 
 1106         /*
 1107          * Note that because we will point to ng_deadnode, the original node
 1108          * is not decremented automatically so we do that manually.
 1109          */
 1110         _NG_HOOK_NODE(hook) = &ng_deadnode;
 1111         NG_NODE_UNREF(node);    /* We no longer point to it so adjust count */
 1112         NG_HOOK_UNREF(hook);    /* Account for linkage (in list) to node */
 1113 }
 1114 
 1115 /*
 1116  * Take two hooks on a node and merge the connection so that the given node
 1117  * is effectively bypassed.
 1118  */
 1119 int
 1120 ng_bypass(hook_p hook1, hook_p hook2)
 1121 {
 1122         if (hook1->hk_node != hook2->hk_node) {
 1123                 TRAP_ERROR();
 1124                 return (EINVAL);
 1125         }
 1126         hook1->hk_peer->hk_peer = hook2->hk_peer;
 1127         hook2->hk_peer->hk_peer = hook1->hk_peer;
 1128 
 1129         hook1->hk_peer = &ng_deadhook;
 1130         hook2->hk_peer = &ng_deadhook;
 1131 
 1132         NG_HOOK_UNREF(hook1);
 1133         NG_HOOK_UNREF(hook2);
 1134 
 1135         /* XXX If we ever cache methods on hooks update them as well */
 1136         ng_destroy_hook(hook1);
 1137         ng_destroy_hook(hook2);
 1138         return (0);
 1139 }
 1140 
 1141 /*
 1142  * Install a new netgraph type
 1143  */
 1144 int
 1145 ng_newtype(struct ng_type *tp)
 1146 {
 1147         const size_t namelen = strlen(tp->name);
 1148 
 1149         /* Check version and type name fields */
 1150         if ((tp->version != NG_ABI_VERSION)
 1151         || (namelen == 0)
 1152         || (namelen >= NG_TYPESIZ)) {
 1153                 TRAP_ERROR();
 1154                 if (tp->version != NG_ABI_VERSION) {
 1155                         printf("Netgraph: Node type rejected. ABI mismatch. Suggest recompile\n");
 1156                 }
 1157                 return (EINVAL);
 1158         }
 1159 
 1160         /* Check for name collision */
 1161         if (ng_findtype(tp->name) != NULL) {
 1162                 TRAP_ERROR();
 1163                 return (EEXIST);
 1164         }
 1165 
 1166 
 1167         /* Link in new type */
 1168         mtx_lock(&ng_typelist_mtx);
 1169         LIST_INSERT_HEAD(&ng_typelist, tp, types);
 1170         tp->refs = 1;   /* first ref is linked list */
 1171         mtx_unlock(&ng_typelist_mtx);
 1172         return (0);
 1173 }
 1174 
 1175 /*
 1176  * unlink a netgraph type
 1177  * If no examples exist
 1178  */
 1179 int
 1180 ng_rmtype(struct ng_type *tp)
 1181 {
 1182         /* Check for name collision */
 1183         if (tp->refs != 1) {
 1184                 TRAP_ERROR();
 1185                 return (EBUSY);
 1186         }
 1187 
 1188         /* Unlink type */
 1189         mtx_lock(&ng_typelist_mtx);
 1190         LIST_REMOVE(tp, types);
 1191         mtx_unlock(&ng_typelist_mtx);
 1192         return (0);
 1193 }
 1194 
 1195 /*
 1196  * Look for a type of the name given
 1197  */
 1198 struct ng_type *
 1199 ng_findtype(const char *typename)
 1200 {
 1201         struct ng_type *type;
 1202 
 1203         mtx_lock(&ng_typelist_mtx);
 1204         LIST_FOREACH(type, &ng_typelist, types) {
 1205                 if (strcmp(type->name, typename) == 0)
 1206                         break;
 1207         }
 1208         mtx_unlock(&ng_typelist_mtx);
 1209         return (type);
 1210 }
 1211 
 1212 /************************************************************************
 1213                         Composite routines
 1214 ************************************************************************/
 1215 /*
 1216  * Connect two nodes using the specified hooks, using queued functions.
 1217  */
 1218 static void
 1219 ng_con_part3(node_p node, hook_p hook, void *arg1, int arg2)
 1220 {
 1221 
 1222         /*
 1223          * When we run, we know that the node 'node' is locked for us.
 1224          * Our caller has a reference on the hook.
 1225          * Our caller has a reference on the node.
 1226          * (In this case our caller is ng_apply_item() ).
 1227          * The peer hook has a reference on the hook.
 1228          * We are all set up except for the final call to the node, and
 1229          * the clearing of the INVALID flag.
 1230          */
 1231         if (NG_HOOK_NODE(hook) == &ng_deadnode) {
 1232                 /*
 1233                  * The node must have been freed again since we last visited
 1234                  * here. ng_destry_hook() has this effect but nothing else does.
 1235                  * We should just release our references and
 1236                  * free anything we can think of.
 1237                  * Since we know it's been destroyed, and it's our caller
 1238                  * that holds the references, just return.
 1239                  */
 1240                 return ;
 1241         }
 1242         if (hook->hk_node->nd_type->connect) {
 1243                 if ((*hook->hk_node->nd_type->connect) (hook)) {
 1244                         ng_destroy_hook(hook);  /* also zaps peer */
 1245                         printf("failed in ng_con_part3()\n");
 1246                         return ;
 1247                 }
 1248         }
 1249         /*
 1250          *  XXX this is wrong for SMP. Possibly we need
 1251          * to separate out 'create' and 'invalid' flags.
 1252          * should only set flags on hooks we have locked under our node.
 1253          */
 1254         hook->hk_flags &= ~HK_INVALID;
 1255         return ;
 1256 }
 1257 
 1258 static void
 1259 ng_con_part2(node_p node, hook_p hook, void *arg1, int arg2)
 1260 {
 1261         hook_p peer;
 1262 
 1263         /*
 1264          * When we run, we know that the node 'node' is locked for us.
 1265          * Our caller has a reference on the hook.
 1266          * Our caller has a reference on the node.
 1267          * (In this case our caller is ng_apply_item() ).
 1268          * The peer hook has a reference on the hook.
 1269          * our node pointer points to the 'dead' node.
 1270          * First check the hook name is unique.
 1271          * Should not happen because we checked before queueing this.
 1272          */
 1273         if (ng_findhook(node, NG_HOOK_NAME(hook)) != NULL) {
 1274                 TRAP_ERROR();
 1275                 ng_destroy_hook(hook); /* should destroy peer too */
 1276                 printf("failed in ng_con_part2()\n");
 1277                 return ;
 1278         }
 1279         /*
 1280          * Check if the node type code has something to say about it
 1281          * If it fails, the unref of the hook will also unref the attached node,
 1282          * however since that node is 'ng_deadnode' this will do nothing.
 1283          * The peer hook will also be destroyed.
 1284          */
 1285         if (node->nd_type->newhook != NULL) {
 1286                 if ((*node->nd_type->newhook)(node, hook, hook->hk_name)) {
 1287                         ng_destroy_hook(hook); /* should destroy peer too */
 1288                         printf("failed in ng_con_part2()\n");
 1289                         return ;
 1290                 }
 1291         }
 1292 
 1293         /*
 1294          * The 'type' agrees so far, so go ahead and link it in.
 1295          * We'll ask again later when we actually connect the hooks.
 1296          */
 1297         hook->hk_node = node;           /* just overwrite ng_deadnode */
 1298         NG_NODE_REF(node);              /* each hook counts as a reference */
 1299         LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
 1300         node->nd_numhooks++;
 1301         NG_HOOK_REF(hook);      /* one for the node */
 1302         
 1303         /*
 1304          * We now have a symetrical situation, where both hooks have been
 1305          * linked to their nodes, the newhook methods have been called
 1306          * And the references are all correct. The hooks are still marked
 1307          * as invalid, as we have not called the 'connect' methods
 1308          * yet.
 1309          * We can call the local one immediatly as we have the
 1310          * node locked, but we need to queue the remote one.
 1311          */
 1312         if (hook->hk_node->nd_type->connect) {
 1313                 if ((*hook->hk_node->nd_type->connect) (hook)) {
 1314                         ng_destroy_hook(hook);  /* also zaps peer */
 1315                         printf("failed in ng_con_part2(A)\n");
 1316                         return ;
 1317                 }
 1318         }
 1319 
 1320         /*
 1321          * Acquire topo mutex to avoid race with ng_destroy_hook().
 1322          */
 1323         mtx_lock(&ng_topo_mtx);
 1324         peer = hook->hk_peer;
 1325         if (peer == &ng_deadhook) {
 1326                 mtx_unlock(&ng_topo_mtx);
 1327                 printf("failed in ng_con_part2(B)\n");
 1328                 ng_destroy_hook(hook);
 1329                 return ;
 1330         }
 1331         mtx_unlock(&ng_topo_mtx);
 1332 
 1333         if (ng_send_fn(peer->hk_node, peer, &ng_con_part3, arg1, arg2)) {
 1334                 printf("failed in ng_con_part2(C)\n");
 1335                 ng_destroy_hook(hook);  /* also zaps peer */
 1336                 return ;
 1337         }
 1338         hook->hk_flags &= ~HK_INVALID; /* need both to be able to work */
 1339         return ;
 1340 }
 1341 
 1342 /*
 1343  * Connect this node with another node. We assume that this node is
 1344  * currently locked, as we are only called from an NGM_CONNECT message.
 1345  */
 1346 static int
 1347 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
 1348 {
 1349         int     error;
 1350         hook_p  hook;
 1351         hook_p  hook2;
 1352 
 1353         if (ng_findhook(node2, name2) != NULL) {
 1354                 return(EEXIST);
 1355         }
 1356         if ((error = ng_add_hook(node, name, &hook)))  /* gives us a ref */
 1357                 return (error);
 1358         /* Allocate the other hook and link it up */
 1359         NG_ALLOC_HOOK(hook2);
 1360         if (hook2 == NULL) {
 1361                 TRAP_ERROR();
 1362                 ng_destroy_hook(hook);  /* XXX check ref counts so far */
 1363                 NG_HOOK_UNREF(hook);    /* including our ref */
 1364                 return (ENOMEM);
 1365         }
 1366         hook2->hk_refs = 1;             /* start with a reference for us. */
 1367         hook2->hk_flags = HK_INVALID;
 1368         hook2->hk_peer = hook;          /* Link the two together */
 1369         hook->hk_peer = hook2;  
 1370         NG_HOOK_REF(hook);              /* Add a ref for the peer to each*/
 1371         NG_HOOK_REF(hook2);
 1372         hook2->hk_node = &ng_deadnode;
 1373         strlcpy(NG_HOOK_NAME(hook2), name2, NG_HOOKSIZ);
 1374 
 1375         /*
 1376          * Queue the function above.
 1377          * Procesing continues in that function in the lock context of
 1378          * the other node.
 1379          */
 1380         ng_send_fn(node2, hook2, &ng_con_part2, NULL, 0);
 1381 
 1382         NG_HOOK_UNREF(hook);            /* Let each hook go if it wants to */
 1383         NG_HOOK_UNREF(hook2);
 1384         return (0);
 1385 }
 1386 
 1387 /*
 1388  * Make a peer and connect.
 1389  * We assume that the local node is locked.
 1390  * The new node probably doesn't need a lock until
 1391  * it has a hook, because it cannot really have any work until then,
 1392  * but we should think about it a bit more.
 1393  *
 1394  * The problem may come if the other node also fires up
 1395  * some hardware or a timer or some other source of activation,
 1396  * also it may already get a command msg via it's ID.
 1397  *
 1398  * We could use the same method as ng_con_nodes() but we'd have
 1399  * to add ability to remove the node when failing. (Not hard, just
 1400  * make arg1 point to the node to remove).
 1401  * Unless of course we just ignore failure to connect and leave
 1402  * an unconnected node?
 1403  */
 1404 static int
 1405 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
 1406 {
 1407         node_p  node2;
 1408         hook_p  hook1, hook2;
 1409         int     error;
 1410 
 1411         if ((error = ng_make_node(type, &node2))) {
 1412                 return (error);
 1413         }
 1414 
 1415         if ((error = ng_add_hook(node, name, &hook1))) { /* gives us a ref */
 1416                 ng_rmnode(node2, NULL, NULL, 0);
 1417                 return (error);
 1418         }
 1419 
 1420         if ((error = ng_add_hook(node2, name2, &hook2))) {
 1421                 ng_rmnode(node2, NULL, NULL, 0);
 1422                 ng_destroy_hook(hook1);
 1423                 NG_HOOK_UNREF(hook1);
 1424                 return (error);
 1425         }
 1426 
 1427         /*
 1428          * Actually link the two hooks together.
 1429          */
 1430         hook1->hk_peer = hook2;
 1431         hook2->hk_peer = hook1;
 1432 
 1433         /* Each hook is referenced by the other */
 1434         NG_HOOK_REF(hook1);
 1435         NG_HOOK_REF(hook2);
 1436 
 1437         /* Give each node the opportunity to veto the pending connection */
 1438         if (hook1->hk_node->nd_type->connect) {
 1439                 error = (*hook1->hk_node->nd_type->connect) (hook1);
 1440         }
 1441 
 1442         if ((error == 0) && hook2->hk_node->nd_type->connect) {
 1443                 error = (*hook2->hk_node->nd_type->connect) (hook2);
 1444 
 1445         }
 1446 
 1447         /*
 1448          * drop the references we were holding on the two hooks.
 1449          */
 1450         if (error) {
 1451                 ng_destroy_hook(hook2); /* also zaps hook1 */
 1452                 ng_rmnode(node2, NULL, NULL, 0);
 1453         } else {
 1454                 /* As a last act, allow the hooks to be used */
 1455                 hook1->hk_flags &= ~HK_INVALID;
 1456                 hook2->hk_flags &= ~HK_INVALID;
 1457         }
 1458         NG_HOOK_UNREF(hook1);
 1459         NG_HOOK_UNREF(hook2);
 1460         return (error);
 1461 }
 1462 
 1463 /************************************************************************
 1464                 Utility routines to send self messages
 1465 ************************************************************************/
 1466         
 1467 /* Shut this node down as soon as everyone is clear of it */
 1468 /* Should add arg "immediatly" to jump the queue */
 1469 int
 1470 ng_rmnode_self(node_p node)
 1471 {
 1472         int             error;
 1473 
 1474         if (node == &ng_deadnode)
 1475                 return (0);
 1476         node->nd_flags |= NGF_INVALID;
 1477         if (node->nd_flags & NGF_CLOSING)
 1478                 return (0);
 1479 
 1480         error = ng_send_fn(node, NULL, &ng_rmnode, NULL, 0);
 1481         return (error);
 1482 }
 1483 
 1484 static void
 1485 ng_rmhook_part2(node_p node, hook_p hook, void *arg1, int arg2)
 1486 {
 1487         ng_destroy_hook(hook);
 1488         return ;
 1489 }
 1490 
 1491 int
 1492 ng_rmhook_self(hook_p hook)
 1493 {
 1494         int             error;
 1495         node_p node = NG_HOOK_NODE(hook);
 1496 
 1497         if (node == &ng_deadnode)
 1498                 return (0);
 1499 
 1500         error = ng_send_fn(node, hook, &ng_rmhook_part2, NULL, 0);
 1501         return (error);
 1502 }
 1503 
 1504 /***********************************************************************
 1505  * Parse and verify a string of the form:  <NODE:><PATH>
 1506  *
 1507  * Such a string can refer to a specific node or a specific hook
 1508  * on a specific node, depending on how you look at it. In the
 1509  * latter case, the PATH component must not end in a dot.
 1510  *
 1511  * Both <NODE:> and <PATH> are optional. The <PATH> is a string
 1512  * of hook names separated by dots. This breaks out the original
 1513  * string, setting *nodep to "NODE" (or NULL if none) and *pathp
 1514  * to "PATH" (or NULL if degenerate). Also, *hookp will point to
 1515  * the final hook component of <PATH>, if any, otherwise NULL.
 1516  *
 1517  * This returns -1 if the path is malformed. The char ** are optional.
 1518  ***********************************************************************/
 1519 int
 1520 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
 1521 {
 1522         char    *node, *path, *hook;
 1523         int     k;
 1524 
 1525         /*
 1526          * Extract absolute NODE, if any
 1527          */
 1528         for (path = addr; *path && *path != ':'; path++);
 1529         if (*path) {
 1530                 node = addr;    /* Here's the NODE */
 1531                 *path++ = '\0'; /* Here's the PATH */
 1532 
 1533                 /* Node name must not be empty */
 1534                 if (!*node)
 1535                         return -1;
 1536 
 1537                 /* A name of "." is OK; otherwise '.' not allowed */
 1538                 if (strcmp(node, ".") != 0) {
 1539                         for (k = 0; node[k]; k++)
 1540                                 if (node[k] == '.')
 1541                                         return -1;
 1542                 }
 1543         } else {
 1544                 node = NULL;    /* No absolute NODE */
 1545                 path = addr;    /* Here's the PATH */
 1546         }
 1547 
 1548         /* Snoop for illegal characters in PATH */
 1549         for (k = 0; path[k]; k++)
 1550                 if (path[k] == ':')
 1551                         return -1;
 1552 
 1553         /* Check for no repeated dots in PATH */
 1554         for (k = 0; path[k]; k++)
 1555                 if (path[k] == '.' && path[k + 1] == '.')
 1556                         return -1;
 1557 
 1558         /* Remove extra (degenerate) dots from beginning or end of PATH */
 1559         if (path[0] == '.')
 1560                 path++;
 1561         if (*path && path[strlen(path) - 1] == '.')
 1562                 path[strlen(path) - 1] = 0;
 1563 
 1564         /* If PATH has a dot, then we're not talking about a hook */
 1565         if (*path) {
 1566                 for (hook = path, k = 0; path[k]; k++)
 1567                         if (path[k] == '.') {
 1568                                 hook = NULL;
 1569                                 break;
 1570                         }
 1571         } else
 1572                 path = hook = NULL;
 1573 
 1574         /* Done */
 1575         if (nodep)
 1576                 *nodep = node;
 1577         if (pathp)
 1578                 *pathp = path;
 1579         if (hookp)
 1580                 *hookp = hook;
 1581         return (0);
 1582 }
 1583 
 1584 /*
 1585  * Given a path, which may be absolute or relative, and a starting node,
 1586  * return the destination node.
 1587  */
 1588 int
 1589 ng_path2noderef(node_p here, const char *address,
 1590                                 node_p *destp, hook_p *lasthook)
 1591 {
 1592         char    fullpath[NG_PATHSIZ];
 1593         char   *nodename, *path, pbuf[2];
 1594         node_p  node, oldnode;
 1595         char   *cp;
 1596         hook_p hook = NULL;
 1597 
 1598         /* Initialize */
 1599         if (destp == NULL) {
 1600                 TRAP_ERROR();
 1601                 return EINVAL;
 1602         }
 1603         *destp = NULL;
 1604 
 1605         /* Make a writable copy of address for ng_path_parse() */
 1606         strncpy(fullpath, address, sizeof(fullpath) - 1);
 1607         fullpath[sizeof(fullpath) - 1] = '\0';
 1608 
 1609         /* Parse out node and sequence of hooks */
 1610         if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
 1611                 TRAP_ERROR();
 1612                 return EINVAL;
 1613         }
 1614         if (path == NULL) {
 1615                 pbuf[0] = '.';  /* Needs to be writable */
 1616                 pbuf[1] = '\0';
 1617                 path = pbuf;
 1618         }
 1619 
 1620         /*
 1621          * For an absolute address, jump to the starting node.
 1622          * Note that this holds a reference on the node for us.
 1623          * Don't forget to drop the reference if we don't need it.
 1624          */
 1625         if (nodename) {
 1626                 node = ng_name2noderef(here, nodename);
 1627                 if (node == NULL) {
 1628                         TRAP_ERROR();
 1629                         return (ENOENT);
 1630                 }
 1631         } else {
 1632                 if (here == NULL) {
 1633                         TRAP_ERROR();
 1634                         return (EINVAL);
 1635                 }
 1636                 node = here;
 1637                 NG_NODE_REF(node);
 1638         }
 1639 
 1640         /*
 1641          * Now follow the sequence of hooks
 1642          * XXX
 1643          * We actually cannot guarantee that the sequence
 1644          * is not being demolished as we crawl along it
 1645          * without extra-ordinary locking etc.
 1646          * So this is a bit dodgy to say the least.
 1647          * We can probably hold up some things by holding
 1648          * the nodelist mutex for the time of this
 1649          * crawl if we wanted.. At least that way we wouldn't have to
 1650          * worry about the nodes dissappearing, but the hooks would still
 1651          * be a problem.
 1652          */
 1653         for (cp = path; node != NULL && *cp != '\0'; ) {
 1654                 char *segment;
 1655 
 1656                 /*
 1657                  * Break out the next path segment. Replace the dot we just
 1658                  * found with a NUL; "cp" points to the next segment (or the
 1659                  * NUL at the end).
 1660                  */
 1661                 for (segment = cp; *cp != '\0'; cp++) {
 1662                         if (*cp == '.') {
 1663                                 *cp++ = '\0';
 1664                                 break;
 1665                         }
 1666                 }
 1667 
 1668                 /* Empty segment */
 1669                 if (*segment == '\0')
 1670                         continue;
 1671 
 1672                 /* We have a segment, so look for a hook by that name */
 1673                 hook = ng_findhook(node, segment);
 1674 
 1675                 /* Can't get there from here... */
 1676                 if (hook == NULL
 1677                     || NG_HOOK_PEER(hook) == NULL
 1678                     || NG_HOOK_NOT_VALID(hook)
 1679                     || NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))) {
 1680                         TRAP_ERROR();
 1681                         NG_NODE_UNREF(node);
 1682 #if 0
 1683                         printf("hooknotvalid %s %s %d %d %d %d ",
 1684                                         path,
 1685                                         segment,
 1686                                         hook == NULL,
 1687                                         NG_HOOK_PEER(hook) == NULL,
 1688                                         NG_HOOK_NOT_VALID(hook),
 1689                                         NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook)));
 1690 #endif
 1691                         return (ENOENT);
 1692                 }
 1693 
 1694                 /*
 1695                  * Hop on over to the next node
 1696                  * XXX
 1697                  * Big race conditions here as hooks and nodes go away
 1698                  * *** Idea.. store an ng_ID_t in each hook and use that
 1699                  * instead of the direct hook in this crawl?
 1700                  */
 1701                 oldnode = node;
 1702                 if ((node = NG_PEER_NODE(hook)))
 1703                         NG_NODE_REF(node);      /* XXX RACE */
 1704                 NG_NODE_UNREF(oldnode); /* XXX another race */
 1705                 if (NG_NODE_NOT_VALID(node)) {
 1706                         NG_NODE_UNREF(node);    /* XXX more races */
 1707                         node = NULL;
 1708                 }
 1709         }
 1710 
 1711         /* If node somehow missing, fail here (probably this is not needed) */
 1712         if (node == NULL) {
 1713                 TRAP_ERROR();
 1714                 return (ENXIO);
 1715         }
 1716 
 1717         /* Done */
 1718         *destp = node;
 1719         if (lasthook != NULL)
 1720                 *lasthook = (hook ? NG_HOOK_PEER(hook) : NULL);
 1721         return (0);
 1722 }
 1723 
 1724 /***************************************************************\
 1725 * Input queue handling.
 1726 * All activities are submitted to the node via the input queue
 1727 * which implements a multiple-reader/single-writer gate.
 1728 * Items which cannot be handled immeditly are queued.
 1729 *
 1730 * read-write queue locking inline functions                     *
 1731 \***************************************************************/
 1732 
 1733 static __inline item_p ng_dequeue(struct ng_queue * ngq, int *rw);
 1734 static __inline item_p ng_acquire_read(struct ng_queue * ngq,
 1735                                         item_p  item);
 1736 static __inline item_p ng_acquire_write(struct ng_queue * ngq,
 1737                                         item_p  item);
 1738 static __inline void    ng_leave_read(struct ng_queue * ngq);
 1739 static __inline void    ng_leave_write(struct ng_queue * ngq);
 1740 static __inline void    ng_queue_rw(struct ng_queue * ngq,
 1741                                         item_p  item, int rw);
 1742 
 1743 /*
 1744  * Definition of the bits fields in the ng_queue flag word.
 1745  * Defined here rather than in netgraph.h because no-one should fiddle
 1746  * with them.
 1747  *
 1748  * The ordering here may be important! don't shuffle these.
 1749  */
 1750 /*-
 1751  Safety Barrier--------+ (adjustable to suit taste) (not used yet)
 1752                        |
 1753                        V
 1754 +-------+-------+-------+-------+-------+-------+-------+-------+
 1755   | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
 1756   | |A|c|t|i|v|e| |R|e|a|d|e|r| |C|o|u|n|t| | | | | | | | | |P|A|
 1757   | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |O|W|
 1758 +-------+-------+-------+-------+-------+-------+-------+-------+
 1759   \___________________________ ____________________________/ | |
 1760                             V                                | |
 1761                   [active reader count]                      | |
 1762                                                              | |
 1763             Operation Pending -------------------------------+ |
 1764                                                                |
 1765           Active Writer ---------------------------------------+
 1766 
 1767 
 1768 */
 1769 #define WRITER_ACTIVE   0x00000001
 1770 #define OP_PENDING      0x00000002
 1771 #define READER_INCREMENT 0x00000004
 1772 #define READER_MASK     0xfffffffc      /* Not valid if WRITER_ACTIVE is set */
 1773 #define SAFETY_BARRIER  0x00100000      /* 128K items queued should be enough */
 1774 
 1775 /* Defines of more elaborate states on the queue */
 1776 /* Mask of bits a new read cares about */
 1777 #define NGQ_RMASK       (WRITER_ACTIVE|OP_PENDING)
 1778 
 1779 /* Mask of bits a new write cares about */
 1780 #define NGQ_WMASK       (NGQ_RMASK|READER_MASK)
 1781 
 1782 /* Test to decide if there is something on the queue. */
 1783 #define QUEUE_ACTIVE(QP) ((QP)->q_flags & OP_PENDING)
 1784 
 1785 /* How to decide what the next queued item is. */
 1786 #define HEAD_IS_READER(QP)  NGI_QUEUED_READER((QP)->queue)
 1787 #define HEAD_IS_WRITER(QP)  NGI_QUEUED_WRITER((QP)->queue) /* notused */
 1788 
 1789 /* Read the status to decide if the next item on the queue can now run. */
 1790 #define QUEUED_READER_CAN_PROCEED(QP)                   \
 1791                 (((QP)->q_flags & (NGQ_RMASK & ~OP_PENDING)) == 0)
 1792 #define QUEUED_WRITER_CAN_PROCEED(QP)                   \
 1793                 (((QP)->q_flags & (NGQ_WMASK & ~OP_PENDING)) == 0)
 1794 
 1795 /* Is there a chance of getting ANY work off the queue? */
 1796 #define NEXT_QUEUED_ITEM_CAN_PROCEED(QP)                                \
 1797         (QUEUE_ACTIVE(QP) &&                                            \
 1798         ((HEAD_IS_READER(QP)) ? QUEUED_READER_CAN_PROCEED(QP) :         \
 1799                                 QUEUED_WRITER_CAN_PROCEED(QP)))
 1800 
 1801 
 1802 #define NGQRW_R 0
 1803 #define NGQRW_W 1
 1804 
 1805 /*
 1806  * Taking into account the current state of the queue and node, possibly take
 1807  * the next entry off the queue and return it. Return NULL if there was
 1808  * nothing we could return, either because there really was nothing there, or
 1809  * because the node was in a state where it cannot yet process the next item
 1810  * on the queue.
 1811  *
 1812  * This MUST MUST MUST be called with the mutex held.
 1813  */
 1814 static __inline item_p
 1815 ng_dequeue(struct ng_queue *ngq, int *rw)
 1816 {
 1817         item_p item;
 1818         u_int           add_arg;
 1819 
 1820         mtx_assert(&ngq->q_mtx, MA_OWNED);
 1821         /*
 1822          * If there is nothing queued, then just return.
 1823          * No point in continuing.
 1824          * XXXGL: assert this?
 1825          */
 1826         if (!QUEUE_ACTIVE(ngq)) {
 1827                 CTR4(KTR_NET, "%20s: node [%x] (%p) queue empty; "
 1828                     "queue flags 0x%lx", __func__,
 1829                     ngq->q_node->nd_ID, ngq->q_node, ngq->q_flags);
 1830                 return (NULL);
 1831         }
 1832 
 1833         /*
 1834          * From here, we can assume there is a head item.
 1835          * We need to find out what it is and if it can be dequeued, given
 1836          * the current state of the node.
 1837          */
 1838         if (HEAD_IS_READER(ngq)) {
 1839                 if (!QUEUED_READER_CAN_PROCEED(ngq)) {
 1840                         /*
 1841                          * It's a reader but we can't use it.
 1842                          * We are stalled so make sure we don't
 1843                          * get called again until something changes.
 1844                          */
 1845                         ng_worklist_remove(ngq->q_node);
 1846                         CTR4(KTR_NET, "%20s: node [%x] (%p) queued reader "
 1847                             "can't proceed; queue flags 0x%lx", __func__,
 1848                             ngq->q_node->nd_ID, ngq->q_node, ngq->q_flags);
 1849                         return (NULL);
 1850                 }
 1851                 /*
 1852                  * Head of queue is a reader and we have no write active.
 1853                  * We don't care how many readers are already active.
 1854                  * Add the correct increment for the reader count.
 1855                  */
 1856                 add_arg = READER_INCREMENT;
 1857                 *rw = NGQRW_R;
 1858         } else if (QUEUED_WRITER_CAN_PROCEED(ngq)) {
 1859                 /*
 1860                  * There is a pending write, no readers and no active writer.
 1861                  * This means we can go ahead with the pending writer. Note
 1862                  * the fact that we now have a writer, ready for when we take
 1863                  * it off the queue.
 1864                  *
 1865                  * We don't need to worry about a possible collision with the
 1866                  * fasttrack reader.
 1867                  *
 1868                  * The fasttrack thread may take a long time to discover that we
 1869                  * are running so we would have an inconsistent state in the
 1870                  * flags for a while. Since we ignore the reader count
 1871                  * entirely when the WRITER_ACTIVE flag is set, this should
 1872                  * not matter (in fact it is defined that way). If it tests
 1873                  * the flag before this operation, the OP_PENDING flag
 1874                  * will make it fail, and if it tests it later, the
 1875                  * WRITER_ACTIVE flag will do the same. If it is SO slow that
 1876                  * we have actually completed the operation, and neither flag
 1877                  * is set by the time that it tests the flags, then it is
 1878                  * actually ok for it to continue. If it completes and we've
 1879                  * finished and the read pending is set it still fails.
 1880                  *
 1881                  * So we can just ignore it,  as long as we can ensure that the
 1882                  * transition from WRITE_PENDING state to the WRITER_ACTIVE
 1883                  * state is atomic.
 1884                  *
 1885                  * After failing, first it will be held back by the mutex, then
 1886                  * when it can proceed, it will queue its request, then it
 1887                  * would arrive at this function. Usually it will have to
 1888                  * leave empty handed because the ACTIVE WRITER bit will be
 1889                  * set.
 1890                  *
 1891                  * Adjust the flags for the new active writer.
 1892                  */
 1893                 add_arg = WRITER_ACTIVE;
 1894                 *rw = NGQRW_W;
 1895                 /*
 1896                  * We want to write "active writer, no readers " Now go make
 1897                  * it true. In fact there may be a number in the readers
 1898                  * count but we know it is not true and will be fixed soon.
 1899                  * We will fix the flags for the next pending entry in a
 1900                  * moment.
 1901                  */
 1902         } else {
 1903                 /*
 1904                  * We can't dequeue anything.. return and say so. Probably we
 1905                  * have a write pending and the readers count is non zero. If
 1906                  * we got here because a reader hit us just at the wrong
 1907                  * moment with the fasttrack code, and put us in a strange
 1908                  * state, then it will be coming through in just a moment,
 1909                  * (just as soon as we release the mutex) and keep things
 1910                  * moving.
 1911                  * Make sure we remove ourselves from the work queue. It
 1912                  * would be a waste of effort to do all this again.
 1913                  */
 1914                 ng_worklist_remove(ngq->q_node);
 1915                 CTR4(KTR_NET, "%20s: node [%x] (%p) can't dequeue anything; "
 1916                     "queue flags 0x%lx", __func__,
 1917                     ngq->q_node->nd_ID, ngq->q_node, ngq->q_flags);
 1918                 return (NULL);
 1919         }
 1920 
 1921         /*
 1922          * Now we dequeue the request (whatever it may be) and correct the
 1923          * pending flags and the next and last pointers.
 1924          */
 1925         item = ngq->queue;
 1926         ngq->queue = item->el_next;
 1927         CTR6(KTR_NET, "%20s: node [%x] (%p) dequeued item %p with flags 0x%lx; "
 1928             "queue flags 0x%lx", __func__,
 1929             ngq->q_node->nd_ID,ngq->q_node, item, item->el_flags, ngq->q_flags);
 1930         if (ngq->last == &(item->el_next)) {
 1931                 /*
 1932                  * that was the last entry in the queue so set the 'last
 1933                  * pointer up correctly and make sure the pending flag is
 1934                  * clear.
 1935                  */
 1936                 add_arg += -OP_PENDING;
 1937                 ngq->last = &(ngq->queue);
 1938                 /*
 1939                  * Whatever flag was set will be cleared and
 1940                  * the new acive field will be set by the add as well,
 1941                  * so we don't need to change add_arg.
 1942                  * But we know we don't need to be on the work list.
 1943                  */
 1944                 atomic_add_long(&ngq->q_flags, add_arg);
 1945                 ng_worklist_remove(ngq->q_node);
 1946         } else {
 1947                 /*
 1948                  * Since there is still something on the queue
 1949                  * we don't need to change the PENDING flag.
 1950                  */
 1951                 atomic_add_long(&ngq->q_flags, add_arg);
 1952                 /*
 1953                  * If we see more doable work, make sure we are
 1954                  * on the work queue.
 1955                  */
 1956                 if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq)) {
 1957                         ng_setisr(ngq->q_node);
 1958                 }
 1959         }
 1960         CTR6(KTR_NET, "%20s: node [%x] (%p) returning item %p as %s; "
 1961             "queue flags 0x%lx", __func__,
 1962             ngq->q_node->nd_ID, ngq->q_node, item, *rw ? "WRITER" : "READER" ,
 1963             ngq->q_flags);
 1964         return (item);
 1965 }
 1966 
 1967 /*
 1968  * Queue a packet to be picked up by someone else.
 1969  * We really don't care who, but we can't or don't want to hang around
 1970  * to process it ourselves. We are probably an interrupt routine..
 1971  * If the queue could be run, flag the netisr handler to start.
 1972  */
 1973 static __inline void
 1974 ng_queue_rw(struct ng_queue * ngq, item_p  item, int rw)
 1975 {
 1976         mtx_assert(&ngq->q_mtx, MA_OWNED);
 1977 
 1978         if (rw == NGQRW_W)
 1979                 NGI_SET_WRITER(item);
 1980         else
 1981                 NGI_SET_READER(item);
 1982         item->el_next = NULL;   /* maybe not needed */
 1983         *ngq->last = item;
 1984         CTR5(KTR_NET, "%20s: node [%x] (%p) queued item %p as %s", __func__,
 1985             ngq->q_node->nd_ID, ngq->q_node, item, rw ? "WRITER" : "READER" );
 1986         /*
 1987          * If it was the first item in the queue then we need to
 1988          * set the last pointer and the type flags.
 1989          */
 1990         if (ngq->last == &(ngq->queue)) {
 1991                 atomic_add_long(&ngq->q_flags, OP_PENDING);
 1992                 CTR3(KTR_NET, "%20s: node [%x] (%p) set OP_PENDING", __func__,
 1993                     ngq->q_node->nd_ID, ngq->q_node);
 1994         }
 1995 
 1996         ngq->last = &(item->el_next);
 1997         /*
 1998          * We can take the worklist lock with the node locked
 1999          * BUT NOT THE REVERSE!
 2000          */
 2001         if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
 2002                 ng_setisr(ngq->q_node);
 2003 }
 2004 
 2005 
 2006 /*
 2007  * This function 'cheats' in that it first tries to 'grab' the use of the
 2008  * node, without going through the mutex. We can do this becasue of the
 2009  * semantics of the lock. The semantics include a clause that says that the
 2010  * value of the readers count is invalid if the WRITER_ACTIVE flag is set. It
 2011  * also says that the WRITER_ACTIVE flag cannot be set if the readers count
 2012  * is not zero. Note that this talks about what is valid to SET the
 2013  * WRITER_ACTIVE flag, because from the moment it is set, the value if the
 2014  * reader count is immaterial, and not valid. The two 'pending' flags have a
 2015  * similar effect, in that If they are orthogonal to the two active fields in
 2016  * how they are set, but if either is set, the attempted 'grab' need to be
 2017  * backed out because there is earlier work, and we maintain ordering in the
 2018  * queue. The result of this is that the reader request can try obtain use of
 2019  * the node with only a single atomic addition, and without any of the mutex
 2020  * overhead. If this fails the operation degenerates to the same as for other
 2021  * cases.
 2022  *
 2023  */
 2024 static __inline item_p
 2025 ng_acquire_read(struct ng_queue *ngq, item_p item)
 2026 {
 2027         KASSERT(ngq != &ng_deadnode.nd_input_queue,
 2028             ("%s: working on deadnode", __func__));
 2029 
 2030         /* ######### Hack alert ######### */
 2031         atomic_add_long(&ngq->q_flags, READER_INCREMENT);
 2032         if ((ngq->q_flags & NGQ_RMASK) == 0) {
 2033                 /* Successfully grabbed node */
 2034                 CTR4(KTR_NET, "%20s: node [%x] (%p) fast acquired item %p",
 2035                     __func__, ngq->q_node->nd_ID, ngq->q_node, item);
 2036                 return (item);
 2037         }
 2038         /* undo the damage if we didn't succeed */
 2039         atomic_subtract_long(&ngq->q_flags, READER_INCREMENT);
 2040 
 2041         /* ######### End Hack alert ######### */
 2042         mtx_lock_spin((&ngq->q_mtx));
 2043         /*
 2044          * Try again. Another processor (or interrupt for that matter) may
 2045          * have removed the last queued item that was stopping us from
 2046          * running, between the previous test, and the moment that we took
 2047          * the mutex. (Or maybe a writer completed.)
 2048          * Even if another fast-track reader hits during this period
 2049          * we don't care as multiple readers is OK.
 2050          */
 2051         if ((ngq->q_flags & NGQ_RMASK) == 0) {
 2052                 atomic_add_long(&ngq->q_flags, READER_INCREMENT);
 2053                 mtx_unlock_spin((&ngq->q_mtx));
 2054                 CTR4(KTR_NET, "%20s: node [%x] (%p) slow acquired item %p",
 2055                     __func__, ngq->q_node->nd_ID, ngq->q_node, item);
 2056                 return (item);
 2057         }
 2058 
 2059         /*
 2060          * and queue the request for later.
 2061          */
 2062         ng_queue_rw(ngq, item, NGQRW_R);
 2063         mtx_unlock_spin(&(ngq->q_mtx));
 2064 
 2065         return (NULL);
 2066 }
 2067 
 2068 static __inline item_p
 2069 ng_acquire_write(struct ng_queue *ngq, item_p item)
 2070 {
 2071         KASSERT(ngq != &ng_deadnode.nd_input_queue,
 2072             ("%s: working on deadnode", __func__));
 2073 
 2074 restart:
 2075         mtx_lock_spin(&(ngq->q_mtx));
 2076         /*
 2077          * If there are no readers, no writer, and no pending packets, then
 2078          * we can just go ahead. In all other situations we need to queue the
 2079          * request
 2080          */
 2081         if ((ngq->q_flags & NGQ_WMASK) == 0) {
 2082                 /* collision could happen *HERE* */
 2083                 atomic_add_long(&ngq->q_flags, WRITER_ACTIVE);
 2084                 mtx_unlock_spin((&ngq->q_mtx));
 2085                 if (ngq->q_flags & READER_MASK) {
 2086                         /* Collision with fast-track reader */
 2087                         atomic_subtract_long(&ngq->q_flags, WRITER_ACTIVE);
 2088                         goto restart;
 2089                 }
 2090                 CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
 2091                     __func__, ngq->q_node->nd_ID, ngq->q_node, item);
 2092                 return (item);
 2093         }
 2094 
 2095         /*
 2096          * and queue the request for later.
 2097          */
 2098         ng_queue_rw(ngq, item, NGQRW_W);
 2099         mtx_unlock_spin(&(ngq->q_mtx));
 2100 
 2101         return (NULL);
 2102 }
 2103 
 2104 static __inline void
 2105 ng_leave_read(struct ng_queue *ngq)
 2106 {
 2107         atomic_subtract_long(&ngq->q_flags, READER_INCREMENT);
 2108 }
 2109 
 2110 static __inline void
 2111 ng_leave_write(struct ng_queue *ngq)
 2112 {
 2113         atomic_subtract_long(&ngq->q_flags, WRITER_ACTIVE);
 2114 }
 2115 
 2116 static void
 2117 ng_flush_input_queue(struct ng_queue * ngq)
 2118 {
 2119         item_p item;
 2120 
 2121         mtx_lock_spin(&ngq->q_mtx);
 2122         while (ngq->queue) {
 2123                 item = ngq->queue;
 2124                 ngq->queue = item->el_next;
 2125                 if (ngq->last == &(item->el_next)) {
 2126                         ngq->last = &(ngq->queue);
 2127                         atomic_add_long(&ngq->q_flags, -OP_PENDING);
 2128                 }
 2129                 mtx_unlock_spin(&ngq->q_mtx);
 2130                 /* If the item is supplying a callback, call it with an error */
 2131                 if (item->apply != NULL) {
 2132                         (item->apply)(item->context, ENOENT);
 2133                         item->apply = NULL;
 2134                 }
 2135                 NG_FREE_ITEM(item);
 2136                 mtx_lock_spin(&ngq->q_mtx);
 2137         }
 2138         /*
 2139          * Take us off the work queue if we are there.
 2140          * We definatly have no work to be done.
 2141          */
 2142         ng_worklist_remove(ngq->q_node);
 2143         mtx_unlock_spin(&ngq->q_mtx);
 2144 }
 2145 
 2146 /***********************************************************************
 2147 * Externally visible method for sending or queueing messages or data.
 2148 ***********************************************************************/
 2149 
 2150 /*
 2151  * The module code should have filled out the item correctly by this stage:
 2152  * Common:
 2153  *    reference to destination node.
 2154  *    Reference to destination rcv hook if relevant.
 2155  * Data:
 2156  *    pointer to mbuf
 2157  * Control_Message:
 2158  *    pointer to msg.
 2159  *    ID of original sender node. (return address)
 2160  * Function:
 2161  *    Function pointer
 2162  *    void * argument
 2163  *    integer argument
 2164  *
 2165  * The nodes have several routines and macros to help with this task:
 2166  */
 2167 
 2168 int
 2169 ng_snd_item(item_p item, int flags)
 2170 {
 2171         hook_p hook = NGI_HOOK(item);
 2172         node_p node = NGI_NODE(item);
 2173         int queue, rw;
 2174         struct ng_queue * ngq = &node->nd_input_queue;
 2175         int error = 0;
 2176 
 2177 #ifdef  NETGRAPH_DEBUG
 2178         _ngi_check(item, __FILE__, __LINE__);
 2179 #endif
 2180 
 2181         queue = (flags & NG_QUEUE) ? 1 : 0;
 2182 
 2183         if (item == NULL) {
 2184                 TRAP_ERROR();
 2185                 return (EINVAL);        /* failed to get queue element */
 2186         }
 2187         if (node == NULL) {
 2188                 NG_FREE_ITEM(item);
 2189                 TRAP_ERROR();
 2190                 return (EINVAL);        /* No address */
 2191         }
 2192         switch(item->el_flags & NGQF_TYPE) {
 2193         case NGQF_DATA:
 2194                 /*
 2195                  * DATA MESSAGE
 2196                  * Delivered to a node via a non-optional hook.
 2197                  * Both should be present in the item even though
 2198                  * the node is derivable from the hook.
 2199                  * References are held on both by the item.
 2200                  */
 2201 
 2202                 /* Protect nodes from sending NULL pointers
 2203                  * to each other
 2204                  */
 2205                 if (NGI_M(item) == NULL)
 2206                         return (EINVAL);
 2207 
 2208                 CHECK_DATA_MBUF(NGI_M(item));
 2209                 if (hook == NULL) {
 2210                         NG_FREE_ITEM(item);
 2211                         TRAP_ERROR();
 2212                         return(EINVAL);
 2213                 }
 2214                 if ((NG_HOOK_NOT_VALID(hook))
 2215                 || (NG_NODE_NOT_VALID(NG_HOOK_NODE(hook)))) {
 2216                         NG_FREE_ITEM(item);
 2217                         return (ENOTCONN);
 2218                 }
 2219                 if ((hook->hk_flags & HK_QUEUE)) {
 2220                         queue = 1;
 2221                 }
 2222                 break;
 2223         case NGQF_MESG:
 2224                 /*
 2225                  * CONTROL MESSAGE
 2226                  * Delivered to a node.
 2227                  * Hook is optional.
 2228                  * References are held by the item on the node and
 2229                  * the hook if it is present.
 2230                  */
 2231                 if (hook && (hook->hk_flags & HK_QUEUE)) {
 2232                         queue = 1;
 2233                 }
 2234                 break;
 2235         case NGQF_FN:
 2236                 break;
 2237         default:
 2238                 NG_FREE_ITEM(item);
 2239                 TRAP_ERROR();
 2240                 return (EINVAL);
 2241         }
 2242         switch(item->el_flags & NGQF_RW) {
 2243         case NGQF_READER:
 2244                 rw = NGQRW_R;
 2245                 break;
 2246         case NGQF_WRITER:
 2247                 rw = NGQRW_W;
 2248                 break;
 2249         default:
 2250                 panic("%s: invalid item flags %lx", __func__, item->el_flags);
 2251         }
 2252 
 2253         /*
 2254          * If the node specifies single threading, force writer semantics.
 2255          * Similarly, the node may say one hook always produces writers.
 2256          * These are overrides.
 2257          */
 2258         if ((node->nd_flags & NGF_FORCE_WRITER)
 2259             || (hook && (hook->hk_flags & HK_FORCE_WRITER)))
 2260                         rw = NGQRW_W;
 2261 
 2262         if (queue) {
 2263                 /* Put it on the queue for that node*/
 2264 #ifdef  NETGRAPH_DEBUG
 2265                 _ngi_check(item, __FILE__, __LINE__);
 2266 #endif
 2267                 mtx_lock_spin(&(ngq->q_mtx));
 2268                 ng_queue_rw(ngq, item, rw);
 2269                 mtx_unlock_spin(&(ngq->q_mtx));
 2270 
 2271                 if (flags & NG_PROGRESS)
 2272                         return (EINPROGRESS);
 2273                 else
 2274                         return (0);
 2275         }
 2276 
 2277         /*
 2278          * We already decided how we will be queueud or treated.
 2279          * Try get the appropriate operating permission.
 2280          */
 2281         if (rw == NGQRW_R)
 2282                 item = ng_acquire_read(ngq, item);
 2283         else
 2284                 item = ng_acquire_write(ngq, item);
 2285 
 2286 
 2287         if (item == NULL) {
 2288                 if (flags & NG_PROGRESS)
 2289                         return (EINPROGRESS);
 2290                 else
 2291                         return (0);
 2292         }
 2293 
 2294 #ifdef  NETGRAPH_DEBUG
 2295         _ngi_check(item, __FILE__, __LINE__);
 2296 #endif
 2297 
 2298         NGI_GET_NODE(item, node); /* zaps stored node */
 2299 
 2300         error = ng_apply_item(node, item, rw); /* drops r/w lock when done */
 2301 
 2302         /*
 2303          * If the node goes away when we remove the reference,
 2304          * whatever we just did caused it.. whatever we do, DO NOT
 2305          * access the node again!
 2306          */
 2307         if (NG_NODE_UNREF(node) == 0) {
 2308                 return (error);
 2309         }
 2310 
 2311         mtx_lock_spin(&(ngq->q_mtx));
 2312         if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
 2313                 ng_setisr(ngq->q_node);
 2314         mtx_unlock_spin(&(ngq->q_mtx));
 2315 
 2316         return (error);
 2317 }
 2318 
 2319 /*
 2320  * We have an item that was possibly queued somewhere.
 2321  * It should contain all the information needed
 2322  * to run it on the appropriate node/hook.
 2323  */
 2324 static int
 2325 ng_apply_item(node_p node, item_p item, int rw)
 2326 {
 2327         hook_p  hook;
 2328         int     error = 0;
 2329         ng_rcvdata_t *rcvdata;
 2330         ng_rcvmsg_t *rcvmsg;
 2331         ng_apply_t *apply = NULL;
 2332         void    *context = NULL;
 2333 
 2334         NGI_GET_HOOK(item, hook); /* clears stored hook */
 2335 #ifdef  NETGRAPH_DEBUG
 2336         _ngi_check(item, __FILE__, __LINE__);
 2337 #endif
 2338 
 2339         /*
 2340          * If the item has an "apply" callback, store it.
 2341          * Clear item's callback immediately, to avoid an extra call if
 2342          * the item is reused by the destination node.
 2343          */
 2344         if (item->apply != NULL) {
 2345                 apply = item->apply;
 2346                 context = item->context;
 2347                 item->apply = NULL;
 2348         }
 2349 
 2350         switch (item->el_flags & NGQF_TYPE) {
 2351         case NGQF_DATA:
 2352                 /*
 2353                  * Check things are still ok as when we were queued.
 2354                  */
 2355                 if ((hook == NULL)
 2356                 || NG_HOOK_NOT_VALID(hook)
 2357                 || NG_NODE_NOT_VALID(node) ) {
 2358                         error = EIO;
 2359                         NG_FREE_ITEM(item);
 2360                         break;
 2361                 }
 2362                 /*
 2363                  * If no receive method, just silently drop it.
 2364                  * Give preference to the hook over-ride method
 2365                  */
 2366                 if ((!(rcvdata = hook->hk_rcvdata))
 2367                 && (!(rcvdata = NG_HOOK_NODE(hook)->nd_type->rcvdata))) {
 2368                         error = 0;
 2369                         NG_FREE_ITEM(item);
 2370                         break;
 2371                 }
 2372                 error = (*rcvdata)(hook, item);
 2373                 break;
 2374         case NGQF_MESG:
 2375                 if (hook) {
 2376                         if (NG_HOOK_NOT_VALID(hook)) {
 2377                                 /*
 2378                                  * The hook has been zapped then we can't
 2379                                  * use it. Immediatly drop its reference.
 2380                                  * The message may not need it.
 2381                                  */
 2382                                 NG_HOOK_UNREF(hook);
 2383                                 hook = NULL;
 2384                         }
 2385                 }
 2386                 /*
 2387                  * Similarly, if the node is a zombie there is
 2388                  * nothing we can do with it, drop everything.
 2389                  */
 2390                 if (NG_NODE_NOT_VALID(node)) {
 2391                         TRAP_ERROR();
 2392                         error = EINVAL;
 2393                         NG_FREE_ITEM(item);
 2394                 } else {
 2395                         /*
 2396                          * Call the appropriate message handler for the object.
 2397                          * It is up to the message handler to free the message.
 2398                          * If it's a generic message, handle it generically,
 2399                          * otherwise call the type's message handler
 2400                          * (if it exists)
 2401                          * XXX (race). Remember that a queued message may
 2402                          * reference a node or hook that has just been
 2403                          * invalidated. It will exist as the queue code
 2404                          * is holding a reference, but..
 2405                          */
 2406 
 2407                         struct ng_mesg *msg = NGI_MSG(item);
 2408 
 2409                         /*
 2410                          * check if the generic handler owns it.
 2411                          */
 2412                         if ((msg->header.typecookie == NGM_GENERIC_COOKIE)
 2413                         && ((msg->header.flags & NGF_RESP) == 0)) {
 2414                                 error = ng_generic_msg(node, item, hook);
 2415                                 break;
 2416                         }
 2417                         /*
 2418                          * Now see if there is a handler (hook or node specific)
 2419                          * in the target node. If none, silently discard.
 2420                          */
 2421                         if (((!hook) || (!(rcvmsg = hook->hk_rcvmsg)))
 2422                         && (!(rcvmsg = node->nd_type->rcvmsg))) {
 2423                                 TRAP_ERROR();
 2424                                 error = 0;
 2425                                 NG_FREE_ITEM(item);
 2426                                 break;
 2427                         }
 2428                         error = (*rcvmsg)(node, item, hook);
 2429                 }
 2430                 break;
 2431         case NGQF_FN:
 2432                 /*
 2433                  *  We have to implicitly trust the hook,
 2434                  * as some of these are used for system purposes
 2435                  * where the hook is invalid. In the case of
 2436                  * the shutdown message we allow it to hit
 2437                  * even if the node is invalid.
 2438                  */
 2439                 if ((NG_NODE_NOT_VALID(node))
 2440                 && (NGI_FN(item) != &ng_rmnode)) {
 2441                         TRAP_ERROR();
 2442                         error = EINVAL;
 2443                         NG_FREE_ITEM(item);
 2444                         break;
 2445                 }
 2446                 (*NGI_FN(item))(node, hook, NGI_ARG1(item), NGI_ARG2(item));
 2447                 NG_FREE_ITEM(item);
 2448                 break;
 2449                 
 2450         }
 2451         /*
 2452          * We held references on some of the resources
 2453          * that we took from the item. Now that we have
 2454          * finished doing everything, drop those references.
 2455          */
 2456         if (hook) {
 2457                 NG_HOOK_UNREF(hook);
 2458         }
 2459 
 2460         if (rw == NGQRW_R) {
 2461                 ng_leave_read(&node->nd_input_queue);
 2462         } else {
 2463                 ng_leave_write(&node->nd_input_queue);
 2464         }
 2465 
 2466         /* Apply callback. */
 2467         if (apply != NULL)
 2468                 (*apply)(context, error);
 2469 
 2470         return (error);
 2471 }
 2472 
 2473 /***********************************************************************
 2474  * Implement the 'generic' control messages
 2475  ***********************************************************************/
 2476 static int
 2477 ng_generic_msg(node_p here, item_p item, hook_p lasthook)
 2478 {
 2479         int error = 0;
 2480         struct ng_mesg *msg;
 2481         struct ng_mesg *resp = NULL;
 2482 
 2483         NGI_GET_MSG(item, msg);
 2484         if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
 2485                 TRAP_ERROR();
 2486                 error = EINVAL;
 2487                 goto out;
 2488         }
 2489         switch (msg->header.cmd) {
 2490         case NGM_SHUTDOWN:
 2491                 ng_rmnode(here, NULL, NULL, 0);
 2492                 break;
 2493         case NGM_MKPEER:
 2494             {
 2495                 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
 2496 
 2497                 if (msg->header.arglen != sizeof(*mkp)) {
 2498                         TRAP_ERROR();
 2499                         error = EINVAL;
 2500                         break;
 2501                 }
 2502                 mkp->type[sizeof(mkp->type) - 1] = '\0';
 2503                 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
 2504                 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
 2505                 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
 2506                 break;
 2507             }
 2508         case NGM_CONNECT:
 2509             {
 2510                 struct ngm_connect *const con =
 2511                         (struct ngm_connect *) msg->data;
 2512                 node_p node2;
 2513 
 2514                 if (msg->header.arglen != sizeof(*con)) {
 2515                         TRAP_ERROR();
 2516                         error = EINVAL;
 2517                         break;
 2518                 }
 2519                 con->path[sizeof(con->path) - 1] = '\0';
 2520                 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
 2521                 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
 2522                 /* Don't forget we get a reference.. */
 2523                 error = ng_path2noderef(here, con->path, &node2, NULL);
 2524                 if (error)
 2525                         break;
 2526                 error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
 2527                 NG_NODE_UNREF(node2);
 2528                 break;
 2529             }
 2530         case NGM_NAME:
 2531             {
 2532                 struct ngm_name *const nam = (struct ngm_name *) msg->data;
 2533 
 2534                 if (msg->header.arglen != sizeof(*nam)) {
 2535                         TRAP_ERROR();
 2536                         error = EINVAL;
 2537                         break;
 2538                 }
 2539                 nam->name[sizeof(nam->name) - 1] = '\0';
 2540                 error = ng_name_node(here, nam->name);
 2541                 break;
 2542             }
 2543         case NGM_RMHOOK:
 2544             {
 2545                 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
 2546                 hook_p hook;
 2547 
 2548                 if (msg->header.arglen != sizeof(*rmh)) {
 2549                         TRAP_ERROR();
 2550                         error = EINVAL;
 2551                         break;
 2552                 }
 2553                 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
 2554                 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
 2555                         ng_destroy_hook(hook);
 2556                 break;
 2557             }
 2558         case NGM_NODEINFO:
 2559             {
 2560                 struct nodeinfo *ni;
 2561 
 2562                 NG_MKRESPONSE(resp, msg, sizeof(*ni), M_NOWAIT);
 2563                 if (resp == NULL) {
 2564                         error = ENOMEM;
 2565                         break;
 2566                 }
 2567 
 2568                 /* Fill in node info */
 2569                 ni = (struct nodeinfo *) resp->data;
 2570                 if (NG_NODE_HAS_NAME(here))
 2571                         strcpy(ni->name, NG_NODE_NAME(here));
 2572                 strcpy(ni->type, here->nd_type->name);
 2573                 ni->id = ng_node2ID(here);
 2574                 ni->hooks = here->nd_numhooks;
 2575                 break;
 2576             }
 2577         case NGM_LISTHOOKS:
 2578             {
 2579                 const int nhooks = here->nd_numhooks;
 2580                 struct hooklist *hl;
 2581                 struct nodeinfo *ni;
 2582                 hook_p hook;
 2583 
 2584                 /* Get response struct */
 2585                 NG_MKRESPONSE(resp, msg, sizeof(*hl)
 2586                     + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
 2587                 if (resp == NULL) {
 2588                         error = ENOMEM;
 2589                         break;
 2590                 }
 2591                 hl = (struct hooklist *) resp->data;
 2592                 ni = &hl->nodeinfo;
 2593 
 2594                 /* Fill in node info */
 2595                 if (NG_NODE_HAS_NAME(here))
 2596                         strcpy(ni->name, NG_NODE_NAME(here));
 2597                 strcpy(ni->type, here->nd_type->name);
 2598                 ni->id = ng_node2ID(here);
 2599 
 2600                 /* Cycle through the linked list of hooks */
 2601                 ni->hooks = 0;
 2602                 LIST_FOREACH(hook, &here->nd_hooks, hk_hooks) {
 2603                         struct linkinfo *const link = &hl->link[ni->hooks];
 2604 
 2605                         if (ni->hooks >= nhooks) {
 2606                                 log(LOG_ERR, "%s: number of %s changed\n",
 2607                                     __func__, "hooks");
 2608                                 break;
 2609                         }
 2610                         if (NG_HOOK_NOT_VALID(hook))
 2611                                 continue;
 2612                         strcpy(link->ourhook, NG_HOOK_NAME(hook));
 2613                         strcpy(link->peerhook, NG_PEER_HOOK_NAME(hook));
 2614                         if (NG_PEER_NODE_NAME(hook)[0] != '\0')
 2615                                 strcpy(link->nodeinfo.name,
 2616                                     NG_PEER_NODE_NAME(hook));
 2617                         strcpy(link->nodeinfo.type,
 2618                            NG_PEER_NODE(hook)->nd_type->name);
 2619                         link->nodeinfo.id = ng_node2ID(NG_PEER_NODE(hook));
 2620                         link->nodeinfo.hooks = NG_PEER_NODE(hook)->nd_numhooks;
 2621                         ni->hooks++;
 2622                 }
 2623                 break;
 2624             }
 2625 
 2626         case NGM_LISTNAMES:
 2627         case NGM_LISTNODES:
 2628             {
 2629                 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
 2630                 struct namelist *nl;
 2631                 node_p node;
 2632                 int num = 0;
 2633 
 2634                 mtx_lock(&ng_nodelist_mtx);
 2635                 /* Count number of nodes */
 2636                 LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
 2637                         if (NG_NODE_IS_VALID(node)
 2638                         && (unnamed || NG_NODE_HAS_NAME(node))) {
 2639                                 num++;
 2640                         }
 2641                 }
 2642                 mtx_unlock(&ng_nodelist_mtx);
 2643 
 2644                 /* Get response struct */
 2645                 NG_MKRESPONSE(resp, msg, sizeof(*nl)
 2646                     + (num * sizeof(struct nodeinfo)), M_NOWAIT);
 2647                 if (resp == NULL) {
 2648                         error = ENOMEM;
 2649                         break;
 2650                 }
 2651                 nl = (struct namelist *) resp->data;
 2652 
 2653                 /* Cycle through the linked list of nodes */
 2654                 nl->numnames = 0;
 2655                 mtx_lock(&ng_nodelist_mtx);
 2656                 LIST_FOREACH(node, &ng_nodelist, nd_nodes) {
 2657                         struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
 2658 
 2659                         if (NG_NODE_NOT_VALID(node))
 2660                                 continue;
 2661                         if (!unnamed && (! NG_NODE_HAS_NAME(node)))
 2662                                 continue;
 2663                         if (nl->numnames >= num) {
 2664                                 log(LOG_ERR, "%s: number of %s changed\n",
 2665                                     __func__, "nodes");
 2666                                 break;
 2667                         }
 2668                         if (NG_NODE_HAS_NAME(node))
 2669                                 strcpy(np->name, NG_NODE_NAME(node));
 2670                         strcpy(np->type, node->nd_type->name);
 2671                         np->id = ng_node2ID(node);
 2672                         np->hooks = node->nd_numhooks;
 2673                         nl->numnames++;
 2674                 }
 2675                 mtx_unlock(&ng_nodelist_mtx);
 2676                 break;
 2677             }
 2678 
 2679         case NGM_LISTTYPES:
 2680             {
 2681                 struct typelist *tl;
 2682                 struct ng_type *type;
 2683                 int num = 0;
 2684 
 2685                 mtx_lock(&ng_typelist_mtx);
 2686                 /* Count number of types */
 2687                 LIST_FOREACH(type, &ng_typelist, types) {
 2688                         num++;
 2689                 }
 2690                 mtx_unlock(&ng_typelist_mtx);
 2691 
 2692                 /* Get response struct */
 2693                 NG_MKRESPONSE(resp, msg, sizeof(*tl)
 2694                     + (num * sizeof(struct typeinfo)), M_NOWAIT);
 2695                 if (resp == NULL) {
 2696                         error = ENOMEM;
 2697                         break;
 2698                 }
 2699                 tl = (struct typelist *) resp->data;
 2700 
 2701                 /* Cycle through the linked list of types */
 2702                 tl->numtypes = 0;
 2703                 mtx_lock(&ng_typelist_mtx);
 2704                 LIST_FOREACH(type, &ng_typelist, types) {
 2705                         struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
 2706 
 2707                         if (tl->numtypes >= num) {
 2708                                 log(LOG_ERR, "%s: number of %s changed\n",
 2709                                     __func__, "types");
 2710                                 break;
 2711                         }
 2712                         strcpy(tp->type_name, type->name);
 2713                         tp->numnodes = type->refs - 1; /* don't count list */
 2714                         tl->numtypes++;
 2715                 }
 2716                 mtx_unlock(&ng_typelist_mtx);
 2717                 break;
 2718             }
 2719 
 2720         case NGM_BINARY2ASCII:
 2721             {
 2722                 int bufSize = 20 * 1024;        /* XXX hard coded constant */
 2723                 const struct ng_parse_type *argstype;
 2724                 const struct ng_cmdlist *c;
 2725                 struct ng_mesg *binary, *ascii;
 2726 
 2727                 /* Data area must contain a valid netgraph message */
 2728                 binary = (struct ng_mesg *)msg->data;
 2729                 if (msg->header.arglen < sizeof(struct ng_mesg) ||
 2730                     (msg->header.arglen - sizeof(struct ng_mesg) <
 2731                     binary->header.arglen)) {
 2732                         TRAP_ERROR();
 2733                         error = EINVAL;
 2734                         break;
 2735                 }
 2736 
 2737                 /* Get a response message with lots of room */
 2738                 NG_MKRESPONSE(resp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
 2739                 if (resp == NULL) {
 2740                         error = ENOMEM;
 2741                         break;
 2742                 }
 2743                 ascii = (struct ng_mesg *)resp->data;
 2744 
 2745                 /* Copy binary message header to response message payload */
 2746                 bcopy(binary, ascii, sizeof(*binary));
 2747 
 2748                 /* Find command by matching typecookie and command number */
 2749                 for (c = here->nd_type->cmdlist;
 2750                     c != NULL && c->name != NULL; c++) {
 2751                         if (binary->header.typecookie == c->cookie
 2752                             && binary->header.cmd == c->cmd)
 2753                                 break;
 2754                 }
 2755                 if (c == NULL || c->name == NULL) {
 2756                         for (c = ng_generic_cmds; c->name != NULL; c++) {
 2757                                 if (binary->header.typecookie == c->cookie
 2758                                     && binary->header.cmd == c->cmd)
 2759                                         break;
 2760                         }
 2761                         if (c->name == NULL) {
 2762                                 NG_FREE_MSG(resp);
 2763                                 error = ENOSYS;
 2764                                 break;
 2765                         }
 2766                 }
 2767 
 2768                 /* Convert command name to ASCII */
 2769                 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
 2770                     "%s", c->name);
 2771 
 2772                 /* Convert command arguments to ASCII */
 2773                 argstype = (binary->header.flags & NGF_RESP) ?
 2774                     c->respType : c->mesgType;
 2775                 if (argstype == NULL) {
 2776                         *ascii->data = '\0';
 2777                 } else {
 2778                         if ((error = ng_unparse(argstype,
 2779                             (u_char *)binary->data,
 2780                             ascii->data, bufSize)) != 0) {
 2781                                 NG_FREE_MSG(resp);
 2782                                 break;
 2783                         }
 2784                 }
 2785 
 2786                 /* Return the result as struct ng_mesg plus ASCII string */
 2787                 bufSize = strlen(ascii->data) + 1;
 2788                 ascii->header.arglen = bufSize;
 2789                 resp->header.arglen = sizeof(*ascii) + bufSize;
 2790                 break;
 2791             }
 2792 
 2793         case NGM_ASCII2BINARY:
 2794             {
 2795                 int bufSize = 2000;     /* XXX hard coded constant */
 2796                 const struct ng_cmdlist *c;
 2797                 const struct ng_parse_type *argstype;
 2798                 struct ng_mesg *ascii, *binary;
 2799                 int off = 0;
 2800 
 2801                 /* Data area must contain at least a struct ng_mesg + '\0' */
 2802                 ascii = (struct ng_mesg *)msg->data;
 2803                 if ((msg->header.arglen < sizeof(*ascii) + 1) ||
 2804                     (ascii->header.arglen < 1) ||
 2805                     (msg->header.arglen < sizeof(*ascii) +
 2806                     ascii->header.arglen)) {
 2807                         TRAP_ERROR();
 2808                         error = EINVAL;
 2809                         break;
 2810                 }
 2811                 ascii->data[ascii->header.arglen - 1] = '\0';
 2812 
 2813                 /* Get a response message with lots of room */
 2814                 NG_MKRESPONSE(resp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
 2815                 if (resp == NULL) {
 2816                         error = ENOMEM;
 2817                         break;
 2818                 }
 2819                 binary = (struct ng_mesg *)resp->data;
 2820 
 2821                 /* Copy ASCII message header to response message payload */
 2822                 bcopy(ascii, binary, sizeof(*ascii));
 2823 
 2824                 /* Find command by matching ASCII command string */
 2825                 for (c = here->nd_type->cmdlist;
 2826                     c != NULL && c->name != NULL; c++) {
 2827                         if (strcmp(ascii->header.cmdstr, c->name) == 0)
 2828                                 break;
 2829                 }
 2830                 if (c == NULL || c->name == NULL) {
 2831                         for (c = ng_generic_cmds; c->name != NULL; c++) {
 2832                                 if (strcmp(ascii->header.cmdstr, c->name) == 0)
 2833                                         break;
 2834                         }
 2835                         if (c->name == NULL) {
 2836                                 NG_FREE_MSG(resp);
 2837                                 error = ENOSYS;
 2838                                 break;
 2839                         }
 2840                 }
 2841 
 2842                 /* Convert command name to binary */
 2843                 binary->header.cmd = c->cmd;
 2844                 binary->header.typecookie = c->cookie;
 2845 
 2846                 /* Convert command arguments to binary */
 2847                 argstype = (binary->header.flags & NGF_RESP) ?
 2848                     c->respType : c->mesgType;
 2849                 if (argstype == NULL) {
 2850                         bufSize = 0;
 2851                 } else {
 2852                         if ((error = ng_parse(argstype, ascii->data,
 2853                             &off, (u_char *)binary->data, &bufSize)) != 0) {
 2854                                 NG_FREE_MSG(resp);
 2855                                 break;
 2856                         }
 2857                 }
 2858 
 2859                 /* Return the result */
 2860                 binary->header.arglen = bufSize;
 2861                 resp->header.arglen = sizeof(*binary) + bufSize;
 2862                 break;
 2863             }
 2864 
 2865         case NGM_TEXT_CONFIG:
 2866         case NGM_TEXT_STATUS:
 2867                 /*
 2868                  * This one is tricky as it passes the command down to the
 2869                  * actual node, even though it is a generic type command.
 2870                  * This means we must assume that the item/msg is already freed
 2871                  * when control passes back to us.
 2872                  */
 2873                 if (here->nd_type->rcvmsg != NULL) {
 2874                         NGI_MSG(item) = msg; /* put it back as we found it */
 2875                         return((*here->nd_type->rcvmsg)(here, item, lasthook));
 2876                 }
 2877                 /* Fall through if rcvmsg not supported */
 2878         default:
 2879                 TRAP_ERROR();
 2880                 error = EINVAL;
 2881         }
 2882         /*
 2883          * Sometimes a generic message may be statically allocated
 2884          * to avoid problems with allocating when in tight memeory situations.
 2885          * Don't free it if it is so.
 2886          * I break them appart here, because erros may cause a free if the item
 2887          * in which case we'd be doing it twice.
 2888          * they are kept together above, to simplify freeing.
 2889          */
 2890 out:
 2891         NG_RESPOND_MSG(error, here, item, resp);
 2892         if (msg)
 2893                 NG_FREE_MSG(msg);
 2894         return (error);
 2895 }
 2896 
 2897 /************************************************************************
 2898                         Queue element get/free routines
 2899 ************************************************************************/
 2900 
 2901 uma_zone_t                      ng_qzone;
 2902 static int                      maxalloc = 512; /* limit the damage of a leak */
 2903 
 2904 TUNABLE_INT("net.graph.maxalloc", &maxalloc);
 2905 SYSCTL_INT(_net_graph, OID_AUTO, maxalloc, CTLFLAG_RDTUN, &maxalloc,
 2906     0, "Maximum number of queue items to allocate");
 2907 
 2908 #ifdef  NETGRAPH_DEBUG
 2909 static TAILQ_HEAD(, ng_item) ng_itemlist = TAILQ_HEAD_INITIALIZER(ng_itemlist);
 2910 static int                      allocated;      /* number of items malloc'd */
 2911 #endif
 2912 
 2913 /*
 2914  * Get a queue entry.
 2915  * This is usually called when a packet first enters netgraph.
 2916  * By definition, this is usually from an interrupt, or from a user.
 2917  * Users are not so important, but try be quick for the times that it's
 2918  * an interrupt.
 2919  */
 2920 static __inline item_p
 2921 ng_getqblk(int flags)
 2922 {
 2923         item_p item = NULL;
 2924         int wait;
 2925 
 2926         wait = (flags & NG_WAITOK) ? M_WAITOK : M_NOWAIT;
 2927 
 2928         item = uma_zalloc(ng_qzone, wait | M_ZERO);
 2929 
 2930 #ifdef  NETGRAPH_DEBUG
 2931         if (item) {
 2932                         mtx_lock(&ngq_mtx);
 2933                         TAILQ_INSERT_TAIL(&ng_itemlist, item, all);
 2934                         allocated++;
 2935                         mtx_unlock(&ngq_mtx);
 2936         }
 2937 #endif
 2938 
 2939         return (item);
 2940 }
 2941 
 2942 /*
 2943  * Release a queue entry
 2944  */
 2945 void
 2946 ng_free_item(item_p item)
 2947 {
 2948         KASSERT(item->apply == NULL, ("%s: leaking apply callback", __func__));
 2949 
 2950         /*
 2951          * The item may hold resources on it's own. We need to free
 2952          * these before we can free the item. What they are depends upon
 2953          * what kind of item it is. it is important that nodes zero
 2954          * out pointers to resources that they remove from the item
 2955          * or we release them again here.
 2956          */
 2957         switch (item->el_flags & NGQF_TYPE) {
 2958         case NGQF_DATA:
 2959                 /* If we have an mbuf still attached.. */
 2960                 NG_FREE_M(_NGI_M(item));
 2961                 break;
 2962         case NGQF_MESG:
 2963                 _NGI_RETADDR(item) = 0;
 2964                 NG_FREE_MSG(_NGI_MSG(item));
 2965                 break;
 2966         case NGQF_FN:
 2967                 /* nothing to free really, */
 2968                 _NGI_FN(item) = NULL;
 2969                 _NGI_ARG1(item) = NULL;
 2970                 _NGI_ARG2(item) = 0;
 2971         case NGQF_UNDEF:
 2972                 break;
 2973         }
 2974         /* If we still have a node or hook referenced... */
 2975         _NGI_CLR_NODE(item);
 2976         _NGI_CLR_HOOK(item);
 2977 
 2978 #ifdef  NETGRAPH_DEBUG
 2979         mtx_lock(&ngq_mtx);
 2980         TAILQ_REMOVE(&ng_itemlist, item, all);
 2981         allocated--;
 2982         mtx_unlock(&ngq_mtx);
 2983 #endif
 2984         uma_zfree(ng_qzone, item);
 2985 }
 2986 
 2987 /************************************************************************
 2988                         Module routines
 2989 ************************************************************************/
 2990 
 2991 /*
 2992  * Handle the loading/unloading of a netgraph node type module
 2993  */
 2994 int
 2995 ng_mod_event(module_t mod, int event, void *data)
 2996 {
 2997         struct ng_type *const type = data;
 2998         int s, error = 0;
 2999 
 3000         switch (event) {
 3001         case MOD_LOAD:
 3002 
 3003                 /* Register new netgraph node type */
 3004                 s = splnet();
 3005                 if ((error = ng_newtype(type)) != 0) {
 3006                         splx(s);
 3007                         break;
 3008                 }
 3009 
 3010                 /* Call type specific code */
 3011                 if (type->mod_event != NULL)
 3012                         if ((error = (*type->mod_event)(mod, event, data))) {
 3013                                 mtx_lock(&ng_typelist_mtx);
 3014                                 type->refs--;   /* undo it */
 3015                                 LIST_REMOVE(type, types);
 3016                                 mtx_unlock(&ng_typelist_mtx);
 3017                         }
 3018                 splx(s);
 3019                 break;
 3020 
 3021         case MOD_UNLOAD:
 3022                 s = splnet();
 3023                 if (type->refs > 1) {           /* make sure no nodes exist! */
 3024                         error = EBUSY;
 3025                 } else {
 3026                         if (type->refs == 0) {
 3027                                 /* failed load, nothing to undo */
 3028                                 splx(s);
 3029                                 break;
 3030                         }
 3031                         if (type->mod_event != NULL) {  /* check with type */
 3032                                 error = (*type->mod_event)(mod, event, data);
 3033                                 if (error != 0) {       /* type refuses.. */
 3034                                         splx(s);
 3035                                         break;
 3036                                 }
 3037                         }
 3038                         mtx_lock(&ng_typelist_mtx);
 3039                         LIST_REMOVE(type, types);
 3040                         mtx_unlock(&ng_typelist_mtx);
 3041                 }
 3042                 splx(s);
 3043                 break;
 3044 
 3045         default:
 3046                 if (type->mod_event != NULL)
 3047                         error = (*type->mod_event)(mod, event, data);
 3048                 else
 3049                         error = EOPNOTSUPP;             /* XXX ? */
 3050                 break;
 3051         }
 3052         return (error);
 3053 }
 3054 
 3055 /*
 3056  * Handle loading and unloading for this code.
 3057  * The only thing we need to link into is the NETISR strucure.
 3058  */
 3059 static int
 3060 ngb_mod_event(module_t mod, int event, void *data)
 3061 {
 3062         int error = 0;
 3063 
 3064         switch (event) {
 3065         case MOD_LOAD:
 3066                 /* Initialize everything. */
 3067                 mtx_init(&ng_worklist_mtx, "ng_worklist", NULL, MTX_SPIN);
 3068                 mtx_init(&ng_typelist_mtx, "netgraph types mutex", NULL,
 3069                     MTX_DEF);
 3070                 mtx_init(&ng_nodelist_mtx, "netgraph nodelist mutex", NULL,
 3071                     MTX_DEF);
 3072                 mtx_init(&ng_idhash_mtx, "netgraph idhash mutex", NULL,
 3073                     MTX_DEF);
 3074                 mtx_init(&ng_topo_mtx, "netgraph topology mutex", NULL,
 3075                     MTX_DEF);
 3076 #ifdef  NETGRAPH_DEBUG
 3077                 mtx_init(&ngq_mtx, "netgraph item list mutex", NULL,
 3078                     MTX_DEF);
 3079 #endif
 3080                 ng_qzone = uma_zcreate("NetGraph items", sizeof(struct ng_item),
 3081                     NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
 3082                 uma_zone_set_max(ng_qzone, maxalloc);
 3083                 netisr_register(NETISR_NETGRAPH, (netisr_t *)ngintr, NULL,
 3084                     NETISR_MPSAFE);
 3085                 break;
 3086         case MOD_UNLOAD:
 3087                 /* You cant unload it because an interface may be using it.  */
 3088                 error = EBUSY;
 3089                 break;
 3090         default:
 3091                 error = EOPNOTSUPP;
 3092                 break;
 3093         }
 3094         return (error);
 3095 }
 3096 
 3097 static moduledata_t netgraph_mod = {
 3098         "netgraph",
 3099         ngb_mod_event,
 3100         (NULL)
 3101 };
 3102 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_NETGRAPH, SI_ORDER_MIDDLE);
 3103 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
 3104 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
 3105 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
 3106 
 3107 #ifdef  NETGRAPH_DEBUG
 3108 void
 3109 dumphook (hook_p hook, char *file, int line)
 3110 {
 3111         printf("hook: name %s, %d refs, Last touched:\n",
 3112                 _NG_HOOK_NAME(hook), hook->hk_refs);
 3113         printf("        Last active @ %s, line %d\n",
 3114                 hook->lastfile, hook->lastline);
 3115         if (line) {
 3116                 printf(" problem discovered at file %s, line %d\n", file, line);
 3117         }
 3118 }
 3119 
 3120 void
 3121 dumpnode(node_p node, char *file, int line)
 3122 {
 3123         printf("node: ID [%x]: type '%s', %d hooks, flags 0x%x, %d refs, %s:\n",
 3124                 _NG_NODE_ID(node), node->nd_type->name,
 3125                 node->nd_numhooks, node->nd_flags,
 3126                 node->nd_refs, node->nd_name);
 3127         printf("        Last active @ %s, line %d\n",
 3128                 node->lastfile, node->lastline);
 3129         if (line) {
 3130                 printf(" problem discovered at file %s, line %d\n", file, line);
 3131         }
 3132 }
 3133 
 3134 void
 3135 dumpitem(item_p item, char *file, int line)
 3136 {
 3137         printf(" ACTIVE item, last used at %s, line %d",
 3138                 item->lastfile, item->lastline);
 3139         switch(item->el_flags & NGQF_TYPE) {
 3140         case NGQF_DATA:
 3141                 printf(" - [data]\n");
 3142                 break;
 3143         case NGQF_MESG:
 3144                 printf(" - retaddr[%d]:\n", _NGI_RETADDR(item));
 3145                 break;
 3146         case NGQF_FN:
 3147                 printf(" - fn@%p (%p, %p, %p, %d (%x))\n",
 3148                         item->body.fn.fn_fn,
 3149                         _NGI_NODE(item),
 3150                         _NGI_HOOK(item),
 3151                         item->body.fn.fn_arg1,
 3152                         item->body.fn.fn_arg2,
 3153                         item->body.fn.fn_arg2);
 3154                 break;
 3155         case NGQF_UNDEF:
 3156                 printf(" - UNDEFINED!\n");
 3157         }
 3158         if (line) {
 3159                 printf(" problem discovered at file %s, line %d\n", file, line);
 3160                 if (_NGI_NODE(item)) {
 3161                         printf("node %p ([%x])\n",
 3162                                 _NGI_NODE(item), ng_node2ID(_NGI_NODE(item)));
 3163                 }
 3164         }
 3165 }
 3166 
 3167 static void
 3168 ng_dumpitems(void)
 3169 {
 3170         item_p item;
 3171         int i = 1;
 3172         TAILQ_FOREACH(item, &ng_itemlist, all) {
 3173                 printf("[%d] ", i++);
 3174                 dumpitem(item, NULL, 0);
 3175         }
 3176 }
 3177 
 3178 static void
 3179 ng_dumpnodes(void)
 3180 {
 3181         node_p node;
 3182         int i = 1;
 3183         mtx_lock(&ng_nodelist_mtx);
 3184         SLIST_FOREACH(node, &ng_allnodes, nd_all) {
 3185                 printf("[%d] ", i++);
 3186                 dumpnode(node, NULL, 0);
 3187         }
 3188         mtx_unlock(&ng_nodelist_mtx);
 3189 }
 3190 
 3191 static void
 3192 ng_dumphooks(void)
 3193 {
 3194         hook_p hook;
 3195         int i = 1;
 3196         mtx_lock(&ng_nodelist_mtx);
 3197         SLIST_FOREACH(hook, &ng_allhooks, hk_all) {
 3198                 printf("[%d] ", i++);
 3199                 dumphook(hook, NULL, 0);
 3200         }
 3201         mtx_unlock(&ng_nodelist_mtx);
 3202 }
 3203 
 3204 static int
 3205 sysctl_debug_ng_dump_items(SYSCTL_HANDLER_ARGS)
 3206 {
 3207         int error;
 3208         int val;
 3209         int i;
 3210 
 3211         val = allocated;
 3212         i = 1;
 3213         error = sysctl_handle_int(oidp, &val, sizeof(int), req);
 3214         if (error != 0 || req->newptr == NULL)
 3215                 return (error);
 3216         if (val == 42) {
 3217                 ng_dumpitems();
 3218                 ng_dumpnodes();
 3219                 ng_dumphooks();
 3220         }
 3221         return (0);
 3222 }
 3223 
 3224 SYSCTL_PROC(_debug, OID_AUTO, ng_dump_items, CTLTYPE_INT | CTLFLAG_RW,
 3225     0, sizeof(int), sysctl_debug_ng_dump_items, "I", "Number of allocated items");
 3226 #endif  /* NETGRAPH_DEBUG */
 3227 
 3228 
 3229 /***********************************************************************
 3230 * Worklist routines
 3231 **********************************************************************/
 3232 /* NETISR thread enters here */
 3233 /*
 3234  * Pick a node off the list of nodes with work,
 3235  * try get an item to process off it.
 3236  * If there are no more, remove the node from the list.
 3237  */
 3238 static void
 3239 ngintr(void)
 3240 {
 3241         item_p item;
 3242         node_p  node = NULL;
 3243 
 3244         for (;;) {
 3245                 mtx_lock_spin(&ng_worklist_mtx);
 3246                 node = TAILQ_FIRST(&ng_worklist);
 3247                 if (!node) {
 3248                         mtx_unlock_spin(&ng_worklist_mtx);
 3249                         break;
 3250                 }
 3251                 node->nd_flags &= ~NGF_WORKQ;   
 3252                 TAILQ_REMOVE(&ng_worklist, node, nd_work);
 3253                 mtx_unlock_spin(&ng_worklist_mtx);
 3254                 CTR3(KTR_NET, "%20s: node [%x] (%p) taken off worklist",
 3255                     __func__, node->nd_ID, node);
 3256                 /*
 3257                  * We have the node. We also take over the reference
 3258                  * that the list had on it.
 3259                  * Now process as much as you can, until it won't
 3260                  * let you have another item off the queue.
 3261                  * All this time, keep the reference
 3262                  * that lets us be sure that the node still exists.
 3263                  * Let the reference go at the last minute.
 3264                  * ng_dequeue will put us back on the worklist
 3265                  * if there is more too do. This may be of use if there
 3266                  * are Multiple Processors and multiple Net threads in the
 3267                  * future.
 3268                  */
 3269                 for (;;) {
 3270                         int rw;
 3271 
 3272                         mtx_lock_spin(&node->nd_input_queue.q_mtx);
 3273                         item = ng_dequeue(&node->nd_input_queue, &rw);
 3274                         if (item == NULL) {
 3275                                 mtx_unlock_spin(&node->nd_input_queue.q_mtx);
 3276                                 break; /* go look for another node */
 3277                         } else {
 3278                                 mtx_unlock_spin(&node->nd_input_queue.q_mtx);
 3279                                 NGI_GET_NODE(item, node); /* zaps stored node */
 3280                                 ng_apply_item(node, item, rw);
 3281                                 NG_NODE_UNREF(node);
 3282                         }
 3283                 }
 3284                 NG_NODE_UNREF(node);
 3285         }
 3286 }
 3287 
 3288 static void
 3289 ng_worklist_remove(node_p node)
 3290 {
 3291         mtx_assert(&node->nd_input_queue.q_mtx, MA_OWNED);
 3292 
 3293         mtx_lock_spin(&ng_worklist_mtx);
 3294         if (node->nd_flags & NGF_WORKQ) {
 3295                 node->nd_flags &= ~NGF_WORKQ;
 3296                 TAILQ_REMOVE(&ng_worklist, node, nd_work);
 3297                 mtx_unlock_spin(&ng_worklist_mtx);
 3298                 NG_NODE_UNREF(node);
 3299                 CTR3(KTR_NET, "%20s: node [%x] (%p) removed from worklist",
 3300                     __func__, node->nd_ID, node);
 3301         } else {
 3302                 mtx_unlock_spin(&ng_worklist_mtx);
 3303         }
 3304 }
 3305 
 3306 /*
 3307  * XXX
 3308  * It's posible that a debugging NG_NODE_REF may need
 3309  * to be outside the mutex zone
 3310  */
 3311 static void
 3312 ng_setisr(node_p node)
 3313 {
 3314 
 3315         mtx_assert(&node->nd_input_queue.q_mtx, MA_OWNED);
 3316 
 3317         if ((node->nd_flags & NGF_WORKQ) == 0) {
 3318                 /*
 3319                  * If we are not already on the work queue,
 3320                  * then put us on.
 3321                  */
 3322                 node->nd_flags |= NGF_WORKQ;
 3323                 mtx_lock_spin(&ng_worklist_mtx);
 3324                 TAILQ_INSERT_TAIL(&ng_worklist, node, nd_work);
 3325                 mtx_unlock_spin(&ng_worklist_mtx);
 3326                 NG_NODE_REF(node); /* XXX fafe in mutex? */
 3327                 CTR3(KTR_NET, "%20s: node [%x] (%p) put on worklist", __func__,
 3328                     node->nd_ID, node);
 3329         } else
 3330                 CTR3(KTR_NET, "%20s: node [%x] (%p) already on worklist",
 3331                     __func__, node->nd_ID, node);
 3332         schednetisr(NETISR_NETGRAPH);
 3333 }
 3334 
 3335 
 3336 /***********************************************************************
 3337 * Externally useable functions to set up a queue item ready for sending
 3338 ***********************************************************************/
 3339 
 3340 #ifdef  NETGRAPH_DEBUG
 3341 #define ITEM_DEBUG_CHECKS                                               \
 3342         do {                                                            \
 3343                 if (NGI_NODE(item) ) {                                  \
 3344                         printf("item already has node");                \
 3345                         kdb_enter("has node");                          \
 3346                         NGI_CLR_NODE(item);                             \
 3347                 }                                                       \
 3348                 if (NGI_HOOK(item) ) {                                  \
 3349                         printf("item already has hook");                \
 3350                         kdb_enter("has hook");                          \
 3351                         NGI_CLR_HOOK(item);                             \
 3352                 }                                                       \
 3353         } while (0)
 3354 #else
 3355 #define ITEM_DEBUG_CHECKS
 3356 #endif
 3357 
 3358 /*
 3359  * Put mbuf into the item.
 3360  * Hook and node references will be removed when the item is dequeued.
 3361  * (or equivalent)
 3362  * (XXX) Unsafe because no reference held by peer on remote node.
 3363  * remote node might go away in this timescale.
 3364  * We know the hooks can't go away because that would require getting
 3365  * a writer item on both nodes and we must have at least a  reader
 3366  * here to be able to do this.
 3367  * Note that the hook loaded is the REMOTE hook.
 3368  *
 3369  * This is possibly in the critical path for new data.
 3370  */
 3371 item_p
 3372 ng_package_data(struct mbuf *m, int flags)
 3373 {
 3374         item_p item;
 3375 
 3376         if ((item = ng_getqblk(flags)) == NULL) {
 3377                 NG_FREE_M(m);
 3378                 return (NULL);
 3379         }
 3380         ITEM_DEBUG_CHECKS;
 3381         item->el_flags = NGQF_DATA | NGQF_READER;
 3382         item->el_next = NULL;
 3383         NGI_M(item) = m;
 3384         return (item);
 3385 }
 3386 
 3387 /*
 3388  * Allocate a queue item and put items into it..
 3389  * Evaluate the address as this will be needed to queue it and
 3390  * to work out what some of the fields should be.
 3391  * Hook and node references will be removed when the item is dequeued.
 3392  * (or equivalent)
 3393  */
 3394 item_p
 3395 ng_package_msg(struct ng_mesg *msg, int flags)
 3396 {
 3397         item_p item;
 3398 
 3399         if ((item = ng_getqblk(flags)) == NULL) {
 3400                 NG_FREE_MSG(msg);
 3401                 return (NULL);
 3402         }
 3403         ITEM_DEBUG_CHECKS;
 3404         /* Messages items count as writers unless explicitly exempted. */
 3405         if (msg->header.cmd & NGM_READONLY)
 3406                 item->el_flags = NGQF_MESG | NGQF_READER;
 3407         else
 3408                 item->el_flags = NGQF_MESG | NGQF_WRITER;
 3409         item->el_next = NULL;
 3410         /*
 3411          * Set the current lasthook into the queue item
 3412          */
 3413         NGI_MSG(item) = msg;
 3414         NGI_RETADDR(item) = 0;
 3415         return (item);
 3416 }
 3417 
 3418 
 3419 
 3420 #define SET_RETADDR(item, here, retaddr)                                \
 3421         do {    /* Data or fn items don't have retaddrs */              \
 3422                 if ((item->el_flags & NGQF_TYPE) == NGQF_MESG) {        \
 3423                         if (retaddr) {                                  \
 3424                                 NGI_RETADDR(item) = retaddr;            \
 3425                         } else {                                        \
 3426                                 /*                                      \
 3427                                  * The old return address should be ok. \
 3428                                  * If there isn't one, use the address  \
 3429                                  * here.                                \
 3430                                  */                                     \
 3431                                 if (NGI_RETADDR(item) == 0) {           \
 3432                                         NGI_RETADDR(item)               \
 3433                                                 = ng_node2ID(here);     \
 3434                                 }                                       \
 3435                         }                                               \
 3436                 }                                                       \
 3437         } while (0)
 3438 
 3439 int
 3440 ng_address_hook(node_p here, item_p item, hook_p hook, ng_ID_t retaddr)
 3441 {
 3442         hook_p peer;
 3443         node_p peernode;
 3444         ITEM_DEBUG_CHECKS;
 3445         /*
 3446          * Quick sanity check..
 3447          * Since a hook holds a reference on it's node, once we know
 3448          * that the peer is still connected (even if invalid,) we know
 3449          * that the peer node is present, though maybe invalid.
 3450          */
 3451         if ((hook == NULL)
 3452         || NG_HOOK_NOT_VALID(hook)
 3453         || (NG_HOOK_PEER(hook) == NULL)
 3454         || NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))
 3455         || NG_NODE_NOT_VALID(NG_PEER_NODE(hook))) {
 3456                 NG_FREE_ITEM(item);
 3457                 TRAP_ERROR();
 3458                 return (ENETDOWN);
 3459         }
 3460 
 3461         /*
 3462          * Transfer our interest to the other (peer) end.
 3463          */
 3464         peer = NG_HOOK_PEER(hook);
 3465         NG_HOOK_REF(peer);
 3466         NGI_SET_HOOK(item, peer);
 3467         peernode = NG_PEER_NODE(hook);
 3468         NG_NODE_REF(peernode);
 3469         NGI_SET_NODE(item, peernode);
 3470         SET_RETADDR(item, here, retaddr);
 3471         return (0);
 3472 }
 3473 
 3474 int
 3475 ng_address_path(node_p here, item_p item, char *address, ng_ID_t retaddr)
 3476 {
 3477         node_p  dest = NULL;
 3478         hook_p  hook = NULL;
 3479         int     error;
 3480 
 3481         ITEM_DEBUG_CHECKS;
 3482         /*
 3483          * Note that ng_path2noderef increments the reference count
 3484          * on the node for us if it finds one. So we don't have to.
 3485          */
 3486         error = ng_path2noderef(here, address, &dest, &hook);
 3487         if (error) {
 3488                 NG_FREE_ITEM(item);
 3489                 return (error);
 3490         }
 3491         NGI_SET_NODE(item, dest);
 3492         if ( hook) {
 3493                 NG_HOOK_REF(hook);      /* don't let it go while on the queue */
 3494                 NGI_SET_HOOK(item, hook);
 3495         }
 3496         SET_RETADDR(item, here, retaddr);
 3497         return (0);
 3498 }
 3499 
 3500 int
 3501 ng_address_ID(node_p here, item_p item, ng_ID_t ID, ng_ID_t retaddr)
 3502 {
 3503         node_p dest;
 3504 
 3505         ITEM_DEBUG_CHECKS;
 3506         /*
 3507          * Find the target node.
 3508          */
 3509         dest = ng_ID2noderef(ID); /* GETS REFERENCE! */
 3510         if (dest == NULL) {
 3511                 NG_FREE_ITEM(item);
 3512                 TRAP_ERROR();
 3513                 return(EINVAL);
 3514         }
 3515         /* Fill out the contents */
 3516         NGI_SET_NODE(item, dest);
 3517         NGI_CLR_HOOK(item);
 3518         SET_RETADDR(item, here, retaddr);
 3519         return (0);
 3520 }
 3521 
 3522 /*
 3523  * special case to send a message to self (e.g. destroy node)
 3524  * Possibly indicate an arrival hook too.
 3525  * Useful for removing that hook :-)
 3526  */
 3527 item_p
 3528 ng_package_msg_self(node_p here, hook_p hook, struct ng_mesg *msg)
 3529 {
 3530         item_p item;
 3531 
 3532         /*
 3533          * Find the target node.
 3534          * If there is a HOOK argument, then use that in preference
 3535          * to the address.
 3536          */
 3537         if ((item = ng_getqblk(NG_NOFLAGS)) == NULL) {
 3538                 NG_FREE_MSG(msg);
 3539                 return (NULL);
 3540         }
 3541 
 3542         /* Fill out the contents */
 3543         item->el_flags = NGQF_MESG | NGQF_WRITER;
 3544         item->el_next = NULL;
 3545         NG_NODE_REF(here);
 3546         NGI_SET_NODE(item, here);
 3547         if (hook) {
 3548                 NG_HOOK_REF(hook);
 3549                 NGI_SET_HOOK(item, hook);
 3550         }
 3551         NGI_MSG(item) = msg;
 3552         NGI_RETADDR(item) = ng_node2ID(here);
 3553         return (item);
 3554 }
 3555 
 3556 int
 3557 ng_send_fn1(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2,
 3558         int flags)
 3559 {
 3560         item_p item;
 3561 
 3562         if ((item = ng_getqblk(flags)) == NULL) {
 3563                 return (ENOMEM);
 3564         }
 3565         item->el_flags = NGQF_FN | NGQF_WRITER;
 3566         NG_NODE_REF(node); /* and one for the item */
 3567         NGI_SET_NODE(item, node);
 3568         if (hook) {
 3569                 NG_HOOK_REF(hook);
 3570                 NGI_SET_HOOK(item, hook);
 3571         }
 3572         NGI_FN(item) = fn;
 3573         NGI_ARG1(item) = arg1;
 3574         NGI_ARG2(item) = arg2;
 3575         return(ng_snd_item(item, flags));
 3576 }
 3577 
 3578 /*
 3579  * Official timeout routines for Netgraph nodes.
 3580  */
 3581 static void
 3582 ng_callout_trampoline(void *arg)
 3583 {
 3584         item_p item = arg;
 3585 
 3586         ng_snd_item(item, 0);
 3587 }
 3588 
 3589 
 3590 int
 3591 ng_callout(struct callout *c, node_p node, hook_p hook, int ticks,
 3592     ng_item_fn *fn, void * arg1, int arg2)
 3593 {
 3594         item_p item, oitem;
 3595 
 3596         if ((item = ng_getqblk(NG_NOFLAGS)) == NULL)
 3597                 return (ENOMEM);
 3598 
 3599         item->el_flags = NGQF_FN | NGQF_WRITER;
 3600         NG_NODE_REF(node);              /* and one for the item */
 3601         NGI_SET_NODE(item, node);
 3602         if (hook) {
 3603                 NG_HOOK_REF(hook);
 3604                 NGI_SET_HOOK(item, hook);
 3605         }
 3606         NGI_FN(item) = fn;
 3607         NGI_ARG1(item) = arg1;
 3608         NGI_ARG2(item) = arg2;
 3609         oitem = c->c_arg;
 3610         if (callout_reset(c, ticks, &ng_callout_trampoline, item) == 1 &&
 3611             oitem != NULL)
 3612                 NG_FREE_ITEM(oitem);
 3613         return (0);
 3614 }
 3615 
 3616 /* A special modified version of untimeout() */
 3617 int
 3618 ng_uncallout(struct callout *c, node_p node)
 3619 {
 3620         item_p item;
 3621         int rval;
 3622 
 3623         KASSERT(c != NULL, ("ng_uncallout: NULL callout"));
 3624         KASSERT(node != NULL, ("ng_uncallout: NULL node"));
 3625 
 3626         rval = callout_stop(c);
 3627         item = c->c_arg;
 3628         /* Do an extra check */
 3629         if ((rval > 0) && (c->c_func == &ng_callout_trampoline) &&
 3630             (NGI_NODE(item) == node)) {
 3631                 /*
 3632                  * We successfully removed it from the queue before it ran
 3633                  * So now we need to unreference everything that was
 3634                  * given extra references. (NG_FREE_ITEM does this).
 3635                  */
 3636                 NG_FREE_ITEM(item);
 3637         }
 3638         c->c_arg = NULL;
 3639 
 3640         return (rval);
 3641 }
 3642 
 3643 /*
 3644  * Set the address, if none given, give the node here.
 3645  */
 3646 void
 3647 ng_replace_retaddr(node_p here, item_p item, ng_ID_t retaddr)
 3648 {
 3649         if (retaddr) {
 3650                 NGI_RETADDR(item) = retaddr;
 3651         } else {
 3652                 /*
 3653                  * The old return address should be ok.
 3654                  * If there isn't one, use the address here.
 3655                  */
 3656                 NGI_RETADDR(item) = ng_node2ID(here);
 3657         }
 3658 }
 3659 
 3660 #define TESTING
 3661 #ifdef TESTING
 3662 /* just test all the macros */
 3663 void
 3664 ng_macro_test(item_p item);
 3665 void
 3666 ng_macro_test(item_p item)
 3667 {
 3668         node_p node = NULL;
 3669         hook_p hook = NULL;
 3670         struct mbuf *m;
 3671         struct ng_mesg *msg;
 3672         ng_ID_t retaddr;
 3673         int     error;
 3674 
 3675         NGI_GET_M(item, m);
 3676         NGI_GET_MSG(item, msg);
 3677         retaddr = NGI_RETADDR(item);
 3678         NG_SEND_DATA(error, hook, m, NULL);
 3679         NG_SEND_DATA_ONLY(error, hook, m);
 3680         NG_FWD_NEW_DATA(error, item, hook, m);
 3681         NG_FWD_ITEM_HOOK(error, item, hook);
 3682         NG_SEND_MSG_HOOK(error, node, msg, hook, retaddr);
 3683         NG_SEND_MSG_ID(error, node, msg, retaddr, retaddr);
 3684         NG_SEND_MSG_PATH(error, node, msg, ".:", retaddr);
 3685         NG_FWD_MSG_HOOK(error, node, item, hook, retaddr);
 3686 }
 3687 #endif /* TESTING */
 3688 

Cache object: 1777c367d05c3309ed533745003ad2be


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.