6 * Copyright (c) 1996-1999 Whistle Communications, Inc.
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.
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
38 * Authors: Julian Elischer <julian@freebsd.org>
39 * Archie Cobbs <archie@freebsd.org>
41 * $FreeBSD: src/sys/netgraph/ng_base.c,v 1.159 2008/04/19 05:30:49 mav Exp $
42 * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
46 * This file implements the base netgraph code.
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/ctype.h>
52 #include <sys/errno.h>
53 /*#include <sys/kdb.h>*/
54 #include <sys/kernel.h>
55 #include <sys/limits.h>
56 #include <sys/malloc.h>
58 #include <sys/msgport2.h>
59 #include <sys/mutex2.h>
60 #include <sys/queue.h>
61 #include <sys/sysctl.h>
62 #include <sys/syslog.h>
63 #include <sys/refcount.h>
65 #include <sys/taskqueue.h>
66 #include <machine/cpu.h>
68 #include <net/netisr.h>
70 #include <netgraph7/ng_message.h>
71 #include <netgraph7/netgraph.h>
72 #include <netgraph7/ng_parse.h>
74 MODULE_VERSION(netgraph, NG_ABI_VERSION);
76 /* Mutex to protect topology events. */
77 static struct mtx ng_topo_mtx;
80 static struct mtx ng_nodelist_mtx; /* protects global node/hook lists */
81 static struct mtx ngq_mtx; /* protects the queue item list */
83 static SLIST_HEAD(, ng_node) ng_allnodes;
84 static LIST_HEAD(, ng_node) ng_freenodes; /* in debug, we never free() them */
85 static SLIST_HEAD(, ng_hook) ng_allhooks;
86 static LIST_HEAD(, ng_hook) ng_freehooks; /* in debug, we never free() them */
88 static void ng_dumpitems(void);
89 static void ng_dumpnodes(void);
90 static void ng_dumphooks(void);
92 #endif /* NETGRAPH_DEBUG */
94 * DEAD versions of the structures.
95 * In order to avoid races, it is sometimes neccesary to point
96 * at SOMETHING even though theoretically, the current entity is
97 * INVALID. Use these to avoid these races.
99 struct ng_type ng_deadtype = {
103 NULL, /* constructor */
110 NULL, /* disconnect */
114 struct ng_node ng_deadnode = {
121 LIST_HEAD_INITIALIZER(ng_deadnode.hooks),
122 {}, /* all_nodes list entry */
123 {}, /* id hashtable list entry */
126 {}, /* should never use! (should hang) */
127 {}, /* workqueue entry */
128 STAILQ_HEAD_INITIALIZER(ng_deadnode.nd_input_queue.queue),
131 #ifdef NETGRAPH_DEBUG
136 #endif /* NETGRAPH_DEBUG */
139 struct ng_hook ng_deadhook = {
142 HK_INVALID | HK_DEAD,
143 0, /* undefined data link type */
144 &ng_deadhook, /* Peer is self */
145 &ng_deadnode, /* attached to deadnode */
147 NULL, /* override rcvmsg() */
148 NULL, /* override rcvdata() */
149 1, /* refs always >= 1 */
150 #ifdef NETGRAPH_DEBUG
155 #endif /* NETGRAPH_DEBUG */
159 * END DEAD STRUCTURES
161 /* List nodes with unallocated work */
162 static STAILQ_HEAD(, ng_node) ng_worklist = STAILQ_HEAD_INITIALIZER(ng_worklist);
163 static struct mtx ng_worklist_mtx; /* MUST LOCK NODE FIRST */
165 /* List of installed types */
166 static LIST_HEAD(, ng_type) ng_typelist;
167 static struct mtx ng_typelist_mtx;
169 /* Hash related definitions */
170 /* XXX Don't need to initialise them because it's a LIST */
171 #define NG_ID_HASH_SIZE 128 /* most systems wont need even this many */
172 static LIST_HEAD(, ng_node) ng_ID_hash[NG_ID_HASH_SIZE];
173 static struct mtx ng_idhash_mtx;
174 /* Method to find a node.. used twice so do it here */
175 #define NG_IDHASH_FN(ID) ((ID) % (NG_ID_HASH_SIZE))
176 #define NG_IDHASH_FIND(ID, node) \
178 KKASSERT(mtx_owned(&ng_idhash_mtx)); \
179 LIST_FOREACH(node, &ng_ID_hash[NG_IDHASH_FN(ID)], \
181 if (NG_NODE_IS_VALID(node) \
182 && (NG_NODE_ID(node) == ID)) { \
188 #define NG_NAME_HASH_SIZE 128 /* most systems wont need even this many */
189 static LIST_HEAD(, ng_node) ng_name_hash[NG_NAME_HASH_SIZE];
190 static struct mtx ng_namehash_mtx;
191 #define NG_NAMEHASH(NAME, HASH) \
195 for (c = (const u_char*)(NAME); *c; c++)\
197 (HASH) = h % (NG_NAME_HASH_SIZE); \
201 /* Internal functions */
202 static int ng_add_hook(node_p node, const char *name, hook_p * hookp);
203 static int ng_generic_msg(node_p here, item_p item, hook_p lasthook);
204 static ng_ID_t ng_decodeidname(const char *name);
205 static int ngb_mod_event(module_t mod, int event, void *data);
206 static void ng_worklist_add(node_p node);
207 static void ngtask(void *, int);
208 static int ng_apply_item(node_p node, item_p item, int rw);
209 static void ng_flush_input_queue(node_p node);
210 static node_p ng_ID2noderef(ng_ID_t ID);
211 static int ng_con_nodes(item_p item, node_p node, const char *name,
212 node_p node2, const char *name2);
213 static int ng_con_part2(node_p node, item_p item, hook_p hook);
214 static int ng_con_part3(node_p node, item_p item, hook_p hook);
215 static int ng_mkpeer(node_p node, const char *name,
216 const char *name2, char *type);
217 static boolean_t bzero_ctor(void *obj, void *private, int ocflags);
219 /* Imported, these used to be externally visible, some may go back. */
220 void ng_destroy_hook(hook_p hook);
221 node_p ng_name2noderef(node_p node, const char *name);
222 int ng_path2noderef(node_p here, const char *path,
223 node_p *dest, hook_p *lasthook);
224 int ng_make_node(const char *type, node_p *nodepp);
225 int ng_path_parse(char *addr, char **node, char **path, char **hook);
226 void ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3);
227 void ng_unname(node_p node);
230 /* Our own netgraph malloc type */
231 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
232 MALLOC_DEFINE(M_NETGRAPH_HOOK, "netgraph_hook", "netgraph hook structures");
233 MALLOC_DEFINE(M_NETGRAPH_NODE, "netgraph_node", "netgraph node structures");
234 MALLOC_DEFINE(M_NETGRAPH_MSG, "netgraph_msg", "netgraph name storage");
236 /* Should not be visible outside this file */
238 #define _NG_ALLOC_HOOK(hook) \
239 hook = kmalloc(sizeof(*hook), M_NETGRAPH_HOOK, \
240 M_WAITOK | M_NULLOK | M_ZERO)
241 #define _NG_ALLOC_NODE(node) \
242 node = kmalloc(sizeof(*node), M_NETGRAPH_NODE, \
243 M_WAITOK | M_NULLOK | M_ZERO)
245 #define NG_QUEUE_LOCK_INIT(n) \
246 mtx_init(&(n)->q_mtx)
247 #define NG_QUEUE_LOCK(n) \
248 mtx_lock(&(n)->q_mtx)
249 #define NG_QUEUE_UNLOCK(n) \
250 mtx_unlock(&(n)->q_mtx)
251 #define NG_WORKLIST_LOCK_INIT() \
252 mtx_init(&ng_worklist_mtx)
253 #define NG_WORKLIST_LOCK() \
254 mtx_lock(&ng_worklist_mtx)
255 #define NG_WORKLIST_UNLOCK() \
256 mtx_unlock(&ng_worklist_mtx)
258 #ifdef NETGRAPH_DEBUG /*----------------------------------------------*/
261 * In an attempt to help track reference count screwups
262 * we do not free objects back to the malloc system, but keep them
263 * in a local cache where we can examine them and keep information safely
264 * after they have been freed.
265 * We use this scheme for nodes and hooks, and to some extent for items.
267 static __inline hook_p
271 SLIST_ENTRY(ng_hook) temp;
272 mtx_lock(&ng_nodelist_mtx);
273 hook = LIST_FIRST(&ng_freehooks);
275 LIST_REMOVE(hook, hk_hooks);
276 bcopy(&hook->hk_all, &temp, sizeof(temp));
277 bzero(hook, sizeof(struct ng_hook));
278 bcopy(&temp, &hook->hk_all, sizeof(temp));
279 mtx_unlock(&ng_nodelist_mtx);
280 hook->hk_magic = HK_MAGIC;
282 mtx_unlock(&ng_nodelist_mtx);
283 _NG_ALLOC_HOOK(hook);
285 hook->hk_magic = HK_MAGIC;
286 mtx_lock(&ng_nodelist_mtx);
287 SLIST_INSERT_HEAD(&ng_allhooks, hook, hk_all);
288 mtx_unlock(&ng_nodelist_mtx);
294 static __inline node_p
298 SLIST_ENTRY(ng_node) temp;
299 mtx_lock(&ng_nodelist_mtx);
300 node = LIST_FIRST(&ng_freenodes);
302 LIST_REMOVE(node, nd_nodes);
303 bcopy(&node->nd_all, &temp, sizeof(temp));
304 bzero(node, sizeof(struct ng_node));
305 bcopy(&temp, &node->nd_all, sizeof(temp));
306 mtx_unlock(&ng_nodelist_mtx);
307 node->nd_magic = ND_MAGIC;
309 mtx_unlock(&ng_nodelist_mtx);
310 _NG_ALLOC_NODE(node);
312 node->nd_magic = ND_MAGIC;
313 mtx_lock(&ng_nodelist_mtx);
314 SLIST_INSERT_HEAD(&ng_allnodes, node, nd_all);
315 mtx_unlock(&ng_nodelist_mtx);
321 #define NG_ALLOC_HOOK(hook) do { (hook) = ng_alloc_hook(); } while (0)
322 #define NG_ALLOC_NODE(node) do { (node) = ng_alloc_node(); } while (0)
325 #define NG_FREE_HOOK(hook) \
327 mtx_lock(&ng_nodelist_mtx); \
328 LIST_INSERT_HEAD(&ng_freehooks, hook, hk_hooks); \
329 hook->hk_magic = 0; \
330 mtx_unlock(&ng_nodelist_mtx); \
333 #define NG_FREE_NODE(node) \
335 mtx_lock(&ng_nodelist_mtx); \
336 LIST_INSERT_HEAD(&ng_freenodes, node, nd_nodes); \
337 node->nd_magic = 0; \
338 mtx_unlock(&ng_nodelist_mtx); \
341 #else /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
343 #define NG_ALLOC_HOOK(hook) _NG_ALLOC_HOOK(hook)
344 #define NG_ALLOC_NODE(node) _NG_ALLOC_NODE(node)
346 #define NG_FREE_HOOK(hook) do { kfree((hook), M_NETGRAPH_HOOK); } while (0)
347 #define NG_FREE_NODE(node) do { kfree((node), M_NETGRAPH_NODE); } while (0)
349 #endif /* NETGRAPH_DEBUG */ /*----------------------------------------------*/
351 /* Set this to kdb_enter("X") to catch all errors as they occur */
356 static ng_ID_t nextID = 1;
359 #define CHECK_DATA_MBUF(m) do { \
364 for (total = 0, n = (m); n != NULL; n = n->m_next) { \
366 if (n->m_nextpkt != NULL) \
367 panic("%s: m_nextpkt", __func__); \
370 if ((m)->m_pkthdr.len != total) { \
371 panic("%s: %d != %d", \
372 __func__, (m)->m_pkthdr.len, total); \
376 #define CHECK_DATA_MBUF(m)
379 #define ERROUT(x) do { error = (x); goto done; } while (0)
381 /************************************************************************
382 Parse type definitions for generic messages
383 ************************************************************************/
385 /* Handy structure parse type defining macro */
386 #define DEFINE_PARSE_STRUCT_TYPE(lo, up, args) \
387 static const struct ng_parse_struct_field \
388 ng_ ## lo ## _type_fields[] = NG_GENERIC_ ## up ## _INFO args; \
389 static const struct ng_parse_type ng_generic_ ## lo ## _type = { \
390 &ng_parse_struct_type, \
391 &ng_ ## lo ## _type_fields \
394 DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
395 DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
396 DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
397 DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
398 DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
399 DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
400 DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));
402 /* Get length of an array when the length is stored as a 32 bit
403 value immediately preceding the array -- as with struct namelist
404 and struct typelist. */
406 ng_generic_list_getLength(const struct ng_parse_type *type,
407 const u_char *start, const u_char *buf)
409 return *((const u_int32_t *)(buf - 4));
412 /* Get length of the array of struct linkinfo inside a struct hooklist */
414 ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
415 const u_char *start, const u_char *buf)
417 const struct hooklist *hl = (const struct hooklist *)start;
419 return hl->nodeinfo.hooks;
422 /* Array type for a variable length array of struct namelist */
423 static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
424 &ng_generic_nodeinfo_type,
425 &ng_generic_list_getLength
427 static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
428 &ng_parse_array_type,
429 &ng_nodeinfoarray_type_info
432 /* Array type for a variable length array of struct typelist */
433 static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
434 &ng_generic_typeinfo_type,
435 &ng_generic_list_getLength
437 static const struct ng_parse_type ng_generic_typeinfoarray_type = {
438 &ng_parse_array_type,
439 &ng_typeinfoarray_type_info
442 /* Array type for array of struct linkinfo in struct hooklist */
443 static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
444 &ng_generic_linkinfo_type,
445 &ng_generic_linkinfo_getLength
447 static const struct ng_parse_type ng_generic_linkinfo_array_type = {
448 &ng_parse_array_type,
449 &ng_generic_linkinfo_array_type_info
452 DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
453 DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
454 (&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
455 DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
456 (&ng_generic_nodeinfoarray_type));
458 /* List of commands and how to convert arguments to/from ASCII */
459 static const struct ng_cmdlist ng_generic_cmds[] = {
471 &ng_generic_mkpeer_type,
478 &ng_generic_connect_type,
485 &ng_generic_name_type,
492 &ng_generic_rmhook_type,
500 &ng_generic_nodeinfo_type
507 &ng_generic_hooklist_type
514 &ng_generic_listnodes_type /* same as NGM_LISTNODES */
521 &ng_generic_listnodes_type
528 &ng_generic_typeinfo_type
535 &ng_parse_string_type
542 &ng_parse_string_type
548 &ng_parse_ng_mesg_type,
549 &ng_parse_ng_mesg_type
555 &ng_parse_ng_mesg_type,
556 &ng_parse_ng_mesg_type
561 /************************************************************************
563 ************************************************************************/
566 * Instantiate a node of the requested type
569 ng_make_node(const char *typename, node_p *nodepp)
571 struct ng_type *type;
574 /* Check that the type makes sense */
575 if (typename == NULL) {
580 /* Locate the node type. If we fail we return. Do not try to load
583 if ((type = ng_findtype(typename)) == NULL)
587 * If we have a constructor, then make the node and
588 * call the constructor to do type specific initialisation.
590 if (type->constructor != NULL) {
591 if ((error = ng_make_node_common(type, nodepp)) == 0) {
592 if ((error = ((*type->constructor)(*nodepp)) != 0)) {
593 NG_NODE_UNREF(*nodepp);
598 * Node has no constructor. We cannot ask for one
599 * to be made. It must be brought into existence by
600 * some external agency. The external agency should
601 * call ng_make_node_common() directly to get the
602 * netgraph part initialised.
611 * Generic node creation. Called by node initialisation for externally
612 * instantiated nodes (e.g. hardware, sockets, etc ).
613 * The returned node has a reference count of 1.
616 ng_make_node_common(struct ng_type *type, node_p *nodepp)
620 /* Require the node type to have been already installed */
621 if (ng_findtype(type->name) == NULL) {
626 /* Make a node and try attach it to the type */
632 node->nd_type = type;
633 NG_NODE_REF(node); /* note reference */
636 NG_QUEUE_LOCK_INIT(&node->nd_input_queue);
637 STAILQ_INIT(&node->nd_input_queue.queue);
638 node->nd_input_queue.q_flags = 0;
640 /* Initialize hook list for new node */
641 LIST_INIT(&node->nd_hooks);
643 /* Link us into the name hash. */
644 mtx_lock(&ng_namehash_mtx);
645 LIST_INSERT_HEAD(&ng_name_hash[0], node, nd_nodes);
646 mtx_unlock(&ng_namehash_mtx);
648 /* get an ID and put us in the hash chain */
649 mtx_lock(&ng_idhash_mtx);
650 for (;;) { /* wrap protection, even if silly */
652 node->nd_ID = nextID++; /* 137/second for 1 year before wrap */
654 /* Is there a problem with the new number? */
655 NG_IDHASH_FIND(node->nd_ID, node2); /* already taken? */
656 if ((node->nd_ID != 0) && (node2 == NULL)) {
660 LIST_INSERT_HEAD(&ng_ID_hash[NG_IDHASH_FN(node->nd_ID)],
662 mtx_unlock(&ng_idhash_mtx);
670 * Forceably start the shutdown process on a node. Either call
671 * its shutdown method, or do the default shutdown if there is
672 * no type-specific method.
674 * We can only be called from a shutdown message, so we know we have
675 * a writer lock, and therefore exclusive access. It also means
676 * that we should not be on the work queue, but we check anyhow.
678 * Persistent node types must have a type-specific method which
679 * allocates a new node in which case, this one is irretrievably going away,
680 * or cleans up anything it needs, and just makes the node valid again,
681 * in which case we allow the node to survive.
683 * XXX We need to think of how to tell a persistent node that we
684 * REALLY need to go away because the hardware has gone or we
685 * are rebooting.... etc.
688 ng_rmnode(node_p node, hook_p dummy1, void *dummy2, int dummy3)
692 /* Check if it's already shutting down */
693 if ((node->nd_flags & NGF_CLOSING) != 0)
696 if (node == &ng_deadnode) {
697 printf ("shutdown called on deadnode\n");
701 /* Add an extra reference so it doesn't go away during this */
705 * Mark it invalid so any newcomers know not to try use it
706 * Also add our own mark so we can't recurse
707 * note that NGF_INVALID does not do this as it's also set during
710 node->nd_flags |= NGF_INVALID|NGF_CLOSING;
712 /* If node has its pre-shutdown method, then call it first*/
713 if (node->nd_type && node->nd_type->close)
714 (*node->nd_type->close)(node);
716 /* Notify all remaining connected nodes to disconnect */
717 while ((hook = LIST_FIRST(&node->nd_hooks)) != NULL)
718 ng_destroy_hook(hook);
721 * Drain the input queue forceably.
722 * it has no hooks so what's it going to do, bleed on someone?
723 * Theoretically we came here from a queue entry that was added
724 * Just before the queue was closed, so it should be empty anyway.
725 * Also removes us from worklist if needed.
727 ng_flush_input_queue(node);
729 /* Ask the type if it has anything to do in this case */
730 if (node->nd_type && node->nd_type->shutdown) {
731 (*node->nd_type->shutdown)(node);
732 if (NG_NODE_IS_VALID(node)) {
734 * Well, blow me down if the node code hasn't declared
735 * that it doesn't want to die.
736 * Presumably it is a persistant node.
737 * If we REALLY want it to go away,
738 * e.g. hardware going away,
739 * Our caller should set NGF_REALLY_DIE in nd_flags.
741 node->nd_flags &= ~(NGF_INVALID|NGF_CLOSING);
742 NG_NODE_UNREF(node); /* Assume they still have theirs */
745 } else { /* do the default thing */
749 ng_unname(node); /* basically a NOP these days */
752 * Remove extra reference, possibly the last
753 * Possible other holders of references may include
754 * timeout callouts, but theoretically the node's supposed to
755 * have cancelled them. Possibly hardware dependencies may
756 * force a driver to 'linger' with a reference.
762 * Remove a reference to the node, possibly the last.
763 * deadnode always acts as it it were the last.
766 ng_unref_node(node_p node)
770 if (node == &ng_deadnode) {
774 v = atomic_fetchadd_int(&node->nd_refs, -1);
776 if (v == 1) { /* we were the last */
778 mtx_lock(&ng_namehash_mtx);
779 node->nd_type->refs--; /* XXX maybe should get types lock? */
780 LIST_REMOVE(node, nd_nodes);
781 mtx_unlock(&ng_namehash_mtx);
783 mtx_lock(&ng_idhash_mtx);
784 LIST_REMOVE(node, nd_idnodes);
785 mtx_unlock(&ng_idhash_mtx);
787 mtx_uninit(&node->nd_input_queue.q_mtx);
793 /************************************************************************
795 ************************************************************************/
797 ng_ID2noderef(ng_ID_t ID)
800 mtx_lock(&ng_idhash_mtx);
801 NG_IDHASH_FIND(ID, node);
804 mtx_unlock(&ng_idhash_mtx);
809 ng_node2ID(node_p node)
811 return (node ? NG_NODE_ID(node) : 0);
814 /************************************************************************
816 ************************************************************************/
819 * Assign a node a name. Once assigned, the name cannot be changed.
822 ng_name_node(node_p node, const char *name)
827 /* Check the name is valid */
828 for (i = 0; i < NG_NODESIZ; i++) {
829 if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
832 if (i == 0 || name[i] != '\0') {
836 if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
841 /* Check the name isn't already being used */
842 if ((node2 = ng_name2noderef(node, name)) != NULL) {
843 NG_NODE_UNREF(node2);
849 strlcpy(NG_NODE_NAME(node), name, NG_NODESIZ);
851 /* Update name hash. */
852 NG_NAMEHASH(name, hash);
853 mtx_lock(&ng_namehash_mtx);
854 LIST_REMOVE(node, nd_nodes);
855 LIST_INSERT_HEAD(&ng_name_hash[hash], node, nd_nodes);
856 mtx_unlock(&ng_namehash_mtx);
862 * Find a node by absolute name. The name should NOT end with ':'
863 * The name "." means "this node" and "[xxx]" means "the node
864 * with ID (ie, at address) xxx".
866 * Returns the node if found, else NULL.
867 * Eventually should add something faster than a sequential search.
868 * Note it acquires a reference on the node so you can be sure it's still
872 ng_name2noderef(node_p here, const char *name)
878 /* "." means "this node" */
879 if (strcmp(name, ".") == 0) {
884 /* Check for name-by-ID */
885 if ((temp = ng_decodeidname(name)) != 0) {
886 return (ng_ID2noderef(temp));
889 /* Find node by name */
890 NG_NAMEHASH(name, hash);
891 mtx_lock(&ng_namehash_mtx);
892 LIST_FOREACH(node, &ng_name_hash[hash], nd_nodes) {
893 if (NG_NODE_IS_VALID(node) &&
894 (strcmp(NG_NODE_NAME(node), name) == 0)) {
900 mtx_unlock(&ng_namehash_mtx);
905 * Decode an ID name, eg. "[f03034de]". Returns 0 if the
906 * string is not valid, otherwise returns the value.
909 ng_decodeidname(const char *name)
911 const int len = strlen(name);
915 /* Check for proper length, brackets, no leading junk */
918 || (name[len - 1] != ']')
919 || (!isxdigit(name[1]))) {
924 val = strtoul(name + 1, &eptr, 16);
925 if ((eptr - name != len - 1)
926 || (val == ULONG_MAX)
934 * Remove a name from a node. This should only be called
935 * when shutting down and removing the node.
936 * IF we allow name changing this may be more resurrected.
939 ng_unname(node_p node)
943 /************************************************************************
945 Names are not optional. Hooks are always connected, except for a
946 brief moment within these routines. On invalidation or during creation
947 they are connected to the 'dead' hook.
948 ************************************************************************/
951 * Remove a hook reference
954 ng_unref_hook(hook_p hook)
958 if (hook == &ng_deadhook) {
962 v = atomic_fetchadd_int(&hook->hk_refs, -1);
964 if (v == 1) { /* we were the last */
965 if (_NG_HOOK_NODE(hook)) /* it'll probably be ng_deadnode */
966 _NG_NODE_UNREF((_NG_HOOK_NODE(hook)));
972 * Add an unconnected hook to a node. Only used internally.
973 * Assumes node is locked. (XXX not yet true )
976 ng_add_hook(node_p node, const char *name, hook_p *hookp)
981 /* Check that the given name is good */
986 if (ng_findhook(node, name) != NULL) {
991 /* Allocate the hook and link it up */
997 hook->hk_refs = 1; /* add a reference for us to return */
998 hook->hk_flags = HK_INVALID;
999 hook->hk_peer = &ng_deadhook; /* start off this way */
1000 hook->hk_node = node;
1001 NG_NODE_REF(node); /* each hook counts as a reference */
1004 strlcpy(NG_HOOK_NAME(hook), name, NG_HOOKSIZ);
1007 * Check if the node type code has something to say about it
1008 * If it fails, the unref of the hook will also unref the node.
1010 if (node->nd_type->newhook != NULL) {
1011 if ((error = (*node->nd_type->newhook)(node, hook, name))) {
1012 NG_HOOK_UNREF(hook); /* this frees the hook */
1017 * The 'type' agrees so far, so go ahead and link it in.
1018 * We'll ask again later when we actually connect the hooks.
1020 LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
1021 node->nd_numhooks++;
1022 NG_HOOK_REF(hook); /* one for the node */
1032 * Node types may supply their own optimized routines for finding
1033 * hooks. If none is supplied, we just do a linear search.
1034 * XXX Possibly we should add a reference to the hook?
1037 ng_findhook(node_p node, const char *name)
1041 if (node->nd_type->findhook != NULL)
1042 return (*node->nd_type->findhook)(node, name);
1043 LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
1044 if (NG_HOOK_IS_VALID(hook)
1045 && (strcmp(NG_HOOK_NAME(hook), name) == 0))
1054 * As hooks are always attached, this really destroys two hooks.
1055 * The one given, and the one attached to it. Disconnect the hooks
1056 * from each other first. We reconnect the peer hook to the 'dead'
1057 * hook so that it can still exist after we depart. We then
1058 * send the peer its own destroy message. This ensures that we only
1059 * interact with the peer's structures when it is locked processing that
1060 * message. We hold a reference to the peer hook so we are guaranteed that
1061 * the peer hook and node are still going to exist until
1062 * we are finished there as the hook holds a ref on the node.
1063 * We run this same code again on the peer hook, but that time it is already
1064 * attached to the 'dead' hook.
1066 * This routine is called at all stages of hook creation
1067 * on error detection and must be able to handle any such stage.
1070 ng_destroy_hook(hook_p hook)
1075 if (hook == &ng_deadhook) { /* better safe than sorry */
1076 printf("ng_destroy_hook called on deadhook\n");
1081 * Protect divorce process with mutex, to avoid races on
1082 * simultaneous disconnect.
1084 mtx_lock(&ng_topo_mtx);
1086 hook->hk_flags |= HK_INVALID;
1088 peer = NG_HOOK_PEER(hook);
1089 node = NG_HOOK_NODE(hook);
1091 if (peer && (peer != &ng_deadhook)) {
1093 * Set the peer to point to ng_deadhook
1094 * from this moment on we are effectively independent it.
1095 * send it an rmhook message of it's own.
1097 peer->hk_peer = &ng_deadhook; /* They no longer know us */
1098 hook->hk_peer = &ng_deadhook; /* Nor us, them */
1099 if (NG_HOOK_NODE(peer) == &ng_deadnode) {
1101 * If it's already divorced from a node,
1104 mtx_unlock(&ng_topo_mtx);
1106 mtx_unlock(&ng_topo_mtx);
1107 ng_rmhook_self(peer); /* Send it a surprise */
1109 NG_HOOK_UNREF(peer); /* account for peer link */
1110 NG_HOOK_UNREF(hook); /* account for peer link */
1112 mtx_unlock(&ng_topo_mtx);
1114 KKASSERT(mtx_notowned(&ng_topo_mtx));
1117 * Remove the hook from the node's list to avoid possible recursion
1118 * in case the disconnection results in node shutdown.
1120 if (node == &ng_deadnode) { /* happens if called from ng_con_nodes() */
1123 LIST_REMOVE(hook, hk_hooks);
1124 node->nd_numhooks--;
1125 if (node->nd_type->disconnect) {
1127 * The type handler may elect to destroy the node so don't
1128 * trust its existence after this point. (except
1129 * that we still hold a reference on it. (which we
1130 * inherrited from the hook we are destroying)
1132 (*node->nd_type->disconnect) (hook);
1136 * Note that because we will point to ng_deadnode, the original node
1137 * is not decremented automatically so we do that manually.
1139 _NG_HOOK_NODE(hook) = &ng_deadnode;
1140 NG_NODE_UNREF(node); /* We no longer point to it so adjust count */
1141 NG_HOOK_UNREF(hook); /* Account for linkage (in list) to node */
1145 * Take two hooks on a node and merge the connection so that the given node
1146 * is effectively bypassed.
1149 ng_bypass(hook_p hook1, hook_p hook2)
1151 if (hook1->hk_node != hook2->hk_node) {
1155 hook1->hk_peer->hk_peer = hook2->hk_peer;
1156 hook2->hk_peer->hk_peer = hook1->hk_peer;
1158 hook1->hk_peer = &ng_deadhook;
1159 hook2->hk_peer = &ng_deadhook;
1161 NG_HOOK_UNREF(hook1);
1162 NG_HOOK_UNREF(hook2);
1164 /* XXX If we ever cache methods on hooks update them as well */
1165 ng_destroy_hook(hook1);
1166 ng_destroy_hook(hook2);
1171 * Install a new netgraph type
1174 ng_newtype(struct ng_type *tp)
1176 const size_t namelen = strlen(tp->name);
1178 /* Check version and type name fields */
1179 if ((tp->version != NG_ABI_VERSION)
1181 || (namelen >= NG_TYPESIZ)) {
1183 if (tp->version != NG_ABI_VERSION) {
1184 printf("Netgraph: Node type rejected. ABI mismatch. Suggest recompile\n");
1189 /* Check for name collision */
1190 if (ng_findtype(tp->name) != NULL) {
1196 /* Link in new type */
1197 mtx_lock(&ng_typelist_mtx);
1198 LIST_INSERT_HEAD(&ng_typelist, tp, types);
1199 tp->refs = 1; /* first ref is linked list */
1200 mtx_unlock(&ng_typelist_mtx);
1205 * unlink a netgraph type
1206 * If no examples exist
1209 ng_rmtype(struct ng_type *tp)
1211 /* Check for name collision */
1212 if (tp->refs != 1) {
1218 mtx_lock(&ng_typelist_mtx);
1219 LIST_REMOVE(tp, types);
1220 mtx_unlock(&ng_typelist_mtx);
1225 * Look for a type of the name given
1228 ng_findtype(const char *typename)
1230 struct ng_type *type;
1232 mtx_lock(&ng_typelist_mtx);
1233 LIST_FOREACH(type, &ng_typelist, types) {
1234 if (strcmp(type->name, typename) == 0)
1237 mtx_unlock(&ng_typelist_mtx);
1241 /************************************************************************
1243 ************************************************************************/
1245 * Connect two nodes using the specified hooks, using queued functions.
1248 ng_con_part3(node_p node, item_p item, hook_p hook)
1253 * When we run, we know that the node 'node' is locked for us.
1254 * Our caller has a reference on the hook.
1255 * Our caller has a reference on the node.
1256 * (In this case our caller is ng_apply_item() ).
1257 * The peer hook has a reference on the hook.
1258 * We are all set up except for the final call to the node, and
1259 * the clearing of the INVALID flag.
1261 if (NG_HOOK_NODE(hook) == &ng_deadnode) {
1263 * The node must have been freed again since we last visited
1264 * here. ng_destry_hook() has this effect but nothing else does.
1265 * We should just release our references and
1266 * free anything we can think of.
1267 * Since we know it's been destroyed, and it's our caller
1268 * that holds the references, just return.
1272 if (hook->hk_node->nd_type->connect) {
1273 if ((error = (*hook->hk_node->nd_type->connect) (hook))) {
1274 ng_destroy_hook(hook); /* also zaps peer */
1275 printf("failed in ng_con_part3()\n");
1280 * XXX this is wrong for SMP. Possibly we need
1281 * to separate out 'create' and 'invalid' flags.
1282 * should only set flags on hooks we have locked under our node.
1284 hook->hk_flags &= ~HK_INVALID;
1291 ng_con_part2(node_p node, item_p item, hook_p hook)
1297 * When we run, we know that the node 'node' is locked for us.
1298 * Our caller has a reference on the hook.
1299 * Our caller has a reference on the node.
1300 * (In this case our caller is ng_apply_item() ).
1301 * The peer hook has a reference on the hook.
1302 * our node pointer points to the 'dead' node.
1303 * First check the hook name is unique.
1304 * Should not happen because we checked before queueing this.
1306 if (ng_findhook(node, NG_HOOK_NAME(hook)) != NULL) {
1308 ng_destroy_hook(hook); /* should destroy peer too */
1309 printf("failed in ng_con_part2()\n");
1313 * Check if the node type code has something to say about it
1314 * If it fails, the unref of the hook will also unref the attached node,
1315 * however since that node is 'ng_deadnode' this will do nothing.
1316 * The peer hook will also be destroyed.
1318 if (node->nd_type->newhook != NULL) {
1319 if ((error = (*node->nd_type->newhook)(node, hook,
1321 ng_destroy_hook(hook); /* should destroy peer too */
1322 printf("failed in ng_con_part2()\n");
1328 * The 'type' agrees so far, so go ahead and link it in.
1329 * We'll ask again later when we actually connect the hooks.
1331 hook->hk_node = node; /* just overwrite ng_deadnode */
1332 NG_NODE_REF(node); /* each hook counts as a reference */
1333 LIST_INSERT_HEAD(&node->nd_hooks, hook, hk_hooks);
1334 node->nd_numhooks++;
1335 NG_HOOK_REF(hook); /* one for the node */
1338 * We now have a symmetrical situation, where both hooks have been
1339 * linked to their nodes, the newhook methods have been called
1340 * And the references are all correct. The hooks are still marked
1341 * as invalid, as we have not called the 'connect' methods
1343 * We can call the local one immediately as we have the
1344 * node locked, but we need to queue the remote one.
1346 if (hook->hk_node->nd_type->connect) {
1347 if ((error = (*hook->hk_node->nd_type->connect) (hook))) {
1348 ng_destroy_hook(hook); /* also zaps peer */
1349 printf("failed in ng_con_part2(A)\n");
1355 * Acquire topo mutex to avoid race with ng_destroy_hook().
1357 mtx_lock(&ng_topo_mtx);
1358 peer = hook->hk_peer;
1359 if (peer == &ng_deadhook) {
1360 mtx_unlock(&ng_topo_mtx);
1361 printf("failed in ng_con_part2(B)\n");
1362 ng_destroy_hook(hook);
1365 mtx_unlock(&ng_topo_mtx);
1367 if ((error = ng_send_fn2(peer->hk_node, peer, item, &ng_con_part3,
1368 NULL, 0, NG_REUSE_ITEM))) {
1369 printf("failed in ng_con_part2(C)\n");
1370 ng_destroy_hook(hook); /* also zaps peer */
1371 return (error); /* item was consumed. */
1373 hook->hk_flags &= ~HK_INVALID; /* need both to be able to work */
1374 return (0); /* item was consumed. */
1381 * Connect this node with another node. We assume that this node is
1382 * currently locked, as we are only called from an NGM_CONNECT message.
1385 ng_con_nodes(item_p item, node_p node, const char *name,
1386 node_p node2, const char *name2)
1392 if (ng_findhook(node2, name2) != NULL) {
1395 if ((error = ng_add_hook(node, name, &hook))) /* gives us a ref */
1397 /* Allocate the other hook and link it up */
1398 NG_ALLOC_HOOK(hook2);
1399 if (hook2 == NULL) {
1401 ng_destroy_hook(hook); /* XXX check ref counts so far */
1402 NG_HOOK_UNREF(hook); /* including our ref */
1405 hook2->hk_refs = 1; /* start with a reference for us. */
1406 hook2->hk_flags = HK_INVALID;
1407 hook2->hk_peer = hook; /* Link the two together */
1408 hook->hk_peer = hook2;
1409 NG_HOOK_REF(hook); /* Add a ref for the peer to each*/
1411 hook2->hk_node = &ng_deadnode;
1412 strlcpy(NG_HOOK_NAME(hook2), name2, NG_HOOKSIZ);
1415 * Queue the function above.
1416 * Procesing continues in that function in the lock context of
1419 if ((error = ng_send_fn2(node2, hook2, item, &ng_con_part2, NULL, 0,
1421 printf("failed in ng_con_nodes(): %d\n", error);
1422 ng_destroy_hook(hook); /* also zaps peer */
1425 NG_HOOK_UNREF(hook); /* Let each hook go if it wants to */
1426 NG_HOOK_UNREF(hook2);
1431 * Make a peer and connect.
1432 * We assume that the local node is locked.
1433 * The new node probably doesn't need a lock until
1434 * it has a hook, because it cannot really have any work until then,
1435 * but we should think about it a bit more.
1437 * The problem may come if the other node also fires up
1438 * some hardware or a timer or some other source of activation,
1439 * also it may already get a command msg via it's ID.
1441 * We could use the same method as ng_con_nodes() but we'd have
1442 * to add ability to remove the node when failing. (Not hard, just
1443 * make arg1 point to the node to remove).
1444 * Unless of course we just ignore failure to connect and leave
1445 * an unconnected node?
1448 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
1451 hook_p hook1, hook2;
1454 if ((error = ng_make_node(type, &node2))) {
1458 if ((error = ng_add_hook(node, name, &hook1))) { /* gives us a ref */
1459 ng_rmnode(node2, NULL, NULL, 0);
1463 if ((error = ng_add_hook(node2, name2, &hook2))) {
1464 ng_rmnode(node2, NULL, NULL, 0);
1465 ng_destroy_hook(hook1);
1466 NG_HOOK_UNREF(hook1);
1471 * Actually link the two hooks together.
1473 hook1->hk_peer = hook2;
1474 hook2->hk_peer = hook1;
1476 /* Each hook is referenced by the other */
1480 /* Give each node the opportunity to veto the pending connection */
1481 if (hook1->hk_node->nd_type->connect) {
1482 error = (*hook1->hk_node->nd_type->connect) (hook1);
1485 if ((error == 0) && hook2->hk_node->nd_type->connect) {
1486 error = (*hook2->hk_node->nd_type->connect) (hook2);
1491 * drop the references we were holding on the two hooks.
1494 ng_destroy_hook(hook2); /* also zaps hook1 */
1495 ng_rmnode(node2, NULL, NULL, 0);
1497 /* As a last act, allow the hooks to be used */
1498 hook1->hk_flags &= ~HK_INVALID;
1499 hook2->hk_flags &= ~HK_INVALID;
1501 NG_HOOK_UNREF(hook1);
1502 NG_HOOK_UNREF(hook2);
1506 /************************************************************************
1507 Utility routines to send self messages
1508 ************************************************************************/
1510 /* Shut this node down as soon as everyone is clear of it */
1511 /* Should add arg "immediately" to jump the queue */
1513 ng_rmnode_self(node_p node)
1517 if (node == &ng_deadnode)
1519 node->nd_flags |= NGF_INVALID;
1520 if (node->nd_flags & NGF_CLOSING)
1523 error = ng_send_fn(node, NULL, &ng_rmnode, NULL, 0);
1528 ng_rmhook_part2(node_p node, hook_p hook, void *arg1, int arg2)
1530 ng_destroy_hook(hook);
1535 ng_rmhook_self(hook_p hook)
1538 node_p node = NG_HOOK_NODE(hook);
1540 if (node == &ng_deadnode)
1543 error = ng_send_fn(node, hook, &ng_rmhook_part2, NULL, 0);
1547 /***********************************************************************
1548 * Parse and verify a string of the form: <NODE:><PATH>
1550 * Such a string can refer to a specific node or a specific hook
1551 * on a specific node, depending on how you look at it. In the
1552 * latter case, the PATH component must not end in a dot.
1554 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
1555 * of hook names separated by dots. This breaks out the original
1556 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
1557 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
1558 * the final hook component of <PATH>, if any, otherwise NULL.
1560 * This returns -1 if the path is malformed. The char ** are optional.
1561 ***********************************************************************/
1563 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
1565 char *node, *path, *hook;
1569 * Extract absolute NODE, if any
1571 for (path = addr; *path && *path != ':'; path++);
1573 node = addr; /* Here's the NODE */
1574 *path++ = '\0'; /* Here's the PATH */
1576 /* Node name must not be empty */
1580 /* A name of "." is OK; otherwise '.' not allowed */
1581 if (strcmp(node, ".") != 0) {
1582 for (k = 0; node[k]; k++)
1587 node = NULL; /* No absolute NODE */
1588 path = addr; /* Here's the PATH */
1591 /* Snoop for illegal characters in PATH */
1592 for (k = 0; path[k]; k++)
1596 /* Check for no repeated dots in PATH */
1597 for (k = 0; path[k]; k++)
1598 if (path[k] == '.' && path[k + 1] == '.')
1601 /* Remove extra (degenerate) dots from beginning or end of PATH */
1604 if (*path && path[strlen(path) - 1] == '.')
1605 path[strlen(path) - 1] = 0;
1607 /* If PATH has a dot, then we're not talking about a hook */
1609 for (hook = path, k = 0; path[k]; k++)
1610 if (path[k] == '.') {
1628 * Given a path, which may be absolute or relative, and a starting node,
1629 * return the destination node.
1632 ng_path2noderef(node_p here, const char *address,
1633 node_p *destp, hook_p *lasthook)
1635 char fullpath[NG_PATHSIZ];
1636 char *nodename, *path, pbuf[2];
1637 node_p node, oldnode;
1642 if (destp == NULL) {
1648 /* Make a writable copy of address for ng_path_parse() */
1649 strncpy(fullpath, address, sizeof(fullpath) - 1);
1650 fullpath[sizeof(fullpath) - 1] = '\0';
1652 /* Parse out node and sequence of hooks */
1653 if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
1658 pbuf[0] = '.'; /* Needs to be writable */
1664 * For an absolute address, jump to the starting node.
1665 * Note that this holds a reference on the node for us.
1666 * Don't forget to drop the reference if we don't need it.
1669 node = ng_name2noderef(here, nodename);
1684 * Now follow the sequence of hooks
1686 * We actually cannot guarantee that the sequence
1687 * is not being demolished as we crawl along it
1688 * without extra-ordinary locking etc.
1689 * So this is a bit dodgy to say the least.
1690 * We can probably hold up some things by holding
1691 * the nodelist mutex for the time of this
1692 * crawl if we wanted.. At least that way we wouldn't have to
1693 * worry about the nodes disappearing, but the hooks would still
1696 for (cp = path; node != NULL && *cp != '\0'; ) {
1700 * Break out the next path segment. Replace the dot we just
1701 * found with a NUL; "cp" points to the next segment (or the
1704 for (segment = cp; *cp != '\0'; cp++) {
1712 if (*segment == '\0')
1715 /* We have a segment, so look for a hook by that name */
1716 hook = ng_findhook(node, segment);
1718 /* Can't get there from here... */
1720 || NG_HOOK_PEER(hook) == NULL
1721 || NG_HOOK_NOT_VALID(hook)
1722 || NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook))) {
1724 NG_NODE_UNREF(node);
1726 printf("hooknotvalid %s %s %d %d %d %d ",
1730 NG_HOOK_PEER(hook) == NULL,
1731 NG_HOOK_NOT_VALID(hook),
1732 NG_HOOK_NOT_VALID(NG_HOOK_PEER(hook)));
1738 * Hop on over to the next node
1740 * Big race conditions here as hooks and nodes go away
1741 * *** Idea.. store an ng_ID_t in each hook and use that
1742 * instead of the direct hook in this crawl?
1745 if ((node = NG_PEER_NODE(hook)))
1746 NG_NODE_REF(node); /* XXX RACE */
1747 NG_NODE_UNREF(oldnode); /* XXX another race */
1748 if (NG_NODE_NOT_VALID(node)) {
1749 NG_NODE_UNREF(node); /* XXX more races */
1754 /* If node somehow missing, fail here (probably this is not needed) */
1762 if (lasthook != NULL)
1763 *lasthook = (hook ? NG_HOOK_PEER(hook) : NULL);
1767 /***************************************************************\
1768 * Input queue handling.
1769 * All activities are submitted to the node via the input queue
1770 * which implements a multiple-reader/single-writer gate.
1771 * Items which cannot be handled immediately are queued.
1773 * read-write queue locking inline functions *
1774 \***************************************************************/
1776 static __inline void ng_queue_rw(node_p node, item_p item, int rw);
1777 static __inline item_p ng_dequeue(node_p node, int *rw);
1778 static __inline item_p ng_acquire_read(node_p node, item_p item);
1779 static __inline item_p ng_acquire_write(node_p node, item_p item);
1780 static __inline void ng_leave_read(node_p node);
1781 static __inline void ng_leave_write(node_p node);
1784 * Definition of the bits fields in the ng_queue flag word.
1785 * Defined here rather than in netgraph.h because no-one should fiddle
1788 * The ordering here may be important! don't shuffle these.
1791 Safety Barrier--------+ (adjustable to suit taste) (not used yet)
1794 +-------+-------+-------+-------+-------+-------+-------+-------+
1795 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
1796 | |A|c|t|i|v|e| |R|e|a|d|e|r| |C|o|u|n|t| | | | | | | | | |P|A|
1797 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |O|W|
1798 +-------+-------+-------+-------+-------+-------+-------+-------+
1799 \___________________________ ____________________________/ | |
1801 [active reader count] | |
1803 Operation Pending -------------------------------+ |
1805 Active Writer ---------------------------------------+
1807 Node queue has such semantics:
1808 - All flags modifications are atomic.
1809 - Reader count can be incremented only if there is no writer or pending flags.
1810 As soon as this can't be done with single operation, it is implemented with
1811 spin loop and atomic_cmpset().
1812 - Writer flag can be set only if there is no any bits set.
1813 It is implemented with atomic_cmpset().
1814 - Pending flag can be set any time, but to avoid collision on queue processing
1815 all queue fields are protected by the mutex.
1816 - Queue processing thread reads queue holding the mutex, but releases it while
1817 processing. When queue is empty pending flag is removed.
1820 #define WRITER_ACTIVE 0x00000001
1821 #define OP_PENDING 0x00000002
1822 #define READER_INCREMENT 0x00000004
1823 #define READER_MASK 0xfffffffc /* Not valid if WRITER_ACTIVE is set */
1824 #define SAFETY_BARRIER 0x00100000 /* 128K items queued should be enough */
1826 /* Defines of more elaborate states on the queue */
1827 /* Mask of bits a new read cares about */
1828 #define NGQ_RMASK (WRITER_ACTIVE|OP_PENDING)
1830 /* Mask of bits a new write cares about */
1831 #define NGQ_WMASK (NGQ_RMASK|READER_MASK)
1833 /* Test to decide if there is something on the queue. */
1834 #define QUEUE_ACTIVE(QP) ((QP)->q_flags & OP_PENDING)
1836 /* How to decide what the next queued item is. */
1837 #define HEAD_IS_READER(QP) NGI_QUEUED_READER(STAILQ_FIRST(&(QP)->queue))
1838 #define HEAD_IS_WRITER(QP) NGI_QUEUED_WRITER(STAILQ_FIRST(&(QP)->queue)) /* notused */
1840 /* Read the status to decide if the next item on the queue can now run. */
1841 #define QUEUED_READER_CAN_PROCEED(QP) \
1842 (((QP)->q_flags & (NGQ_RMASK & ~OP_PENDING)) == 0)
1843 #define QUEUED_WRITER_CAN_PROCEED(QP) \
1844 (((QP)->q_flags & (NGQ_WMASK & ~OP_PENDING)) == 0)
1846 /* Is there a chance of getting ANY work off the queue? */
1847 #define NEXT_QUEUED_ITEM_CAN_PROCEED(QP) \
1848 ((HEAD_IS_READER(QP)) ? QUEUED_READER_CAN_PROCEED(QP) : \
1849 QUEUED_WRITER_CAN_PROCEED(QP))
1854 #define NGQ2_WORKQ 0x00000001
1857 * Taking into account the current state of the queue and node, possibly take
1858 * the next entry off the queue and return it. Return NULL if there was
1859 * nothing we could return, either because there really was nothing there, or
1860 * because the node was in a state where it cannot yet process the next item
1863 static __inline item_p
1864 ng_dequeue(node_p node, int *rw)
1867 struct ng_queue *ngq = &node->nd_input_queue;
1869 /* This MUST be called with the mutex held. */
1870 KKASSERT(mtx_owned(&ngq->q_mtx));
1872 /* If there is nothing queued, then just return. */
1873 if (!QUEUE_ACTIVE(ngq)) {
1874 CTR4(KTR_NET, "%20s: node [%x] (%p) queue empty; "
1875 "queue flags 0x%lx", __func__,
1876 node->nd_ID, node, ngq->q_flags);
1881 * From here, we can assume there is a head item.
1882 * We need to find out what it is and if it can be dequeued, given
1883 * the current state of the node.
1885 if (HEAD_IS_READER(ngq)) {
1887 long t = ngq->q_flags;
1888 if (t & WRITER_ACTIVE) {
1889 /* There is writer, reader can't proceed. */
1890 CTR4(KTR_NET, "%20s: node [%x] (%p) queued reader "
1891 "can't proceed; queue flags 0x%lx", __func__,
1892 node->nd_ID, node, t);
1895 if (atomic_cmpset_acq_int(&ngq->q_flags, t,
1896 t + READER_INCREMENT))
1900 /* We have got reader lock for the node. */
1902 } else if (atomic_cmpset_acq_int(&ngq->q_flags, OP_PENDING,
1903 OP_PENDING + WRITER_ACTIVE)) {
1904 /* We have got writer lock for the node. */
1907 /* There is somebody other, writer can't proceed. */
1908 CTR4(KTR_NET, "%20s: node [%x] (%p) queued writer "
1909 "can't proceed; queue flags 0x%lx", __func__,
1910 node->nd_ID, node, ngq->q_flags);
1915 * Now we dequeue the request (whatever it may be) and correct the
1916 * pending flags and the next and last pointers.
1918 item = STAILQ_FIRST(&ngq->queue);
1919 STAILQ_REMOVE_HEAD(&ngq->queue, el_next);
1920 if (STAILQ_EMPTY(&ngq->queue))
1921 atomic_clear_int(&ngq->q_flags, OP_PENDING);
1922 CTR6(KTR_NET, "%20s: node [%x] (%p) returning item %p as %s; "
1923 "queue flags 0x%lx", __func__,
1924 node->nd_ID, node, item, *rw ? "WRITER" : "READER" ,
1930 * Queue a packet to be picked up later by someone else.
1931 * If the queue could be run now, add node to the queue handler's worklist.
1933 static __inline void
1934 ng_queue_rw(node_p node, item_p item, int rw)
1936 struct ng_queue *ngq = &node->nd_input_queue;
1938 NGI_SET_WRITER(item);
1940 NGI_SET_READER(item);
1943 /* Set OP_PENDING flag and enqueue the item. */
1944 atomic_set_int(&ngq->q_flags, OP_PENDING);
1945 STAILQ_INSERT_TAIL(&ngq->queue, item, el_next);
1947 CTR5(KTR_NET, "%20s: node [%x] (%p) queued item %p as %s", __func__,
1948 node->nd_ID, node, item, rw ? "WRITER" : "READER" );
1951 * We can take the worklist lock with the node locked
1952 * BUT NOT THE REVERSE!
1954 if (NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
1955 ng_worklist_add(node);
1956 NG_QUEUE_UNLOCK(ngq);
1959 /* Acquire reader lock on node. If node is busy, queue the packet. */
1960 static __inline item_p
1961 ng_acquire_read(node_p node, item_p item)
1963 KASSERT(node != &ng_deadnode,
1964 ("%s: working on deadnode", __func__));
1966 /* Reader needs node without writer and pending items. */
1968 long t = node->nd_input_queue.q_flags;
1970 break; /* Node is not ready for reader. */
1971 if (atomic_cmpset_acq_int(&node->nd_input_queue.q_flags,
1972 t, t + READER_INCREMENT)) {
1973 /* Successfully grabbed node */
1974 CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
1975 __func__, node->nd_ID, node, item);
1981 /* Queue the request for later. */
1982 ng_queue_rw(node, item, NGQRW_R);
1987 /* Acquire writer lock on node. If node is busy, queue the packet. */
1988 static __inline item_p
1989 ng_acquire_write(node_p node, item_p item)
1991 KASSERT(node != &ng_deadnode,
1992 ("%s: working on deadnode", __func__));
1994 /* Writer needs completely idle node. */
1995 if (atomic_cmpset_acq_int(&node->nd_input_queue.q_flags,
1996 0, WRITER_ACTIVE)) {
1997 /* Successfully grabbed node */
1998 CTR4(KTR_NET, "%20s: node [%x] (%p) acquired item %p",
1999 __func__, node->nd_ID, node, item);
2003 /* Queue the request for later. */
2004 ng_queue_rw(node, item, NGQRW_W);
2010 static __inline item_p
2011 ng_upgrade_write(node_p node, item_p item)
2013 struct ng_queue *ngq = &node->nd_input_queue;
2014 KASSERT(node != &ng_deadnode,
2015 ("%s: working on deadnode", __func__));
2017 NGI_SET_WRITER(item);
2022 * There will never be no readers as we are there ourselves.
2023 * Set the WRITER_ACTIVE flags ASAP to block out fast track readers.
2024 * The caller we are running from will call ng_leave_read()
2025 * soon, so we must account for that. We must leave again with the
2026 * READER lock. If we find other readers, then
2027 * queue the request for later. However "later" may be rignt now
2028 * if there are no readers. We don't really care if there are queued
2029 * items as we will bypass them anyhow.
2031 atomic_add_int(&ngq->q_flags, WRITER_ACTIVE - READER_INCREMENT);
2032 if ((ngq->q_flags & (NGQ_WMASK & ~OP_PENDING)) == WRITER_ACTIVE) {
2033 NG_QUEUE_UNLOCK(ngq);
2035 /* It's just us, act on the item. */
2036 /* will NOT drop writer lock when done */
2037 ng_apply_item(node, item, 0);
2040 * Having acted on the item, atomically
2041 * down grade back to READER and finish up
2043 atomic_add_int(&ngq->q_flags,
2044 READER_INCREMENT - WRITER_ACTIVE);
2046 /* Our caller will call ng_leave_read() */
2050 * It's not just us active, so queue us AT THE HEAD.
2051 * "Why?" I hear you ask.
2052 * Put us at the head of the queue as we've already been
2053 * through it once. If there is nothing else waiting,
2054 * set the correct flags.
2056 if (STAILQ_EMPTY(&ngq->queue)) {
2057 /* We've gone from, 0 to 1 item in the queue */
2058 atomic_set_int(&ngq->q_flags, OP_PENDING);
2060 CTR3(KTR_NET, "%20s: node [%x] (%p) set OP_PENDING", __func__,
2063 STAILQ_INSERT_HEAD(&ngq->queue, item, el_next);
2064 CTR4(KTR_NET, "%20s: node [%x] (%p) requeued item %p as WRITER",
2065 __func__, node->nd_ID, node, item );
2067 /* Reverse what we did above. That downgrades us back to reader */
2068 atomic_add_int(&ngq->q_flags, READER_INCREMENT - WRITER_ACTIVE);
2069 if (QUEUE_ACTIVE(ngq) && NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2070 ng_worklist_add(node);
2071 NG_QUEUE_UNLOCK(ngq);
2077 /* Release reader lock. */
2078 static __inline void
2079 ng_leave_read(node_p node)
2081 atomic_subtract_rel_int(&node->nd_input_queue.q_flags, READER_INCREMENT);
2084 /* Release writer lock. */
2085 static __inline void
2086 ng_leave_write(node_p node)
2088 atomic_clear_rel_int(&node->nd_input_queue.q_flags, WRITER_ACTIVE);
2091 /* Purge node queue. Called on node shutdown. */
2093 ng_flush_input_queue(node_p node)
2095 struct ng_queue *ngq = &node->nd_input_queue;
2099 while ((item = STAILQ_FIRST(&ngq->queue)) != NULL) {
2100 STAILQ_REMOVE_HEAD(&ngq->queue, el_next);
2101 if (STAILQ_EMPTY(&ngq->queue))
2102 atomic_clear_int(&ngq->q_flags, OP_PENDING);
2103 NG_QUEUE_UNLOCK(ngq);
2105 /* If the item is supplying a callback, call it with an error */
2106 if (item->apply != NULL) {
2107 if (item->depth == 1)
2108 item->apply->error = ENOENT;
2109 if (refcount_release(&item->apply->refs)) {
2110 (*item->apply->apply)(item->apply->context,
2111 item->apply->error);
2117 NG_QUEUE_UNLOCK(ngq);
2120 /***********************************************************************
2121 * Externally visible method for sending or queueing messages or data.
2122 ***********************************************************************/
2125 * The module code should have filled out the item correctly by this stage:
2127 * reference to destination node.
2128 * Reference to destination rcv hook if relevant.
2129 * apply pointer must be or NULL or reference valid struct ng_apply_info.
2134 * ID of original sender node. (return address)
2140 * The nodes have several routines and macros to help with this task:
2144 ng_snd_item(item_p item, int flags)
2149 struct ng_queue *ngq;
2152 /* We are sending item, so it must be present! */
2153 KASSERT(item != NULL, ("ng_snd_item: item is NULL"));
2155 #ifdef NETGRAPH_DEBUG
2156 _ngi_check(item, __FILE__, __LINE__);
2159 /* Item was sent once more, postpone apply() call. */
2161 refcount_acquire(&item->apply->refs);
2163 node = NGI_NODE(item);
2164 /* Node is never optional. */
2165 KASSERT(node != NULL, ("ng_snd_item: node is NULL"));
2167 hook = NGI_HOOK(item);
2168 /* Valid hook and mbuf are mandatory for data. */
2169 if ((item->el_flags & NGQF_TYPE) == NGQF_DATA) {
2170 KASSERT(hook != NULL, ("ng_snd_item: hook for data is NULL"));
2171 if (NGI_M(item) == NULL)
2173 CHECK_DATA_MBUF(NGI_M(item));
2177 * If the item or the node specifies single threading, force
2178 * writer semantics. Similarly, the node may say one hook always
2179 * produces writers. These are overrides.
2181 if (((item->el_flags & NGQF_RW) == NGQF_WRITER) ||
2182 (node->nd_flags & NGF_FORCE_WRITER) ||
2183 (hook && (hook->hk_flags & HK_FORCE_WRITER))) {
2190 * If sender or receiver requests queued delivery or stack usage
2191 * level is dangerous - enqueue message.
2193 if ((flags & NG_QUEUE) || (hook && (hook->hk_flags & HK_QUEUE))) {
2197 #ifdef GET_STACK_USAGE
2199 * Most of netgraph nodes have small stack consumption and
2200 * for them 25% of free stack space is more than enough.
2201 * Nodes/hooks with higher stack usage should be marked as
2202 * HI_STACK. For them 50% of stack will be guaranteed then.
2203 * XXX: Values 25% and 50% are completely empirical.
2206 GET_STACK_USAGE(st, su);
2208 if ((sl * 4 < st) ||
2209 ((sl * 2 < st) && ((node->nd_flags & NGF_HI_STACK) ||
2210 (hook && (hook->hk_flags & HK_HI_STACK))))) {
2218 /* Put it on the queue for that node*/
2219 ng_queue_rw(node, item, rw);
2220 return ((flags & NG_PROGRESS) ? EINPROGRESS : 0);
2224 * We already decided how we will be queueud or treated.
2225 * Try get the appropriate operating permission.
2228 item = ng_acquire_read(node, item);
2230 item = ng_acquire_write(node, item);
2232 /* Item was queued while trying to get permission. */
2234 return ((flags & NG_PROGRESS) ? EINPROGRESS : 0);
2236 NGI_GET_NODE(item, node); /* zaps stored node */
2239 error = ng_apply_item(node, item, rw); /* drops r/w lock when done */
2241 /* If something is waiting on queue and ready, schedule it. */
2242 ngq = &node->nd_input_queue;
2243 if (QUEUE_ACTIVE(ngq)) {
2245 if (QUEUE_ACTIVE(ngq) && NEXT_QUEUED_ITEM_CAN_PROCEED(ngq))
2246 ng_worklist_add(node);
2247 NG_QUEUE_UNLOCK(ngq);
2251 * Node may go away as soon as we remove the reference.
2252 * Whatever we do, DO NOT access the node again!
2254 NG_NODE_UNREF(node);
2259 /* If was not sent, apply callback here. */
2260 if (item->apply != NULL) {
2261 if (item->depth == 0 && error != 0)
2262 item->apply->error = error;
2263 if (refcount_release(&item->apply->refs)) {
2264 (*item->apply->apply)(item->apply->context,
2265 item->apply->error);
2274 * We have an item that was possibly queued somewhere.
2275 * It should contain all the information needed
2276 * to run it on the appropriate node/hook.
2277 * If there is apply pointer and we own the last reference, call apply().
2280 ng_apply_item(node_p node, item_p item, int rw)
2283 ng_rcvdata_t *rcvdata;
2284 ng_rcvmsg_t *rcvmsg;
2285 struct ng_apply_info *apply;
2286 int error = 0, depth;
2288 /* Node and item are never optional. */
2289 KASSERT(node != NULL, ("ng_apply_item: node is NULL"));
2290 KASSERT(item != NULL, ("ng_apply_item: item is NULL"));
2292 NGI_GET_HOOK(item, hook); /* clears stored hook */
2293 #ifdef NETGRAPH_DEBUG
2294 _ngi_check(item, __FILE__, __LINE__);
2297 apply = item->apply;
2298 depth = item->depth;
2300 switch (item->el_flags & NGQF_TYPE) {
2303 * Check things are still ok as when we were queued.
2305 KASSERT(hook != NULL, ("ng_apply_item: hook for data is NULL"));
2306 if (NG_HOOK_NOT_VALID(hook) ||
2307 NG_NODE_NOT_VALID(node)) {
2313 * If no receive method, just silently drop it.
2314 * Give preference to the hook over-ride method
2316 if ((!(rcvdata = hook->hk_rcvdata))
2317 && (!(rcvdata = NG_HOOK_NODE(hook)->nd_type->rcvdata))) {
2322 error = (*rcvdata)(hook, item);
2325 if (hook && NG_HOOK_NOT_VALID(hook)) {
2327 * The hook has been zapped then we can't use it.
2328 * Immediately drop its reference.
2329 * The message may not need it.
2331 NG_HOOK_UNREF(hook);
2335 * Similarly, if the node is a zombie there is
2336 * nothing we can do with it, drop everything.
2338 if (NG_NODE_NOT_VALID(node)) {
2345 * Call the appropriate message handler for the object.
2346 * It is up to the message handler to free the message.
2347 * If it's a generic message, handle it generically,
2348 * otherwise call the type's message handler (if it exists).
2349 * XXX (race). Remember that a queued message may
2350 * reference a node or hook that has just been
2351 * invalidated. It will exist as the queue code
2352 * is holding a reference, but..
2354 if ((NGI_MSG(item)->header.typecookie == NGM_GENERIC_COOKIE) &&
2355 ((NGI_MSG(item)->header.flags & NGF_RESP) == 0)) {
2356 error = ng_generic_msg(node, item, hook);
2359 if (((!hook) || (!(rcvmsg = hook->hk_rcvmsg))) &&
2360 (!(rcvmsg = node->nd_type->rcvmsg))) {
2366 error = (*rcvmsg)(node, item, hook);
2371 * We have to implicitly trust the hook,
2372 * as some of these are used for system purposes
2373 * where the hook is invalid. In the case of
2374 * the shutdown message we allow it to hit
2375 * even if the node is invalid.
2377 if ((NG_NODE_NOT_VALID(node))
2378 && (NGI_FN(item) != &ng_rmnode)) {
2384 if ((item->el_flags & NGQF_TYPE) == NGQF_FN) {
2385 (*NGI_FN(item))(node, hook, NGI_ARG1(item),
2388 } else /* it is NGQF_FN2 */
2389 error = (*NGI_FN2(item))(node, item, hook);
2393 * We held references on some of the resources
2394 * that we took from the item. Now that we have
2395 * finished doing everything, drop those references.
2398 NG_HOOK_UNREF(hook);
2401 ng_leave_read(node);
2403 ng_leave_write(node);
2405 /* Apply callback. */
2406 if (apply != NULL) {
2407 if (depth == 1 && error != 0)
2408 apply->error = error;
2409 if (refcount_release(&apply->refs))
2410 (*apply->apply)(apply->context, apply->error);
2416 /***********************************************************************
2417 * Implement the 'generic' control messages
2418 ***********************************************************************/
2420 ng_generic_msg(node_p here, item_p item, hook_p lasthook)
2423 struct ng_mesg *msg;
2424 struct ng_mesg *resp = NULL;
2426 NGI_GET_MSG(item, msg);
2427 if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
2432 switch (msg->header.cmd) {
2434 ng_rmnode(here, NULL, NULL, 0);
2438 struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
2440 if (msg->header.arglen != sizeof(*mkp)) {
2445 mkp->type[sizeof(mkp->type) - 1] = '\0';
2446 mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
2447 mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
2448 error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
2453 struct ngm_connect *const con =
2454 (struct ngm_connect *) msg->data;
2457 if (msg->header.arglen != sizeof(*con)) {
2462 con->path[sizeof(con->path) - 1] = '\0';
2463 con->ourhook[sizeof(con->ourhook) - 1] = '\0';
2464 con->peerhook[sizeof(con->peerhook) - 1] = '\0';
2465 /* Don't forget we get a reference.. */
2466 error = ng_path2noderef(here, con->path, &node2, NULL);
2469 error = ng_con_nodes(item, here, con->ourhook,
2470 node2, con->peerhook);
2471 NG_NODE_UNREF(node2);
2476 struct ngm_name *const nam = (struct ngm_name *) msg->data;
2478 if (msg->header.arglen != sizeof(*nam)) {
2483 nam->name[sizeof(nam->name) - 1] = '\0';
2484 error = ng_name_node(here, nam->name);
2489 struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
2492 if (msg->header.arglen != sizeof(*rmh)) {
2497 rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
2498 if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
2499 ng_destroy_hook(hook);
2504 struct nodeinfo *ni;
2506 NG_MKRESPONSE(resp, msg, sizeof(*ni), M_WAITOK | M_NULLOK);
2512 /* Fill in node info */
2513 ni = (struct nodeinfo *) resp->data;
2514 if (NG_NODE_HAS_NAME(here))
2515 strcpy(ni->name, NG_NODE_NAME(here));
2516 strcpy(ni->type, here->nd_type->name);
2517 ni->id = ng_node2ID(here);
2518 ni->hooks = here->nd_numhooks;
2523 const int nhooks = here->nd_numhooks;
2524 struct hooklist *hl;
2525 struct nodeinfo *ni;
2528 /* Get response struct */
2529 NG_MKRESPONSE(resp, msg, sizeof(*hl)
2530 + (nhooks * sizeof(struct linkinfo)), M_WAITOK | M_NULLOK);
2535 hl = (struct hooklist *) resp->data;
2538 /* Fill in node info */
2539 if (NG_NODE_HAS_NAME(here))
2540 strcpy(ni->name, NG_NODE_NAME(here));
2541 strcpy(ni->type, here->nd_type->name);
2542 ni->id = ng_node2ID(here);
2544 /* Cycle through the linked list of hooks */
2546 LIST_FOREACH(hook, &here->nd_hooks, hk_hooks) {
2547 struct linkinfo *const link = &hl->link[ni->hooks];
2549 if (ni->hooks >= nhooks) {
2550 log(LOG_ERR, "%s: number of %s changed\n",
2554 if (NG_HOOK_NOT_VALID(hook))
2556 strcpy(link->ourhook, NG_HOOK_NAME(hook));
2557 strcpy(link->peerhook, NG_PEER_HOOK_NAME(hook));
2558 if (NG_PEER_NODE_NAME(hook)[0] != '\0')
2559 strcpy(link->nodeinfo.name,
2560 NG_PEER_NODE_NAME(hook));
2561 strcpy(link->nodeinfo.type,
2562 NG_PEER_NODE(hook)->nd_type->name);
2563 link->nodeinfo.id = ng_node2ID(NG_PEER_NODE(hook));
2564 link->nodeinfo.hooks = NG_PEER_NODE(hook)->nd_numhooks;
2573 const int unnamed = (msg->header.cmd == NGM_LISTNODES);
2574 struct namelist *nl;
2578 mtx_lock(&ng_namehash_mtx);
2579 /* Count number of nodes */
2580 for (i = 0; i < NG_NAME_HASH_SIZE; i++) {
2581 LIST_FOREACH(node, &ng_name_hash[i], nd_nodes) {
2582 if (NG_NODE_IS_VALID(node) &&
2583 (unnamed || NG_NODE_HAS_NAME(node))) {
2588 mtx_unlock(&ng_namehash_mtx);
2590 /* Get response struct */
2591 NG_MKRESPONSE(resp, msg, sizeof(*nl)
2592 + (num * sizeof(struct nodeinfo)), M_WAITOK | M_NULLOK);
2597 nl = (struct namelist *) resp->data;
2599 /* Cycle through the linked list of nodes */
2601 mtx_lock(&ng_namehash_mtx);
2602 for (i = 0; i < NG_NAME_HASH_SIZE; i++) {
2603 LIST_FOREACH(node, &ng_name_hash[i], nd_nodes) {
2604 struct nodeinfo *const np =
2605 &nl->nodeinfo[nl->numnames];
2607 if (NG_NODE_NOT_VALID(node))
2609 if (!unnamed && (! NG_NODE_HAS_NAME(node)))
2611 if (nl->numnames >= num) {
2612 log(LOG_ERR, "%s: number of nodes changed\n",
2616 if (NG_NODE_HAS_NAME(node))
2617 strcpy(np->name, NG_NODE_NAME(node));
2618 strcpy(np->type, node->nd_type->name);
2619 np->id = ng_node2ID(node);
2620 np->hooks = node->nd_numhooks;
2624 mtx_unlock(&ng_namehash_mtx);
2630 struct typelist *tl;
2631 struct ng_type *type;
2634 mtx_lock(&ng_typelist_mtx);
2635 /* Count number of types */
2636 LIST_FOREACH(type, &ng_typelist, types) {
2639 mtx_unlock(&ng_typelist_mtx);
2641 /* Get response struct */
2642 NG_MKRESPONSE(resp, msg, sizeof(*tl)
2643 + (num * sizeof(struct typeinfo)), M_WAITOK | M_NULLOK);
2648 tl = (struct typelist *) resp->data;
2650 /* Cycle through the linked list of types */
2652 mtx_lock(&ng_typelist_mtx);
2653 LIST_FOREACH(type, &ng_typelist, types) {
2654 struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
2656 if (tl->numtypes >= num) {
2657 log(LOG_ERR, "%s: number of %s changed\n",
2661 strcpy(tp->type_name, type->name);
2662 tp->numnodes = type->refs - 1; /* don't count list */
2665 mtx_unlock(&ng_typelist_mtx);
2669 case NGM_BINARY2ASCII:
2671 int bufSize = 20 * 1024; /* XXX hard coded constant */
2672 const struct ng_parse_type *argstype;
2673 const struct ng_cmdlist *c;
2674 struct ng_mesg *binary, *ascii;
2676 /* Data area must contain a valid netgraph message */
2677 binary = (struct ng_mesg *)msg->data;
2678 if (msg->header.arglen < sizeof(struct ng_mesg) ||
2679 (msg->header.arglen - sizeof(struct ng_mesg) <
2680 binary->header.arglen)) {
2686 /* Get a response message with lots of room */
2687 NG_MKRESPONSE(resp, msg, sizeof(*ascii) + bufSize, M_WAITOK | M_NULLOK);
2692 ascii = (struct ng_mesg *)resp->data;
2694 /* Copy binary message header to response message payload */
2695 bcopy(binary, ascii, sizeof(*binary));
2697 /* Find command by matching typecookie and command number */
2698 for (c = here->nd_type->cmdlist;
2699 c != NULL && c->name != NULL; c++) {
2700 if (binary->header.typecookie == c->cookie
2701 && binary->header.cmd == c->cmd)
2704 if (c == NULL || c->name == NULL) {
2705 for (c = ng_generic_cmds; c->name != NULL; c++) {
2706 if (binary->header.typecookie == c->cookie
2707 && binary->header.cmd == c->cmd)
2710 if (c->name == NULL) {
2717 /* Convert command name to ASCII */
2718 snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
2721 /* Convert command arguments to ASCII */
2722 argstype = (binary->header.flags & NGF_RESP) ?
2723 c->respType : c->mesgType;
2724 if (argstype == NULL) {
2725 *ascii->data = '\0';
2727 if ((error = ng_unparse(argstype,
2728 (u_char *)binary->data,
2729 ascii->data, bufSize)) != 0) {
2735 /* Return the result as struct ng_mesg plus ASCII string */
2736 bufSize = strlen(ascii->data) + 1;
2737 ascii->header.arglen = bufSize;
2738 resp->header.arglen = sizeof(*ascii) + bufSize;
2742 case NGM_ASCII2BINARY:
2744 int bufSize = 2000; /* XXX hard coded constant */
2745 const struct ng_cmdlist *c;
2746 const struct ng_parse_type *argstype;
2747 struct ng_mesg *ascii, *binary;
2750 /* Data area must contain at least a struct ng_mesg + '\0' */
2751 ascii = (struct ng_mesg *)msg->data;
2752 if ((msg->header.arglen < sizeof(*ascii) + 1) ||
2753 (ascii->header.arglen < 1) ||
2754 (msg->header.arglen < sizeof(*ascii) +
2755 ascii->header.arglen)) {
2760 ascii->data[ascii->header.arglen - 1] = '\0';
2762 /* Get a response message with lots of room */
2763 NG_MKRESPONSE(resp, msg, sizeof(*binary) + bufSize, M_WAITOK | M_NULLOK);
2768 binary = (struct ng_mesg *)resp->data;
2770 /* Copy ASCII message header to response message payload */
2771 bcopy(ascii, binary, sizeof(*ascii));
2773 /* Find command by matching ASCII command string */
2774 for (c = here->nd_type->cmdlist;
2775 c != NULL && c->name != NULL; c++) {
2776 if (strcmp(ascii->header.cmdstr, c->name) == 0)
2779 if (c == NULL || c->name == NULL) {
2780 for (c = ng_generic_cmds; c->name != NULL; c++) {
2781 if (strcmp(ascii->header.cmdstr, c->name) == 0)
2784 if (c->name == NULL) {
2791 /* Convert command name to binary */
2792 binary->header.cmd = c->cmd;
2793 binary->header.typecookie = c->cookie;
2795 /* Convert command arguments to binary */
2796 argstype = (binary->header.flags & NGF_RESP) ?
2797 c->respType : c->mesgType;
2798 if (argstype == NULL) {
2801 if ((error = ng_parse(argstype, ascii->data,
2802 &off, (u_char *)binary->data, &bufSize)) != 0) {
2808 /* Return the result */
2809 binary->header.arglen = bufSize;
2810 resp->header.arglen = sizeof(*binary) + bufSize;
2814 case NGM_TEXT_CONFIG:
2815 case NGM_TEXT_STATUS:
2817 * This one is tricky as it passes the command down to the
2818 * actual node, even though it is a generic type command.
2819 * This means we must assume that the item/msg is already freed
2820 * when control passes back to us.
2822 if (here->nd_type->rcvmsg != NULL) {
2823 NGI_MSG(item) = msg; /* put it back as we found it */
2824 return((*here->nd_type->rcvmsg)(here, item, lasthook));
2826 /* Fall through if rcvmsg not supported */
2832 * Sometimes a generic message may be statically allocated
2833 * to avoid problems with allocating when in tight memeory situations.
2834 * Don't free it if it is so.
2835 * I break them appart here, because erros may cause a free if the item
2836 * in which case we'd be doing it twice.
2837 * they are kept together above, to simplify freeing.
2840 NG_RESPOND_MSG(error, here, item, resp);
2846 /************************************************************************
2847 Queue element get/free routines
2848 ************************************************************************/
2850 uma_zone_t ng_qzone;
2851 uma_zone_t ng_qdzone;
2852 static int maxalloc = 4096;/* limit the damage of a leak */
2853 static int maxdata = 512; /* limit the damage of a DoS */
2855 TUNABLE_INT("net.graph.maxalloc", &maxalloc);
2856 SYSCTL_INT(_net_graph, OID_AUTO, maxalloc, CTLFLAG_RDTUN, &maxalloc,
2857 0, "Maximum number of non-data queue items to allocate");
2858 TUNABLE_INT("net.graph.maxdata", &maxdata);
2859 SYSCTL_INT(_net_graph, OID_AUTO, maxdata, CTLFLAG_RDTUN, &maxdata,
2860 0, "Maximum number of data queue items to allocate");
2862 #ifdef NETGRAPH_DEBUG
2863 static TAILQ_HEAD(, ng_item) ng_itemlist = TAILQ_HEAD_INITIALIZER(ng_itemlist);
2864 static int allocated; /* number of items malloc'd */
2868 * Get a queue entry.
2869 * This is usually called when a packet first enters netgraph.
2870 * By definition, this is usually from an interrupt, or from a user.
2871 * Users are not so important, but try be quick for the times that it's
2874 static __inline item_p
2875 ng_alloc_item(int type, int flags)
2879 KASSERT(((type & ~NGQF_TYPE) == 0),
2880 ("%s: incorrect item type: %d", __func__, type));
2882 item = uma_zalloc((type == NGQF_DATA)?ng_qdzone:ng_qzone,
2883 (flags & NG_WAITOK) ? M_WAITOK : M_NOWAIT );
2886 item->el_flags = type;
2887 #ifdef NETGRAPH_DEBUG
2889 TAILQ_INSERT_TAIL(&ng_itemlist, item, all);
2891 mtx_unlock(&ngq_mtx);
2899 * Release a queue entry
2902 ng_free_item(item_p item)
2905 * The item may hold resources on it's own. We need to free
2906 * these before we can free the item. What they are depends upon
2907 * what kind of item it is. it is important that nodes zero
2908 * out pointers to resources that they remove from the item
2909 * or we release them again here.
2911 switch (item->el_flags & NGQF_TYPE) {
2913 /* If we have an mbuf still attached.. */
2914 NG_FREE_M(_NGI_M(item));
2917 _NGI_RETADDR(item) = 0;
2918 NG_FREE_MSG(_NGI_MSG(item));
2922 /* nothing to free really, */
2923 _NGI_FN(item) = NULL;
2924 _NGI_ARG1(item) = NULL;
2925 _NGI_ARG2(item) = 0;
2928 /* If we still have a node or hook referenced... */
2929 _NGI_CLR_NODE(item);
2930 _NGI_CLR_HOOK(item);
2932 #ifdef NETGRAPH_DEBUG
2934 TAILQ_REMOVE(&ng_itemlist, item, all);
2936 mtx_unlock(&ngq_mtx);
2938 uma_zfree(((item->el_flags & NGQF_TYPE) == NGQF_DATA)?
2939 ng_qdzone:ng_qzone, item);
2943 * Change type of the queue entry.
2944 * Possibly reallocates it from another UMA zone.
2946 static __inline item_p
2947 ng_realloc_item(item_p pitem, int type, int flags)
2952 KASSERT((pitem != NULL), ("%s: can't reallocate NULL", __func__));
2953 KASSERT(((type & ~NGQF_TYPE) == 0),
2954 ("%s: incorrect item type: %d", __func__, type));
2956 from = ((pitem->el_flags & NGQF_TYPE) == NGQF_DATA);
2957 to = (type == NGQF_DATA);
2959 /* If reallocation is required do it and copy item. */
2960 if ((item = ng_alloc_item(type, flags)) == NULL) {
2961 ng_free_item(pitem);
2965 ng_free_item(pitem);
2968 item->el_flags = (item->el_flags & ~NGQF_TYPE) | type;
2973 /************************************************************************
2975 ************************************************************************/
2978 * Handle the loading/unloading of a netgraph node type module
2981 ng_mod_event(module_t mod, int event, void *data)
2983 struct ng_type *const type = data;
2989 /* Register new netgraph node type */
2991 if ((error = ng_newtype(type)) != 0) {
2996 /* Call type specific code */
2997 if (type->mod_event != NULL)
2998 if ((error = (*type->mod_event)(mod, event, data))) {
2999 mtx_lock(&ng_typelist_mtx);
3000 type->refs--; /* undo it */
3001 LIST_REMOVE(type, types);
3002 mtx_unlock(&ng_typelist_mtx);
3009 if (type->refs > 1) { /* make sure no nodes exist! */
3012 if (type->refs == 0) {
3013 /* failed load, nothing to undo */
3017 if (type->mod_event != NULL) { /* check with type */
3018 error = (*type->mod_event)(mod, event, data);
3019 if (error != 0) { /* type refuses.. */
3024 mtx_lock(&ng_typelist_mtx);
3025 LIST_REMOVE(type, types);
3026 mtx_unlock(&ng_typelist_mtx);
3032 if (type->mod_event != NULL)
3033 error = (*type->mod_event)(mod, event, data);
3035 error = EOPNOTSUPP; /* XXX ? */
3042 * Handle loading and unloading for this code.
3043 * The only thing we need to link into is the NETISR strucure.
3046 ngb_mod_event(module_t mod, int event, void *data)
3052 /* Initialize everything. */
3053 NG_WORKLIST_LOCK_INIT();
3054 mtx_init(&ng_typelist_mtx);
3055 mtx_init(&ng_idhash_mtx);
3056 mtx_init(&ng_namehash_mtx);
3057 mtx_init(&ng_topo_mtx);
3058 #ifdef NETGRAPH_DEBUG
3059 mtx_init(&ng_nodelist_mtx);
3062 ng_qzone = uma_zcreate("NetGraph items", sizeof(struct ng_item),
3063 NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
3064 uma_zone_set_max(ng_qzone, maxalloc);
3065 ng_qdzone = uma_zcreate("NetGraph data items", sizeof(struct ng_item),
3066 NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
3067 uma_zone_set_max(ng_qdzone, maxdata);
3070 /* You can't unload it because an interface may be using it. */
3080 static moduledata_t netgraph_mod = {
3085 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_NETGRAPH, SI_ORDER_MIDDLE);
3086 SYSCTL_NODE(_net, OID_AUTO, graph, CTLFLAG_RW, 0, "netgraph Family");
3087 SYSCTL_INT(_net_graph, OID_AUTO, abi_version, CTLFLAG_RD, 0, NG_ABI_VERSION,"");
3088 SYSCTL_INT(_net_graph, OID_AUTO, msg_version, CTLFLAG_RD, 0, NG_VERSION, "");
3090 #ifdef NETGRAPH_DEBUG
3092 dumphook (hook_p hook, char *file, int line)
3094 printf("hook: name %s, %d refs, Last touched:\n",
3095 _NG_HOOK_NAME(hook), hook->hk_refs);
3096 printf(" Last active @ %s, line %d\n",
3097 hook->lastfile, hook->lastline);
3099 printf(" problem discovered at file %s, line %d\n", file, line);
3104 dumpnode(node_p node, char *file, int line)
3106 printf("node: ID [%x]: type '%s', %d hooks, flags 0x%x, %d refs, %s:\n",
3107 _NG_NODE_ID(node), node->nd_type->name,
3108 node->nd_numhooks, node->nd_flags,
3109 node->nd_refs, node->nd_name);
3110 printf(" Last active @ %s, line %d\n",
3111 node->lastfile, node->lastline);
3113 printf(" problem discovered at file %s, line %d\n", file, line);
3118 dumpitem(item_p item, char *file, int line)
3120 printf(" ACTIVE item, last used at %s, line %d",
3121 item->lastfile, item->lastline);
3122 switch(item->el_flags & NGQF_TYPE) {
3124 printf(" - [data]\n");
3127 printf(" - retaddr[%d]:\n", _NGI_RETADDR(item));
3130 printf(" - fn@%p (%p, %p, %p, %d (%x))\n",
3134 item->body.fn.fn_arg1,
3135 item->body.fn.fn_arg2,
3136 item->body.fn.fn_arg2);
3139 printf(" - fn2@%p (%p, %p, %p, %d (%x))\n",
3143 item->body.fn.fn_arg1,
3144 item->body.fn.fn_arg2,
3145 item->body.fn.fn_arg2);
3149 printf(" problem discovered at file %s, line %d\n", file, line);
3150 if (_NGI_NODE(item)) {
3151 printf("node %p ([%x])\n",
3152 _NGI_NODE(item), ng_node2ID(_NGI_NODE(item)));
3162 TAILQ_FOREACH(item, &ng_itemlist, all) {
3163 printf("[%d] ", i++);
3164 dumpitem(item, NULL, 0);
3173 mtx_lock(&ng_nodelist_mtx);
3174 SLIST_FOREACH(node, &ng_allnodes, nd_all) {
3175 printf("[%d] ", i++);
3176 dumpnode(node, NULL, 0);
3178 mtx_unlock(&ng_nodelist_mtx);
3186 mtx_lock(&ng_nodelist_mtx);
3187 SLIST_FOREACH(hook, &ng_allhooks, hk_all) {
3188 printf("[%d] ", i++);
3189 dumphook(hook, NULL, 0);
3191 mtx_unlock(&ng_nodelist_mtx);
3195 sysctl_debug_ng_dump_items(SYSCTL_HANDLER_ARGS)
3201 error = sysctl_handle_int(oidp, &val, 0, req);
3202 if (error != 0 || req->newptr == NULL)
3212 SYSCTL_PROC(_debug, OID_AUTO, ng_dump_items, CTLTYPE_INT | CTLFLAG_RW,
3213 0, sizeof(int), sysctl_debug_ng_dump_items, "I", "Number of allocated items");
3214 #endif /* NETGRAPH_DEBUG */
3217 /***********************************************************************
3219 **********************************************************************/
3220 /* NETGRAPH taskqueue routine
3222 * Pick a node off the list of nodes with work,
3223 * try get an item to process off it.
3224 * If there are no more, remove the node from the list.
3226 * This routine used to be a netisr but because no actual packets are
3227 * really sent to it, it has been converted to a taskqueue.
3230 ngtask(void *context, int pending)
3235 /* Get node from the worklist. */
3237 node = STAILQ_FIRST(&ng_worklist);
3239 NG_WORKLIST_UNLOCK();
3242 STAILQ_REMOVE_HEAD(&ng_worklist, nd_input_queue.q_work);
3243 NG_WORKLIST_UNLOCK();
3244 CTR3(KTR_NET, "%20s: node [%x] (%p) taken off worklist",
3245 __func__, node->nd_ID, node);
3247 * We have the node. We also take over the reference
3248 * that the list had on it.
3249 * Now process as much as you can, until it won't
3250 * let you have another item off the queue.
3251 * All this time, keep the reference
3252 * that lets us be sure that the node still exists.
3253 * Let the reference go at the last minute.
3259 NG_QUEUE_LOCK(&node->nd_input_queue);
3260 item = ng_dequeue(node, &rw);
3262 node->nd_input_queue.q_flags2 &= ~NGQ2_WORKQ;
3263 NG_QUEUE_UNLOCK(&node->nd_input_queue);
3264 break; /* go look for another node */
3266 NG_QUEUE_UNLOCK(&node->nd_input_queue);
3267 NGI_GET_NODE(item, node); /* zaps stored node */
3268 ng_apply_item(node, item, rw);
3269 NG_NODE_UNREF(node);
3272 NG_NODE_UNREF(node);
3278 * It's posible that a debugging NG_NODE_REF may need
3279 * to be outside the mutex zone
3282 ng_worklist_add(node_p node)
3285 KKASSERT(mtx_owned(&node->nd_input_queue.q_mtx));
3287 if ((node->nd_input_queue.q_flags2 & NGQ2_WORKQ) == 0) {
3288 static struct task ng_task;
3291 * If we are not already on the work queue,
3294 node->nd_input_queue.q_flags2 |= NGQ2_WORKQ;
3295 NG_NODE_REF(node); /* XXX fafe in mutex? */
3297 STAILQ_INSERT_TAIL(&ng_worklist, node, nd_input_queue.q_work);
3298 NG_WORKLIST_UNLOCK();
3299 TASK_INIT(&ng_task, 0, ngtask, NULL);
3300 taskqueue_enqueue(taskqueue_swi, &ng_task);
3301 CTR3(KTR_NET, "%20s: node [%x] (%p) put on worklist", __func__,
3304 CTR3(KTR_NET, "%20s: node [%x] (%p) already on worklist",
3305 __func__, node->nd_ID, node);
3310 /***********************************************************************
3311 * Externally useable functions to set up a queue item ready for sending
3312 ***********************************************************************/
3314 #ifdef NETGRAPH_DEBUG
3315 #define ITEM_DEBUG_CHECKS \
3317 if (NGI_NODE(item) ) { \
3318 printf("item already has node"); \
3319 kdb_enter(KDB_WHY_NETGRAPH, "has node"); \
3320 NGI_CLR_NODE(item); \
3322 if (NGI_HOOK(item) ) { \
3323 printf("item already has hook"); \
3324 kdb_enter(KDB_WHY_NETGRAPH, "has hook"); \
3325 NGI_CLR_HOOK(item); \
3329 #define ITEM_DEBUG_CHECKS
3333 * Put mbuf into the item.
3334 * Hook and node references will be removed when the item is dequeued.
3336 * (XXX) Unsafe because no reference held by peer on remote node.
3337 * remote node might go away in this timescale.
3338 * We know the hooks can't go away because that would require getting
3339 * a writer item on both nodes and we must have at least a reader
3340 * here to be able to do this.
3341 * Note that the hook loaded is the REMOTE hook.
3343 * This is possibly in the critical path for new data.
3346 ng_package_data(struct mbuf *m, int flags)
3350 if ((item = ng_alloc_item(NGQF_DATA, flags)) == NULL) {
3355 item->el_flags |= NGQF_READER;
3361 * Allocate a queue item and put items into it..
3362 * Evaluate the address as this will be needed to queue it and
3363 * to work out what some of the fields should be.
3364 * Hook and node references will be removed when the item is dequeued.
3368 ng_package_msg(struct ng_mesg *msg, int flags)
3372 if ((item = ng_alloc_item(NGQF_MESG, flags)) == NULL) {
3377 /* Messages items count as writers unless explicitly exempted. */
3378 if (msg->header.cmd & NGM_READONLY)
3379 item->el_flags |= NGQF_READER;
3381 item->el_flags |= NGQF_WRITER;
3383 * Set the current lasthook into the queue item
3385 NGI_MSG(item) = msg;
3386 NGI_RETADDR(item) = 0;
3392 #define SET_RETADDR(item, here, retaddr) \
3393 do { /* Data or fn items don't have retaddrs */ \
3394 if ((item->el_flags & NGQF_TYPE) == NGQF_MESG) { \
3396 NGI_RETADDR(item) = retaddr; \
3399 * The old return address should be ok. \
3400 * If there isn't one, use the address \
3403 if (NGI_RETADDR(item) == 0) { \
3405 = ng_node2ID(here); \
3412 ng_address_hook(node_p here, item_p item, hook_p hook, ng_ID_t retaddr)
3418 * Quick sanity check..
3419 * Since a hook holds a reference on it's node, once we know
3420 * that the peer is still connected (even if invalid,) we know
3421 * that the peer node is present, though maybe invalid.
3423 if ((hook == NULL) ||
3424 NG_HOOK_NOT_VALID(hook) ||
3425 NG_HOOK_NOT_VALID(peer = NG_HOOK_PEER(hook)) ||
3426 NG_NODE_NOT_VALID(peernode = NG_PEER_NODE(hook))) {
3433 * Transfer our interest to the other (peer) end.
3436 NG_NODE_REF(peernode);
3437 NGI_SET_HOOK(item, peer);
3438 NGI_SET_NODE(item, peernode);
3439 SET_RETADDR(item, here, retaddr);
3444 ng_address_path(node_p here, item_p item, char *address, ng_ID_t retaddr)
3452 * Note that ng_path2noderef increments the reference count
3453 * on the node for us if it finds one. So we don't have to.
3455 error = ng_path2noderef(here, address, &dest, &hook);
3460 NGI_SET_NODE(item, dest);
3462 NG_HOOK_REF(hook); /* don't let it go while on the queue */
3463 NGI_SET_HOOK(item, hook);
3465 SET_RETADDR(item, here, retaddr);
3470 ng_address_ID(node_p here, item_p item, ng_ID_t ID, ng_ID_t retaddr)
3476 * Find the target node.
3478 dest = ng_ID2noderef(ID); /* GETS REFERENCE! */
3484 /* Fill out the contents */
3485 NGI_SET_NODE(item, dest);
3487 SET_RETADDR(item, here, retaddr);
3492 * special case to send a message to self (e.g. destroy node)
3493 * Possibly indicate an arrival hook too.
3494 * Useful for removing that hook :-)
3497 ng_package_msg_self(node_p here, hook_p hook, struct ng_mesg *msg)
3502 * Find the target node.
3503 * If there is a HOOK argument, then use that in preference
3506 if ((item = ng_alloc_item(NGQF_MESG, NG_NOFLAGS)) == NULL) {
3511 /* Fill out the contents */
3512 item->el_flags |= NGQF_WRITER;
3514 NGI_SET_NODE(item, here);
3517 NGI_SET_HOOK(item, hook);
3519 NGI_MSG(item) = msg;
3520 NGI_RETADDR(item) = ng_node2ID(here);
3525 * Send ng_item_fn function call to the specified node.
3529 ng_send_fn(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2)
3532 return ng_send_fn1(node, hook, fn, arg1, arg2, NG_NOFLAGS);
3536 ng_send_fn1(node_p node, hook_p hook, ng_item_fn *fn, void * arg1, int arg2,
3541 if ((item = ng_alloc_item(NGQF_FN, flags)) == NULL) {
3544 item->el_flags |= NGQF_WRITER;
3545 NG_NODE_REF(node); /* and one for the item */
3546 NGI_SET_NODE(item, node);
3549 NGI_SET_HOOK(item, hook);
3552 NGI_ARG1(item) = arg1;
3553 NGI_ARG2(item) = arg2;
3554 return(ng_snd_item(item, flags));
3558 * Send ng_item_fn2 function call to the specified node.
3560 * If an optional pitem parameter is supplied, its apply
3561 * callback will be copied to the new item. If also NG_REUSE_ITEM
3562 * flag is set, no new item will be allocated, but pitem will
3566 ng_send_fn2(node_p node, hook_p hook, item_p pitem, ng_item_fn2 *fn, void *arg1,
3567 int arg2, int flags)
3571 KASSERT((pitem != NULL || (flags & NG_REUSE_ITEM) == 0),
3572 ("%s: NG_REUSE_ITEM but no pitem", __func__));
3575 * Allocate a new item if no supplied or
3576 * if we can't use supplied one.
3578 if (pitem == NULL || (flags & NG_REUSE_ITEM) == 0) {
3579 if ((item = ng_alloc_item(NGQF_FN2, flags)) == NULL)
3582 item->apply = pitem->apply;
3584 if ((item = ng_realloc_item(pitem, NGQF_FN2, flags)) == NULL)
3588 item->el_flags = (item->el_flags & ~NGQF_RW) | NGQF_WRITER;
3589 NG_NODE_REF(node); /* and one for the item */
3590 NGI_SET_NODE(item, node);
3593 NGI_SET_HOOK(item, hook);
3596 NGI_ARG1(item) = arg1;
3597 NGI_ARG2(item) = arg2;
3598 return(ng_snd_item(item, flags));
3602 * Official timeout routines for Netgraph nodes.
3605 ng_callout_trampoline(void *arg)
3609 ng_snd_item(item, 0);
3614 ng_callout(struct callout *c, node_p node, hook_p hook, int ticks,
3615 ng_item_fn *fn, void * arg1, int arg2)
3619 if ((item = ng_alloc_item(NGQF_FN, NG_NOFLAGS)) == NULL)
3622 item->el_flags |= NGQF_WRITER;
3623 NG_NODE_REF(node); /* and one for the item */
3624 NGI_SET_NODE(item, node);
3627 NGI_SET_HOOK(item, hook);
3630 NGI_ARG1(item) = arg1;
3631 NGI_ARG2(item) = arg2;
3633 callout_reset(c, ticks, &ng_callout_trampoline, item);
3637 /* A special modified version of untimeout() */
3639 ng_uncallout(struct callout *c, node_p node)
3644 KASSERT(c != NULL, ("ng_uncallout: NULL callout"));
3645 KASSERT(node != NULL, ("ng_uncallout: NULL node"));
3647 rval = callout_stop(c);
3649 /* Do an extra check */
3650 if ((rval > 0) && (c->c_func == &ng_callout_trampoline) &&
3651 (NGI_NODE(item) == node)) {
3653 * We successfully removed it from the queue before it ran
3654 * So now we need to unreference everything that was
3655 * given extra references. (NG_FREE_ITEM does this).
3665 * Set the address, if none given, give the node here.
3668 ng_replace_retaddr(node_p here, item_p item, ng_ID_t retaddr)
3671 NGI_RETADDR(item) = retaddr;
3674 * The old return address should be ok.
3675 * If there isn't one, use the address here.
3677 NGI_RETADDR(item) = ng_node2ID(here);
3682 bzero_ctor(void *obj, void *private, int ocflags)
3684 struct ng_item *i = obj;
3686 bzero(i, sizeof(struct ng_item));
3692 /* just test all the macros */
3694 ng_macro_test(item_p item);
3696 ng_macro_test(item_p item)
3701 struct ng_mesg *msg;
3706 NGI_GET_MSG(item, msg);
3707 retaddr = NGI_RETADDR(item);
3708 NG_SEND_DATA(error, hook, m, NULL);
3709 NG_SEND_DATA_ONLY(error, hook, m);
3710 NG_FWD_NEW_DATA(error, item, hook, m);
3711 NG_FWD_ITEM_HOOK(error, item, hook);
3712 NG_SEND_MSG_HOOK(error, node, msg, hook, retaddr);
3713 NG_SEND_MSG_ID(error, node, msg, retaddr, retaddr);
3714 NG_SEND_MSG_PATH(error, node, msg, ".:", retaddr);
3715 NG_FWD_MSG_HOOK(error, node, item, hook, retaddr);
3717 #endif /* TESTING */