xref: /freebsd/sys/netgraph/ng_base.c (revision a14a0223ae1b172e96dd2a1d849e22026a98b692)
1 
2 /*
3  * ng_base.c
4  *
5  * Copyright (c) 1996-1999 Whistle Communications, Inc.
6  * All rights reserved.
7  *
8  * Subject to the following obligations and disclaimer of warranty, use and
9  * redistribution of this software, in source or object code forms, with or
10  * without modifications are expressly permitted by Whistle Communications;
11  * provided, however, that:
12  * 1. Any and all reproductions of the source or object code must include the
13  *    copyright notice above and the following disclaimer of warranties; and
14  * 2. No rights are granted, in any manner or form, to use Whistle
15  *    Communications, Inc. trademarks, including the mark "WHISTLE
16  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17  *    such appears in the above copyright notice or in the software.
18  *
19  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35  * OF SUCH DAMAGE.
36  *
37  * Authors: Julian Elischer <julian@whistle.com>
38  *          Archie Cobbs <archie@whistle.com>
39  *
40  * $FreeBSD$
41  * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
42  */
43 
44 /*
45  * This file implements the base netgraph code.
46  */
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/errno.h>
51 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/syslog.h>
54 #include <sys/linker.h>
55 #include <sys/queue.h>
56 #include <sys/mbuf.h>
57 #include <sys/socketvar.h>
58 #include <sys/ctype.h>
59 #include <machine/limits.h>
60 
61 #include <net/netisr.h>
62 
63 #include <netgraph/ng_message.h>
64 #include <netgraph/netgraph.h>
65 
66 /* List of all nodes */
67 static LIST_HEAD(, ng_node) nodelist;
68 
69 /* List of installed types */
70 static LIST_HEAD(, ng_type) typelist;
71 
72 /* Hash releted definitions */
73 #define ID_HASH_SIZE 32 /* most systems wont need even this many */
74 static LIST_HEAD(, ng_node) ID_hash[ID_HASH_SIZE];
75 /* Don't nead to initialise them because it's a LIST */
76 
77 /* Internal functions */
78 static int	ng_add_hook(node_p node, const char *name, hook_p * hookp);
79 static int	ng_connect(hook_p hook1, hook_p hook2);
80 static void	ng_disconnect_hook(hook_p hook);
81 static int	ng_generic_msg(node_p here, struct ng_mesg *msg,
82 			const char *retaddr, struct ng_mesg ** resp);
83 static ng_ID_t	ng_decodeidname(const char *name);
84 static int	ngb_mod_event(module_t mod, int event, void *data);
85 static void	ngintr(void);
86 
87 /* Our own netgraph malloc type */
88 MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");
89 
90 /* Set this to Debugger("X") to catch all errors as they occur */
91 #ifndef TRAP_ERROR
92 #define TRAP_ERROR
93 #endif
94 
95 static	ng_ID_t nextID = 1;
96 
97 
98 /************************************************************************
99 			Node routines
100 ************************************************************************/
101 
102 /*
103  * Instantiate a node of the requested type
104  */
105 int
106 ng_make_node(const char *typename, node_p *nodepp)
107 {
108 	struct ng_type *type;
109 
110 	/* Check that the type makes sense */
111 	if (typename == NULL) {
112 		TRAP_ERROR;
113 		return (EINVAL);
114 	}
115 
116 	/* Locate the node type */
117 	if ((type = ng_findtype(typename)) == NULL) {
118 		char *path, filename[NG_TYPELEN + 4];
119 		linker_file_t lf;
120 		int error;
121 
122 		/* Not found, try to load it as a loadable module */
123 		snprintf(filename, sizeof(filename), "ng_%s.ko", typename);
124 		if ((path = linker_search_path(filename)) == NULL)
125 			return (ENXIO);
126 		error = linker_load_file(path, &lf);
127 		FREE(path, M_LINKER);
128 		if (error != 0)
129 			return (error);
130 		lf->userrefs++;		/* pretend loaded by the syscall */
131 
132 		/* Try again, as now the type should have linked itself in */
133 		if ((type = ng_findtype(typename)) == NULL)
134 			return (ENXIO);
135 	}
136 
137 	/* Call the constructor */
138 	if (type->constructor != NULL)
139 		return ((*type->constructor)(nodepp));
140 	else
141 		return (ng_make_node_common(type, nodepp));
142 }
143 
144 /*
145  * Generic node creation. Called by node constructors.
146  * The returned node has a reference count of 1.
147  */
148 int
149 ng_make_node_common(struct ng_type *type, node_p *nodepp)
150 {
151 	node_p node;
152 
153 	/* Require the node type to have been already installed */
154 	if (ng_findtype(type->name) == NULL) {
155 		TRAP_ERROR;
156 		return (EINVAL);
157 	}
158 
159 	/* Make a node and try attach it to the type */
160 	MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_WAITOK);
161 	if (node == NULL) {
162 		TRAP_ERROR;
163 		return (ENOMEM);
164 	}
165 	bzero(node, sizeof(*node));
166 	node->type = type;
167 	node->refs++;				/* note reference */
168 	type->refs++;
169 
170 	/* Link us into the node linked list */
171 	LIST_INSERT_HEAD(&nodelist, node, nodes);
172 
173 	/* Initialize hook list for new node */
174 	LIST_INIT(&node->hooks);
175 
176 	/* get an ID and put us in the hash chain */
177 	node->ID = nextID++; /* 137 per second for 1 year before wrap */
178 	LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);
179 
180 	/* Done */
181 	*nodepp = node;
182 	return (0);
183 }
184 
185 /*
186  * Forceably start the shutdown process on a node. Either call
187  * it's shutdown method, or do the default shutdown if there is
188  * no type-specific method.
189  *
190  * Persistent nodes must have a type-specific method which
191  * resets the NG_INVALID flag.
192  */
193 void
194 ng_rmnode(node_p node)
195 {
196 	/* Check if it's already shutting down */
197 	if ((node->flags & NG_INVALID) != 0)
198 		return;
199 
200 	/* Add an extra reference so it doesn't go away during this */
201 	node->refs++;
202 
203 	/* Mark it invalid so any newcomers know not to try use it */
204 	node->flags |= NG_INVALID;
205 
206 	/* Ask the type if it has anything to do in this case */
207 	if (node->type && node->type->shutdown)
208 		(*node->type->shutdown)(node);
209 	else {				/* do the default thing */
210 		ng_unname(node);
211 		ng_cutlinks(node);
212 		ng_unref(node);
213 	}
214 
215 	/* Remove extra reference, possibly the last */
216 	ng_unref(node);
217 }
218 
219 /*
220  * Called by the destructor to remove any STANDARD external references
221  */
222 void
223 ng_cutlinks(node_p node)
224 {
225 	hook_p  hook;
226 
227 	/* Make sure that this is set to stop infinite loops */
228 	node->flags |= NG_INVALID;
229 
230 	/* If we have sleepers, wake them up; they'll see NG_INVALID */
231 	if (node->sleepers)
232 		wakeup(node);
233 
234 	/* Notify all remaining connected nodes to disconnect */
235 	while ((hook = LIST_FIRST(&node->hooks)) != NULL)
236 		ng_destroy_hook(hook);
237 }
238 
239 /*
240  * Remove a reference to the node, possibly the last
241  */
242 void
243 ng_unref(node_p node)
244 {
245 	if (--node->refs <= 0) {
246 		node->type->refs--;
247 		LIST_REMOVE(node, nodes);
248 		LIST_REMOVE(node, idnodes);
249 		FREE(node, M_NETGRAPH);
250 	}
251 }
252 
253 /*
254  * Wait for a node to come ready. Returns a node with a reference count;
255  * don't forget to drop it when we are done with it using ng_release_node().
256  */
257 int
258 ng_wait_node(node_p node, char *msg)
259 {
260 	int s, error = 0;
261 
262 	if (msg == NULL)
263 		msg = "netgraph";
264 	s = splnet();
265 	node->sleepers++;
266 	node->refs++;		/* the sleeping process counts as a reference */
267 	while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
268 		error = tsleep(node, (PZERO + 1) | PCATCH, msg, 0);
269 	node->sleepers--;
270 	if (node->flags & NG_INVALID) {
271 		TRAP_ERROR;
272 		error = ENXIO;
273 	} else {
274 #ifdef DIAGNOSTIC
275 		if (node->refs == 1) {
276 			panic(__FUNCTION__);
277 			error = ENXIO;
278 		}
279 #endif
280 		node->flags |= NG_BUSY;
281 	}
282 	splx(s);
283 
284 	/* Release the reference we had on it */
285 	if (error != 0)
286 		ng_unref(node);
287 	return error;
288 }
289 
290 /*
291  * Release a node acquired via ng_wait_node()
292  */
293 void
294 ng_release_node(node_p node)
295 {
296 	/* Declare that we don't want it */
297 	node->flags &= ~NG_BUSY;
298 
299 	/* If we have sleepers, then wake them up */
300 	if (node->sleepers)
301 		wakeup(node);
302 
303 	/* We also have a reference.. drop it too */
304 	ng_unref(node);
305 }
306 
307 /************************************************************************
308 			Node ID handling
309 ************************************************************************/
310 static node_p
311 ng_ID2node(ng_ID_t ID)
312 {
313 	node_p np;
314 	LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
315 		if (np->ID == ID)
316 			break;
317 	}
318 	return(np);
319 }
320 
321 ng_ID_t
322 ng_node2ID(node_p node)
323 {
324 	return (node->ID);
325 }
326 
327 /************************************************************************
328 			Node name handling
329 ************************************************************************/
330 
331 /*
332  * Assign a node a name. Once assigned, the name cannot be changed.
333  */
334 int
335 ng_name_node(node_p node, const char *name)
336 {
337 	int i;
338 
339 	/* Check the name is valid */
340 	for (i = 0; i < NG_NODELEN + 1; i++) {
341 		if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
342 			break;
343 	}
344 	if (i == 0 || name[i] != '\0') {
345 		TRAP_ERROR;
346 		return (EINVAL);
347 	}
348 	if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
349 		TRAP_ERROR;
350 		return (EINVAL);
351 	}
352 
353 	/* Check the node isn't already named */
354 	if (node->name != NULL) {
355 		TRAP_ERROR;
356 		return (EISCONN);
357 	}
358 
359 	/* Check the name isn't already being used */
360 	if (ng_findname(node, name) != NULL) {
361 		TRAP_ERROR;
362 		return (EADDRINUSE);
363 	}
364 
365 	/* Allocate space and copy it */
366 	MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_WAITOK);
367 	if (node->name == NULL) {
368 		TRAP_ERROR;
369 		return (ENOMEM);
370 	}
371 	strcpy(node->name, name);
372 
373 	/* The name counts as a reference */
374 	node->refs++;
375 	return (0);
376 }
377 
378 /*
379  * Find a node by absolute name. The name should NOT end with ':'
380  * The name "." means "this node" and "[xxx]" means "the node
381  * with ID (ie, at address) xxx".
382  *
383  * Returns the node if found, else NULL.
384  */
385 node_p
386 ng_findname(node_p this, const char *name)
387 {
388 	node_p node;
389 	ng_ID_t temp;
390 
391 	/* "." means "this node" */
392 	if (strcmp(name, ".") == 0)
393 		return(this);
394 
395 	/* Check for name-by-ID */
396 	if ((temp = ng_decodeidname(name)) != 0) {
397 		return (ng_ID2node(temp));
398 	}
399 
400 	/* Find node by name */
401 	LIST_FOREACH(node, &nodelist, nodes) {
402 		if (node->name != NULL && strcmp(node->name, name) == 0)
403 			break;
404 	}
405 	return (node);
406 }
407 
408 /*
409  * Decode a ID name, eg. "[f03034de]". Returns 0 if the
410  * string is not valid, otherwise returns the value.
411  */
412 static ng_ID_t
413 ng_decodeidname(const char *name)
414 {
415 	const int len = strlen(name);
416 	const char *eptr;
417 	u_long val;
418 
419 	/* Check for proper length, brackets, no leading junk */
420 	if (len < 3 || name[0] != '[' || name[len - 1] != ']'
421 	    || !isxdigit(name[1]))
422 		return (0);
423 
424 	/* Decode number */
425 	val = strtoul(name + 1, &eptr, 16);
426 	if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
427 		return (0);
428 	return (ng_ID_t)val;
429 }
430 
431 /*
432  * Remove a name from a node. This should only be called
433  * when shutting down and removing the node.
434  */
435 void
436 ng_unname(node_p node)
437 {
438 	if (node->name) {
439 		FREE(node->name, M_NETGRAPH);
440 		node->name = NULL;
441 		ng_unref(node);
442 	}
443 }
444 
445 /************************************************************************
446 			Hook routines
447 
448  Names are not optional. Hooks are always connected, except for a
449  brief moment within these routines.
450 
451 ************************************************************************/
452 
453 /*
454  * Remove a hook reference
455  */
456 static void
457 ng_unref_hook(hook_p hook)
458 {
459 	if (--hook->refs == 0)
460 		FREE(hook, M_NETGRAPH);
461 }
462 
463 /*
464  * Add an unconnected hook to a node. Only used internally.
465  */
466 static int
467 ng_add_hook(node_p node, const char *name, hook_p *hookp)
468 {
469 	hook_p hook;
470 	int error = 0;
471 
472 	/* Check that the given name is good */
473 	if (name == NULL) {
474 		TRAP_ERROR;
475 		return (EINVAL);
476 	}
477 	LIST_FOREACH(hook, &node->hooks, hooks) {
478 		if (strcmp(hook->name, name) == 0) {
479 			TRAP_ERROR;
480 			return (EEXIST);
481 		}
482 	}
483 
484 	/* Allocate the hook and link it up */
485 	MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_WAITOK);
486 	if (hook == NULL) {
487 		TRAP_ERROR;
488 		return (ENOMEM);
489 	}
490 	bzero(hook, sizeof(*hook));
491 	hook->refs = 1;
492 	hook->flags = HK_INVALID;
493 	hook->node = node;
494 	node->refs++;		/* each hook counts as a reference */
495 
496 	/* Check if the node type code has something to say about it */
497 	if (node->type->newhook != NULL)
498 		if ((error = (*node->type->newhook)(node, hook, name)) != 0)
499 			goto fail;
500 
501 	/*
502 	 * The 'type' agrees so far, so go ahead and link it in.
503 	 * We'll ask again later when we actually connect the hooks.
504 	 */
505 	LIST_INSERT_HEAD(&node->hooks, hook, hooks);
506 	node->numhooks++;
507 
508 	/* Set hook name */
509 	MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_WAITOK);
510 	if (hook->name == NULL) {
511 		error = ENOMEM;
512 		LIST_REMOVE(hook, hooks);
513 		node->numhooks--;
514 fail:
515 		hook->node = NULL;
516 		ng_unref(node);
517 		ng_unref_hook(hook);	/* this frees the hook */
518 		return (error);
519 	}
520 	strcpy(hook->name, name);
521 	if (hookp)
522 		*hookp = hook;
523 	return (error);
524 }
525 
526 /*
527  * Connect a pair of hooks. Only used internally.
528  */
529 static int
530 ng_connect(hook_p hook1, hook_p hook2)
531 {
532 	int     error;
533 
534 	hook1->peer = hook2;
535 	hook2->peer = hook1;
536 
537 	/* Give each node the opportunity to veto the impending connection */
538 	if (hook1->node->type->connect) {
539 		if ((error = (*hook1->node->type->connect) (hook1))) {
540 			ng_destroy_hook(hook1);	/* also zaps hook2 */
541 			return (error);
542 		}
543 	}
544 	if (hook2->node->type->connect) {
545 		if ((error = (*hook2->node->type->connect) (hook2))) {
546 			ng_destroy_hook(hook2);	/* also zaps hook1 */
547 			return (error);
548 		}
549 	}
550 	hook1->flags &= ~HK_INVALID;
551 	hook2->flags &= ~HK_INVALID;
552 	return (0);
553 }
554 
555 /*
556  * Destroy a hook
557  *
558  * As hooks are always attached, this really destroys two hooks.
559  * The one given, and the one attached to it. Disconnect the hooks
560  * from each other first.
561  */
562 void
563 ng_destroy_hook(hook_p hook)
564 {
565 	hook_p peer = hook->peer;
566 
567 	hook->flags |= HK_INVALID;		/* as soon as possible */
568 	if (peer) {
569 		peer->flags |= HK_INVALID;	/* as soon as possible */
570 		hook->peer = NULL;
571 		peer->peer = NULL;
572 		ng_disconnect_hook(peer);
573 	}
574 	ng_disconnect_hook(hook);
575 }
576 
577 /*
578  * Notify the node of the hook's demise. This may result in more actions
579  * (e.g. shutdown) but we don't do that ourselves and don't know what
580  * happens there. If there is no appropriate handler, then just remove it
581  * (and decrement the reference count of it's node which in turn might
582  * make something happen).
583  */
584 static void
585 ng_disconnect_hook(hook_p hook)
586 {
587 	node_p node = hook->node;
588 
589 	/*
590 	 * Remove the hook from the node's list to avoid possible recursion
591 	 * in case the disconnection results in node shutdown.
592 	 */
593 	LIST_REMOVE(hook, hooks);
594 	node->numhooks--;
595 	if (node->type->disconnect) {
596 		/*
597 		 * The type handler may elect to destroy the peer so don't
598 		 * trust its existance after this point.
599 		 */
600 		(*node->type->disconnect) (hook);
601 	}
602 	ng_unref(node);		/* might be the last reference */
603 	if (hook->name)
604 		FREE(hook->name, M_NETGRAPH);
605 	hook->node = NULL;	/* may still be referenced elsewhere */
606 	ng_unref_hook(hook);
607 }
608 
609 /*
610  * Take two hooks on a node and merge the connection so that the given node
611  * is effectively bypassed.
612  */
613 int
614 ng_bypass(hook_p hook1, hook_p hook2)
615 {
616 	if (hook1->node != hook2->node)
617 		return (EINVAL);
618 	hook1->peer->peer = hook2->peer;
619 	hook2->peer->peer = hook1->peer;
620 
621 	/* XXX If we ever cache methods on hooks update them as well */
622 	hook1->peer = NULL;
623 	hook2->peer = NULL;
624 	ng_destroy_hook(hook1);
625 	ng_destroy_hook(hook2);
626 	return (0);
627 }
628 
629 /*
630  * Install a new netgraph type
631  */
632 int
633 ng_newtype(struct ng_type *tp)
634 {
635 	const size_t namelen = strlen(tp->name);
636 
637 	/* Check version and type name fields */
638 	if (tp->version != NG_VERSION || namelen == 0 || namelen > NG_TYPELEN) {
639 		TRAP_ERROR;
640 		return (EINVAL);
641 	}
642 
643 	/* Check for name collision */
644 	if (ng_findtype(tp->name) != NULL) {
645 		TRAP_ERROR;
646 		return (EEXIST);
647 	}
648 
649 	/* Link in new type */
650 	LIST_INSERT_HEAD(&typelist, tp, types);
651 	tp->refs = 0;
652 	return (0);
653 }
654 
655 /*
656  * Look for a type of the name given
657  */
658 struct ng_type *
659 ng_findtype(const char *typename)
660 {
661 	struct ng_type *type;
662 
663 	LIST_FOREACH(type, &typelist, types) {
664 		if (strcmp(type->name, typename) == 0)
665 			break;
666 	}
667 	return (type);
668 }
669 
670 
671 /************************************************************************
672 			Composite routines
673 ************************************************************************/
674 
675 /*
676  * Make a peer and connect. The order is arranged to minimise
677  * the work needed to back out in case of error.
678  */
679 int
680 ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
681 {
682 	node_p  node2;
683 	hook_p  hook;
684 	hook_p  hook2;
685 	int     error;
686 
687 	if ((error = ng_add_hook(node, name, &hook)))
688 		return (error);
689 	if ((error = ng_make_node(type, &node2))) {
690 		ng_destroy_hook(hook);
691 		return (error);
692 	}
693 	if ((error = ng_add_hook(node2, name2, &hook2))) {
694 		ng_rmnode(node2);
695 		ng_destroy_hook(hook);
696 		return (error);
697 	}
698 
699 	/*
700 	 * Actually link the two hooks together.. on failure they are
701 	 * destroyed so we don't have to do that here.
702 	 */
703 	if ((error = ng_connect(hook, hook2)))
704 		ng_rmnode(node2);
705 	return (error);
706 }
707 
708 /*
709  * Connect two nodes using the specified hooks
710  */
711 int
712 ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
713 {
714 	int     error;
715 	hook_p  hook;
716 	hook_p  hook2;
717 
718 	if ((error = ng_add_hook(node, name, &hook)))
719 		return (error);
720 	if ((error = ng_add_hook(node2, name2, &hook2))) {
721 		ng_destroy_hook(hook);
722 		return (error);
723 	}
724 	return (ng_connect(hook, hook2));
725 }
726 
727 /*
728  * Parse and verify a string of the form:  <NODE:><PATH>
729  *
730  * Such a string can refer to a specific node or a specific hook
731  * on a specific node, depending on how you look at it. In the
732  * latter case, the PATH component must not end in a dot.
733  *
734  * Both <NODE:> and <PATH> are optional. The <PATH> is a string
735  * of hook names separated by dots. This breaks out the original
736  * string, setting *nodep to "NODE" (or NULL if none) and *pathp
737  * to "PATH" (or NULL if degenerate). Also, *hookp will point to
738  * the final hook component of <PATH>, if any, otherwise NULL.
739  *
740  * This returns -1 if the path is malformed. The char ** are optional.
741  */
742 
743 int
744 ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
745 {
746 	char   *node, *path, *hook;
747 	int     k;
748 
749 	/*
750 	 * Extract absolute NODE, if any
751 	 */
752 	for (path = addr; *path && *path != ':'; path++);
753 	if (*path) {
754 		node = addr;	/* Here's the NODE */
755 		*path++ = '\0';	/* Here's the PATH */
756 
757 		/* Node name must not be empty */
758 		if (!*node)
759 			return -1;
760 
761 		/* A name of "." is OK; otherwise '.' not allowed */
762 		if (strcmp(node, ".") != 0) {
763 			for (k = 0; node[k]; k++)
764 				if (node[k] == '.')
765 					return -1;
766 		}
767 	} else {
768 		node = NULL;	/* No absolute NODE */
769 		path = addr;	/* Here's the PATH */
770 	}
771 
772 	/* Snoop for illegal characters in PATH */
773 	for (k = 0; path[k]; k++)
774 		if (path[k] == ':')
775 			return -1;
776 
777 	/* Check for no repeated dots in PATH */
778 	for (k = 0; path[k]; k++)
779 		if (path[k] == '.' && path[k + 1] == '.')
780 			return -1;
781 
782 	/* Remove extra (degenerate) dots from beginning or end of PATH */
783 	if (path[0] == '.')
784 		path++;
785 	if (*path && path[strlen(path) - 1] == '.')
786 		path[strlen(path) - 1] = 0;
787 
788 	/* If PATH has a dot, then we're not talking about a hook */
789 	if (*path) {
790 		for (hook = path, k = 0; path[k]; k++)
791 			if (path[k] == '.') {
792 				hook = NULL;
793 				break;
794 			}
795 	} else
796 		path = hook = NULL;
797 
798 	/* Done */
799 	if (nodep)
800 		*nodep = node;
801 	if (pathp)
802 		*pathp = path;
803 	if (hookp)
804 		*hookp = hook;
805 	return (0);
806 }
807 
808 /*
809  * Given a path, which may be absolute or relative, and a starting node,
810  * return the destination node. Compute the "return address" if desired.
811  */
812 int
813 ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp)
814 {
815 	const	node_p start = here;
816 	char    fullpath[NG_PATHLEN + 1];
817 	char   *nodename, *path, pbuf[2];
818 	node_p  node;
819 	char   *cp;
820 
821 	/* Initialize */
822 	if (rtnp)
823 		*rtnp = NULL;
824 	if (destp == NULL)
825 		return EINVAL;
826 	*destp = NULL;
827 
828 	/* Make a writable copy of address for ng_path_parse() */
829 	strncpy(fullpath, address, sizeof(fullpath) - 1);
830 	fullpath[sizeof(fullpath) - 1] = '\0';
831 
832 	/* Parse out node and sequence of hooks */
833 	if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
834 		TRAP_ERROR;
835 		return EINVAL;
836 	}
837 	if (path == NULL) {
838 		pbuf[0] = '.';	/* Needs to be writable */
839 		pbuf[1] = '\0';
840 		path = pbuf;
841 	}
842 
843 	/* For an absolute address, jump to the starting node */
844 	if (nodename) {
845 		node = ng_findname(here, nodename);
846 		if (node == NULL) {
847 			TRAP_ERROR;
848 			return (ENOENT);
849 		}
850 	} else
851 		node = here;
852 
853 	/* Now follow the sequence of hooks */
854 	for (cp = path; node != NULL && *cp != '\0'; ) {
855 		hook_p hook;
856 		char *segment;
857 
858 		/*
859 		 * Break out the next path segment. Replace the dot we just
860 		 * found with a NUL; "cp" points to the next segment (or the
861 		 * NUL at the end).
862 		 */
863 		for (segment = cp; *cp != '\0'; cp++) {
864 			if (*cp == '.') {
865 				*cp++ = '\0';
866 				break;
867 			}
868 		}
869 
870 		/* Empty segment */
871 		if (*segment == '\0')
872 			continue;
873 
874 		/* We have a segment, so look for a hook by that name */
875 		LIST_FOREACH(hook, &node->hooks, hooks) {
876 			if (hook->name && strcmp(hook->name, segment) == 0)
877 				break;
878 		}
879 
880 		/* Can't get there from here... */
881 		if (hook == NULL
882 		    || hook->peer == NULL
883 		    || (hook->flags & HK_INVALID) != 0) {
884 			TRAP_ERROR;
885 			return (ENOENT);
886 		}
887 
888 		/* Hop on over to the next node */
889 		node = hook->peer->node;
890 	}
891 
892 	/* If node somehow missing, fail here (probably this is not needed) */
893 	if (node == NULL) {
894 		TRAP_ERROR;
895 		return (ENXIO);
896 	}
897 
898 	/* Now compute return address, i.e., the path to the sender */
899 	if (rtnp != NULL) {
900 		MALLOC(*rtnp, char *, NG_NODELEN + 2, M_NETGRAPH, M_WAITOK);
901 		if (*rtnp == NULL) {
902 			TRAP_ERROR;
903 			return (ENOMEM);
904 		}
905 		if (start->name != NULL)
906 			sprintf(*rtnp, "%s:", start->name);
907 		else
908 			sprintf(*rtnp, "[%x]:", ng_node2ID(start));
909 	}
910 
911 	/* Done */
912 	*destp = node;
913 	return (0);
914 }
915 
916 /*
917  * Call the appropriate message handler for the object.
918  * It is up to the message handler to free the message.
919  * If it's a generic message, handle it generically, otherwise
920  * call the type's message handler (if it exists)
921  */
922 
923 #define CALL_MSG_HANDLER(error, node, msg, retaddr, resp)		\
924 do {									\
925 	if((msg)->header.typecookie == NGM_GENERIC_COOKIE) {		\
926 		(error) = ng_generic_msg((node), (msg),			\
927 				(retaddr), (resp));			\
928 	} else {							\
929 		if ((node)->type->rcvmsg != NULL) {			\
930 			(error) = (*(node)->type->rcvmsg)((node),	\
931 					(msg), (retaddr), (resp));	\
932 		} else {						\
933 			TRAP_ERROR;					\
934 			FREE((msg), M_NETGRAPH);			\
935 			(error) = EINVAL;				\
936 		}							\
937 	}								\
938 } while (0)
939 
940 
941 /*
942  * Send a control message to a node
943  */
944 int
945 ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
946 	    struct ng_mesg **rptr)
947 {
948 	node_p  dest = NULL;
949 	char   *retaddr = NULL;
950 	int     error;
951 
952 	/* Find the target node */
953 	error = ng_path2node(here, address, &dest, &retaddr);
954 	if (error) {
955 		FREE(msg, M_NETGRAPH);
956 		return error;
957 	}
958 
959 	/* Make sure the resp field is null before we start */
960 	if (rptr != NULL)
961 		*rptr = NULL;
962 
963 	CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr);
964 
965 	/* Make sure that if there is a response, it has the RESP bit set */
966 	if ((error == 0) && rptr && *rptr)
967 		(*rptr)->header.flags |= NGF_RESP;
968 
969 	/*
970 	 * If we had a return address it is up to us to free it. They should
971 	 * have taken a copy if they needed to make a delayed response.
972 	 */
973 	if (retaddr)
974 		FREE(retaddr, M_NETGRAPH);
975 	return (error);
976 }
977 
978 /*
979  * Implement the 'generic' control messages
980  */
981 static int
982 ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
983 	       struct ng_mesg **resp)
984 {
985 	int error = 0;
986 
987 	if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
988 		TRAP_ERROR;
989 		FREE(msg, M_NETGRAPH);
990 		return (EINVAL);
991 	}
992 	switch (msg->header.cmd) {
993 	case NGM_SHUTDOWN:
994 		ng_rmnode(here);
995 		break;
996 	case NGM_MKPEER:
997 	    {
998 		struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;
999 
1000 		if (msg->header.arglen != sizeof(*mkp)) {
1001 			TRAP_ERROR;
1002 			return (EINVAL);
1003 		}
1004 		mkp->type[sizeof(mkp->type) - 1] = '\0';
1005 		mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
1006 		mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
1007 		error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
1008 		break;
1009 	    }
1010 	case NGM_CONNECT:
1011 	    {
1012 		struct ngm_connect *const con =
1013 			(struct ngm_connect *) msg->data;
1014 		node_p node2;
1015 
1016 		if (msg->header.arglen != sizeof(*con)) {
1017 			TRAP_ERROR;
1018 			return (EINVAL);
1019 		}
1020 		con->path[sizeof(con->path) - 1] = '\0';
1021 		con->ourhook[sizeof(con->ourhook) - 1] = '\0';
1022 		con->peerhook[sizeof(con->peerhook) - 1] = '\0';
1023 		error = ng_path2node(here, con->path, &node2, NULL);
1024 		if (error)
1025 			break;
1026 		error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
1027 		break;
1028 	    }
1029 	case NGM_NAME:
1030 	    {
1031 		struct ngm_name *const nam = (struct ngm_name *) msg->data;
1032 
1033 		if (msg->header.arglen != sizeof(*nam)) {
1034 			TRAP_ERROR;
1035 			return (EINVAL);
1036 		}
1037 		nam->name[sizeof(nam->name) - 1] = '\0';
1038 		error = ng_name_node(here, nam->name);
1039 		break;
1040 	    }
1041 	case NGM_RMHOOK:
1042 	    {
1043 		struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
1044 		hook_p hook;
1045 
1046 		if (msg->header.arglen != sizeof(*rmh)) {
1047 			TRAP_ERROR;
1048 			return (EINVAL);
1049 		}
1050 		rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
1051 		LIST_FOREACH(hook, &here->hooks, hooks) {
1052 			if (hook->name && strcmp(hook->name, rmh->ourhook) == 0)
1053 				break;
1054 		}
1055 		if (hook)
1056 			ng_destroy_hook(hook);
1057 		break;
1058 	    }
1059 	case NGM_NODEINFO:
1060 	    {
1061 		struct nodeinfo *ni;
1062 		struct ng_mesg *rp;
1063 
1064 		/* Get response struct */
1065 		if (resp == NULL) {
1066 			error = EINVAL;
1067 			break;
1068 		}
1069 		NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
1070 		if (rp == NULL) {
1071 			error = ENOMEM;
1072 			break;
1073 		}
1074 
1075 		/* Fill in node info */
1076 		ni = (struct nodeinfo *) rp->data;
1077 		if (here->name != NULL)
1078 			strncpy(ni->name, here->name, NG_NODELEN);
1079 		strncpy(ni->type, here->type->name, NG_TYPELEN);
1080 		ni->id = ng_node2ID(here);
1081 		ni->hooks = here->numhooks;
1082 		*resp = rp;
1083 		break;
1084 	    }
1085 	case NGM_LISTHOOKS:
1086 	    {
1087 		const int nhooks = here->numhooks;
1088 		struct hooklist *hl;
1089 		struct nodeinfo *ni;
1090 		struct ng_mesg *rp;
1091 		hook_p hook;
1092 
1093 		/* Get response struct */
1094 		if (resp == NULL) {
1095 			error = EINVAL;
1096 			break;
1097 		}
1098 		NG_MKRESPONSE(rp, msg, sizeof(*hl)
1099 		    + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
1100 		if (rp == NULL) {
1101 			error = ENOMEM;
1102 			break;
1103 		}
1104 		hl = (struct hooklist *) rp->data;
1105 		ni = &hl->nodeinfo;
1106 
1107 		/* Fill in node info */
1108 		if (here->name)
1109 			strncpy(ni->name, here->name, NG_NODELEN);
1110 		strncpy(ni->type, here->type->name, NG_TYPELEN);
1111 		ni->id = ng_node2ID(here);
1112 
1113 		/* Cycle through the linked list of hooks */
1114 		ni->hooks = 0;
1115 		LIST_FOREACH(hook, &here->hooks, hooks) {
1116 			struct linkinfo *const link = &hl->link[ni->hooks];
1117 
1118 			if (ni->hooks >= nhooks) {
1119 				log(LOG_ERR, "%s: number of %s changed\n",
1120 				    __FUNCTION__, "hooks");
1121 				break;
1122 			}
1123 			if ((hook->flags & HK_INVALID) != 0)
1124 				continue;
1125 			strncpy(link->ourhook, hook->name, NG_HOOKLEN);
1126 			strncpy(link->peerhook, hook->peer->name, NG_HOOKLEN);
1127 			if (hook->peer->node->name != NULL)
1128 				strncpy(link->nodeinfo.name,
1129 				    hook->peer->node->name, NG_NODELEN);
1130 			strncpy(link->nodeinfo.type,
1131 			   hook->peer->node->type->name, NG_TYPELEN);
1132 			link->nodeinfo.id = ng_node2ID(hook->peer->node);
1133 			link->nodeinfo.hooks = hook->peer->node->numhooks;
1134 			ni->hooks++;
1135 		}
1136 		*resp = rp;
1137 		break;
1138 	    }
1139 
1140 	case NGM_LISTNAMES:
1141 	case NGM_LISTNODES:
1142 	    {
1143 		const int unnamed = (msg->header.cmd == NGM_LISTNODES);
1144 		struct namelist *nl;
1145 		struct ng_mesg *rp;
1146 		node_p node;
1147 		int num = 0;
1148 
1149 		if (resp == NULL) {
1150 			error = EINVAL;
1151 			break;
1152 		}
1153 
1154 		/* Count number of nodes */
1155 		LIST_FOREACH(node, &nodelist, nodes) {
1156 			if (unnamed || node->name != NULL)
1157 				num++;
1158 		}
1159 
1160 		/* Get response struct */
1161 		if (resp == NULL) {
1162 			error = EINVAL;
1163 			break;
1164 		}
1165 		NG_MKRESPONSE(rp, msg, sizeof(*nl)
1166 		    + (num * sizeof(struct nodeinfo)), M_NOWAIT);
1167 		if (rp == NULL) {
1168 			error = ENOMEM;
1169 			break;
1170 		}
1171 		nl = (struct namelist *) rp->data;
1172 
1173 		/* Cycle through the linked list of nodes */
1174 		nl->numnames = 0;
1175 		LIST_FOREACH(node, &nodelist, nodes) {
1176 			struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];
1177 
1178 			if (nl->numnames >= num) {
1179 				log(LOG_ERR, "%s: number of %s changed\n",
1180 				    __FUNCTION__, "nodes");
1181 				break;
1182 			}
1183 			if ((node->flags & NG_INVALID) != 0)
1184 				continue;
1185 			if (!unnamed && node->name == NULL)
1186 				continue;
1187 			if (node->name != NULL)
1188 				strncpy(np->name, node->name, NG_NODELEN);
1189 			strncpy(np->type, node->type->name, NG_TYPELEN);
1190 			np->id = ng_node2ID(node);
1191 			np->hooks = node->numhooks;
1192 			nl->numnames++;
1193 		}
1194 		*resp = rp;
1195 		break;
1196 	    }
1197 
1198 	case NGM_LISTTYPES:
1199 	    {
1200 		struct typelist *tl;
1201 		struct ng_mesg *rp;
1202 		struct ng_type *type;
1203 		int num = 0;
1204 
1205 		if (resp == NULL) {
1206 			error = EINVAL;
1207 			break;
1208 		}
1209 
1210 		/* Count number of types */
1211 		LIST_FOREACH(type, &typelist, types)
1212 			num++;
1213 
1214 		/* Get response struct */
1215 		if (resp == NULL) {
1216 			error = EINVAL;
1217 			break;
1218 		}
1219 		NG_MKRESPONSE(rp, msg, sizeof(*tl)
1220 		    + (num * sizeof(struct typeinfo)), M_NOWAIT);
1221 		if (rp == NULL) {
1222 			error = ENOMEM;
1223 			break;
1224 		}
1225 		tl = (struct typelist *) rp->data;
1226 
1227 		/* Cycle through the linked list of types */
1228 		tl->numtypes = 0;
1229 		LIST_FOREACH(type, &typelist, types) {
1230 			struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];
1231 
1232 			if (tl->numtypes >= num) {
1233 				log(LOG_ERR, "%s: number of %s changed\n",
1234 				    __FUNCTION__, "types");
1235 				break;
1236 			}
1237 			strncpy(tp->typename, type->name, NG_TYPELEN);
1238 			tp->numnodes = type->refs;
1239 			tl->numtypes++;
1240 		}
1241 		*resp = rp;
1242 		break;
1243 	    }
1244 
1245 	case NGM_TEXT_STATUS:
1246 		/*
1247 		 * This one is tricky as it passes the command down to the
1248 		 * actual node, even though it is a generic type command.
1249 		 * This means we must assume that the msg is already freed
1250 		 * when control passes back to us.
1251 		 */
1252 		if (resp == NULL) {
1253 			error = EINVAL;
1254 			break;
1255 		}
1256 		if (here->type->rcvmsg != NULL)
1257 			return((*here->type->rcvmsg)(here, msg, retaddr, resp));
1258 		/* Fall through if rcvmsg not supported */
1259 	default:
1260 		TRAP_ERROR;
1261 		error = EINVAL;
1262 	}
1263 	FREE(msg, M_NETGRAPH);
1264 	return (error);
1265 }
1266 
1267 /*
1268  * Send a data packet to a node. If the recipient has no
1269  * 'receive data' method, then silently discard the packet.
1270  */
1271 int
1272 ng_send_data(hook_p hook, struct mbuf *m, meta_p meta)
1273 {
1274 	int (*rcvdata)(hook_p, struct mbuf *, meta_p);
1275 	int error;
1276 
1277 #ifdef DIAGNOSTIC
1278 	if ((m->m_flags & M_PKTHDR) == 0)
1279 		panic(__FUNCTION__);
1280 #endif
1281 	if (hook && (hook->flags & HK_INVALID) == 0) {
1282 		rcvdata = hook->peer->node->type->rcvdata;
1283 		if (rcvdata != NULL)
1284 			error = (*rcvdata)(hook->peer, m, meta);
1285 		else {
1286 			error = 0;
1287 			NG_FREE_DATA(m, meta);
1288 		}
1289 	} else {
1290 		TRAP_ERROR;
1291 		error = ENOTCONN;
1292 		NG_FREE_DATA(m, meta);
1293 	}
1294 	return (error);
1295 }
1296 
1297 /*
1298  * Send a queued data packet to a node. If the recipient has no
1299  * 'receive queued data' method, then try the 'receive data' method above.
1300  */
1301 int
1302 ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta)
1303 {
1304 	int (*rcvdataq)(hook_p, struct mbuf *, meta_p);
1305 	int error;
1306 
1307 #ifdef DIAGNOSTIC
1308 	if ((m->m_flags & M_PKTHDR) == 0)
1309 		panic(__FUNCTION__);
1310 #endif
1311 	if (hook && (hook->flags & HK_INVALID) == 0) {
1312 		rcvdataq = hook->peer->node->type->rcvdataq;
1313 		if (rcvdataq != NULL)
1314 			error = (*rcvdataq)(hook->peer, m, meta);
1315 		else {
1316 			error = ng_send_data(hook, m, meta);
1317 		}
1318 	} else {
1319 		TRAP_ERROR;
1320 		error = ENOTCONN;
1321 		NG_FREE_DATA(m, meta);
1322 	}
1323 	return (error);
1324 }
1325 
1326 /************************************************************************
1327 			Module routines
1328 ************************************************************************/
1329 
1330 /*
1331  * Handle the loading/unloading of a netgraph node type module
1332  */
1333 int
1334 ng_mod_event(module_t mod, int event, void *data)
1335 {
1336 	struct ng_type *const type = data;
1337 	int s, error = 0;
1338 
1339 	switch (event) {
1340 	case MOD_LOAD:
1341 
1342 		/* Register new netgraph node type */
1343 		s = splnet();
1344 		if ((error = ng_newtype(type)) != 0) {
1345 			splx(s);
1346 			break;
1347 		}
1348 
1349 		/* Call type specific code */
1350 		if (type->mod_event != NULL)
1351 			if ((error = (*type->mod_event)(mod, event, data)) != 0)
1352 				LIST_REMOVE(type, types);
1353 		splx(s);
1354 		break;
1355 
1356 	case MOD_UNLOAD:
1357 		s = splnet();
1358 		if (type->refs != 0)		/* make sure no nodes exist! */
1359 			error = EBUSY;
1360 		else {
1361 			if (type->mod_event != NULL) {	/* check with type */
1362 				error = (*type->mod_event)(mod, event, data);
1363 				if (error != 0) {	/* type refuses.. */
1364 					splx(s);
1365 					break;
1366 				}
1367 			}
1368 			LIST_REMOVE(type, types);
1369 		}
1370 		splx(s);
1371 		break;
1372 
1373 	default:
1374 		if (type->mod_event != NULL)
1375 			error = (*type->mod_event)(mod, event, data);
1376 		else
1377 			error = 0;		/* XXX ? */
1378 		break;
1379 	}
1380 	return (error);
1381 }
1382 
1383 /*
1384  * Handle loading and unloading for this code.
1385  * The only thing we need to link into is the NETISR strucure.
1386  */
1387 static int
1388 ngb_mod_event(module_t mod, int event, void *data)
1389 {
1390 	int s, error = 0;
1391 
1392 	switch (event) {
1393 	case MOD_LOAD:
1394 		/* Register line discipline */
1395 		s = splimp();
1396 		error = register_netisr(NETISR_NETGRAPH, ngintr);
1397 		splx(s);
1398 		break;
1399 	case MOD_UNLOAD:
1400 		/* You cant unload it because an interface may be using it.  */
1401 		error = EBUSY;
1402 		break;
1403 	default:
1404 		error = EOPNOTSUPP;
1405 		break;
1406 	}
1407 	return (error);
1408 }
1409 
1410 static moduledata_t netgraph_mod = {
1411 	"netgraph",
1412 	ngb_mod_event,
1413 	(NULL)
1414 };
1415 DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
1416 
1417 /************************************************************************
1418 			Queueing routines
1419 ************************************************************************/
1420 
1421 /* The structure for queueing across ISR switches */
1422 struct ng_queue_entry {
1423 	u_long	flags;
1424 	struct ng_queue_entry *next;
1425 	union {
1426 		struct {
1427 			hook_p		da_hook;	/*  target hook */
1428 			struct mbuf	*da_m;
1429 			meta_p		da_meta;
1430 		} data;
1431 		struct {
1432 			struct ng_mesg	*msg_msg;
1433 			node_p		msg_node;
1434 			void		*msg_retaddr;
1435 		} msg;
1436 	} body;
1437 };
1438 #define NGQF_DATA	0x01		/* the queue element is data */
1439 #define NGQF_MESG	0x02		/* the queue element is a message */
1440 
1441 static struct ng_queue_entry   *ngqbase;	/* items to be unqueued */
1442 static struct ng_queue_entry   *ngqlast;	/* last item queued */
1443 static const int		ngqroom = 64;	/* max items to queue */
1444 static int			ngqsize;	/* number of items in queue */
1445 
1446 static struct ng_queue_entry   *ngqfree;	/* free ones */
1447 static const int		ngqfreemax = 16;/* cache at most this many */
1448 static int			ngqfreesize;	/* number of cached entries */
1449 
1450 /*
1451  * Get a queue entry
1452  */
1453 static struct ng_queue_entry *
1454 ng_getqblk(void)
1455 {
1456 	register struct ng_queue_entry *q;
1457 	int s;
1458 
1459 	/* Could be guarding against tty ints or whatever */
1460 	s = splhigh();
1461 
1462 	/* Try get a cached queue block, or else allocate a new one */
1463 	if ((q = ngqfree) == NULL) {
1464 		splx(s);
1465 		if (ngqsize < ngqroom) {	/* don't worry about races */
1466 			MALLOC(q, struct ng_queue_entry *,
1467 			    sizeof(*q), M_NETGRAPH, M_NOWAIT);
1468 		}
1469 	} else {
1470 		ngqfree = q->next;
1471 		ngqfreesize--;
1472 		splx(s);
1473 	}
1474 	return (q);
1475 }
1476 
1477 /*
1478  * Release a queue entry
1479  */
1480 #define RETURN_QBLK(q)							\
1481 do {									\
1482 	int s;								\
1483 	if (ngqfreesize < ngqfreemax) { /* don't worry about races */ 	\
1484 		s = splhigh();						\
1485 		(q)->next = ngqfree;					\
1486 		ngqfree = (q);						\
1487 		ngqfreesize++;						\
1488 		splx(s);						\
1489 	} else {							\
1490 		FREE((q), M_NETGRAPH);					\
1491 	}								\
1492 } while (0)
1493 
1494 /*
1495  * Running at a raised (but we don't know which) processor priority level,
1496  * put the data onto a queue to be picked up by another PPL (probably splnet)
1497  */
1498 int
1499 ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
1500 {
1501 	struct ng_queue_entry *q;
1502 	int s;
1503 
1504 	if (hook == NULL) {
1505 		NG_FREE_DATA(m, meta);
1506 		return (0);
1507 	}
1508 	if ((q = ng_getqblk()) == NULL) {
1509 		NG_FREE_DATA(m, meta);
1510 		return (ENOBUFS);
1511 	}
1512 
1513 	/* Fill out the contents */
1514 	q->flags = NGQF_DATA;
1515 	q->next = NULL;
1516 	q->body.data.da_hook = hook;
1517 	q->body.data.da_m = m;
1518 	q->body.data.da_meta = meta;
1519 	hook->refs++;		/* don't let it go away while on the queue */
1520 
1521 	/* Put it on the queue */
1522 	s = splhigh();
1523 	if (ngqbase) {
1524 		ngqlast->next = q;
1525 	} else {
1526 		ngqbase = q;
1527 	}
1528 	ngqlast = q;
1529 	ngqsize++;
1530 	splx(s);
1531 
1532 	/* Schedule software interrupt to handle it later */
1533 	schednetisr(NETISR_NETGRAPH);
1534 	return (0);
1535 }
1536 
1537 /*
1538  * Running at a raised (but we don't know which) processor priority level,
1539  * put the msg onto a queue to be picked up by another PPL (probably splnet)
1540  */
1541 int
1542 ng_queue_msg(node_p here, struct ng_mesg * msg, int len, const char *address)
1543 {
1544 	register struct ng_queue_entry *q;
1545 	int     s;
1546 	node_p  dest = NULL;
1547 	char   *retaddr = NULL;
1548 	int     error;
1549 
1550 	/* Find the target node. */
1551 	error = ng_path2node(here, address, &dest, &retaddr);
1552 	if (error) {
1553 		FREE(msg, M_NETGRAPH);
1554 		return (error);
1555 	}
1556 	if ((q = ng_getqblk()) == NULL) {
1557 		FREE(msg, M_NETGRAPH);
1558 		if (retaddr)
1559 			FREE(retaddr, M_NETGRAPH);
1560 		return (ENOBUFS);
1561 	}
1562 
1563 	/* Fill out the contents */
1564 	q->flags = NGQF_MESG;
1565 	q->next = NULL;
1566 	q->body.msg.msg_node = dest;
1567 	q->body.msg.msg_msg = msg;
1568 	q->body.msg.msg_retaddr = retaddr;
1569 	dest->refs++;		/* don't let it go away while on the queue */
1570 
1571 	/* Put it on the queue */
1572 	s = splhigh();
1573 	if (ngqbase) {
1574 		ngqlast->next = q;
1575 	} else {
1576 		ngqbase = q;
1577 	}
1578 	ngqlast = q;
1579 	ngqsize++;
1580 	splx(s);
1581 
1582 	/* Schedule software interrupt to handle it later */
1583 	schednetisr(NETISR_NETGRAPH);
1584 	return (0);
1585 }
1586 
1587 /*
1588  * Pick an item off the queue, process it, and dispose of the queue entry.
1589  * Should be running at splnet.
1590  */
1591 static void
1592 ngintr(void)
1593 {
1594 	hook_p  hook;
1595 	struct ng_queue_entry *ngq;
1596 	struct mbuf *m;
1597 	meta_p  meta;
1598 	void   *retaddr;
1599 	struct ng_mesg *msg;
1600 	node_p  node;
1601 	int     error = 0;
1602 	int     s;
1603 
1604 	while (1) {
1605 		s = splhigh();
1606 		if ((ngq = ngqbase)) {
1607 			ngqbase = ngq->next;
1608 			ngqsize--;
1609 		}
1610 		splx(s);
1611 		if (ngq == NULL)
1612 			return;
1613 		switch (ngq->flags) {
1614 		case NGQF_DATA:
1615 			hook = ngq->body.data.da_hook;
1616 			m = ngq->body.data.da_m;
1617 			meta = ngq->body.data.da_meta;
1618 			RETURN_QBLK(ngq);
1619 			NG_SEND_DATAQ(error, hook, m, meta);
1620 			ng_unref_hook(hook);
1621 			break;
1622 		case NGQF_MESG:
1623 			node = ngq->body.msg.msg_node;
1624 			msg = ngq->body.msg.msg_msg;
1625 			retaddr = ngq->body.msg.msg_retaddr;
1626 			RETURN_QBLK(ngq);
1627 			if (node->flags & NG_INVALID) {
1628 				FREE(msg, M_NETGRAPH);
1629 			} else {
1630 				CALL_MSG_HANDLER(error, node, msg,
1631 						 retaddr, NULL);
1632 			}
1633 			ng_unref(node);
1634 			if (retaddr)
1635 				FREE(retaddr, M_NETGRAPH);
1636 			break;
1637 		default:
1638 			RETURN_QBLK(ngq);
1639 		}
1640 	}
1641 }
1642 
1643 
1644