xref: /freebsd/sys/netgraph/ng_sample.c (revision 2eb8169a1ad3bd8c7960767a5bc471c8d8bc677e)
1 
2 /*
3  * ng_sample.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  * Author: Julian Elischer <julian@freebsd.org>
38  *
39  * $FreeBSD$
40  * $Whistle: ng_sample.c,v 1.13 1999/11/01 09:24:52 julian Exp $
41  */
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/mbuf.h>
47 #include <sys/malloc.h>
48 #include <sys/ctype.h>
49 #include <sys/errno.h>
50 #include <sys/syslog.h>
51 
52 #include <netgraph/ng_message.h>
53 #include <netgraph/ng_parse.h>
54 #include <netgraph/ng_sample.h>
55 #include <netgraph/netgraph.h>
56 
57 /* If you do complicated mallocs you may want to do this */
58 /* and use it for your mallocs */
59 #ifdef NG_SEPARATE_MALLOC
60 MALLOC_DEFINE(M_NETGRAPH_XXX, "netgraph_xxx", "netgraph xxx node ");
61 #else
62 #define M_NETGRAPH_XXX M_NETGRAPH
63 #endif
64 
65 /*
66  * This section contains the netgraph method declarations for the
67  * sample node. These methods define the netgraph 'type'.
68  */
69 
70 static ng_constructor_t	ng_xxx_constructor;
71 static ng_rcvmsg_t	ng_xxx_rcvmsg;
72 static ng_shutdown_t	ng_xxx_shutdown;
73 static ng_newhook_t	ng_xxx_newhook;
74 static ng_connect_t	ng_xxx_connect;
75 static ng_rcvdata_t	ng_xxx_rcvdata;	 /* note these are both ng_rcvdata_t */
76 static ng_disconnect_t	ng_xxx_disconnect;
77 
78 /* Parse type for struct ngxxxstat */
79 static const struct ng_parse_struct_info
80 	ng_xxx_stat_type_info = NG_XXX_STATS_TYPE_INFO;
81 static const struct ng_parse_type ng_xxx_stat_type = {
82 	&ng_parse_struct_type,
83 	&ng_xxx_stat_type_info
84 };
85 
86 /* List of commands and how to convert arguments to/from ASCII */
87 static const struct ng_cmdlist ng_xxx_cmdlist[] = {
88 	{
89 	  NGM_XXX_COOKIE,
90 	  NGM_XXX_GET_STATUS,
91 	  "getstatus",
92 	  NULL,
93 	  &ng_xxx_stat_type,
94 	},
95 	{
96 	  NGM_XXX_COOKIE,
97 	  NGM_XXX_SET_FLAG,
98 	  "setflag",
99 	  &ng_parse_int32_type,
100 	  NULL
101 	},
102 	{ 0 }
103 };
104 
105 /* Netgraph node type descriptor */
106 static struct ng_type typestruct = {
107 	NG_ABI_VERSION,
108 	NG_XXX_NODE_TYPE,
109 	NULL,
110 	ng_xxx_constructor,
111 	ng_xxx_rcvmsg,
112 	ng_xxx_shutdown,
113 	ng_xxx_newhook,
114 	NULL,
115 	ng_xxx_connect,
116 	ng_xxx_rcvdata,
117 	ng_xxx_disconnect,
118 	ng_xxx_cmdlist
119 };
120 NETGRAPH_INIT(xxx, &typestruct);
121 
122 /* Information we store for each hook on each node */
123 struct XXX_hookinfo {
124 	int     dlci;		/* The DLCI it represents, -1 == downstream */
125 	int     channel;	/* The channel representing this DLCI */
126 	hook_p  hook;
127 };
128 
129 /* Information we store for each node */
130 struct XXX {
131 	struct XXX_hookinfo channel[XXX_NUM_DLCIS];
132 	struct XXX_hookinfo downstream_hook;
133 	node_p		node;		/* back pointer to node */
134 	hook_p  	debughook;
135 	u_int   	packets_in;	/* packets in from downstream */
136 	u_int   	packets_out;	/* packets out towards downstream */
137 	u_int32_t	flags;
138 };
139 typedef struct XXX *xxx_p;
140 
141 /*
142  * Allocate the private data structure. The generic node has already
143  * been created. Link them together. We arrive with a reference to the node
144  * i.e. the reference count is incremented for us already.
145  *
146  * If this were a device node than this work would be done in the attach()
147  * routine and the constructor would return EINVAL as you should not be able
148  * to creatednodes that depend on hardware (unless you can add the hardware :)
149  */
150 static int
151 ng_xxx_constructor(node_p node)
152 {
153 	xxx_p privdata;
154 	int i, error;
155 
156 	/* Initialize private descriptor */
157 	MALLOC(privdata, xxx_p, sizeof(*privdata), M_NETGRAPH,
158 		M_NOWAIT | M_ZERO);
159 	if (privdata == NULL)
160 		return (ENOMEM);
161 	for (i = 0; i < XXX_NUM_DLCIS; i++) {
162 		privdata->channel[i].dlci = -2;
163 		privdata->channel[i].channel = i;
164 	}
165 
166 	/* Link structs together; this counts as our one reference to *nodep */
167 	NG_NODE_PRIVATE(node) = privdata;
168 	privdata->node = node;
169 	return (0);
170 }
171 
172 /*
173  * Give our ok for a hook to be added...
174  * If we are not running this might kick a device into life.
175  * Possibly decode information out of the hook name.
176  * Add the hook's private info to the hook structure.
177  * (if we had some). In this example, we assume that there is a
178  * an array of structs, called 'channel' in the private info,
179  * one for each active channel. The private
180  * pointer of each hook points to the appropriate XXX_hookinfo struct
181  * so that the source of an input packet is easily identified.
182  * (a dlci is a frame relay channel)
183  */
184 static int
185 ng_xxx_newhook(node_p node, hook_p hook, const char *name)
186 {
187 	const xxx_p xxxp = NG_NODE_PRIVATE(node);
188 	const char *cp;
189 	int dlci = 0;
190 	int chan;
191 
192 #if 0
193 	/* Possibly start up the device if it's not already going */
194 	if ((xxxp->flags & SCF_RUNNING) == 0) {
195 		ng_xxx_start_hardware(xxxp);
196 	}
197 #endif
198 
199 	/* Example of how one might use hooks with embedded numbers: All
200 	 * hooks start with 'dlci' and have a decimal trailing channel
201 	 * number up to 4 digits Use the leadin defined int he associated .h
202 	 * file. */
203 	if (strncmp(name,
204 	    NG_XXX_HOOK_DLCI_LEADIN, strlen(NG_XXX_HOOK_DLCI_LEADIN)) == 0) {
205 		char *eptr;
206 
207 		cp = name + sizeof(NG_XXX_HOOK_DLCI_LEADIN);
208 		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
209 			return (EINVAL);
210 		dlci = (int)strtoul(cp, &eptr, 10);
211 		if (*eptr != '\0' || dlci < 0 || dlci > 1023)
212 			return (EINVAL);
213 
214 		/* We have a dlci, now either find it, or allocate it */
215 		for (chan = 0; chan < XXX_NUM_DLCIS; chan++)
216 			if (xxxp->channel[chan].dlci == dlci)
217 				break;
218 		if (chan == XXX_NUM_DLCIS) {
219 			for (chan = 0; chan < XXX_NUM_DLCIS; chan++)
220 				if (xxxp->channel[chan].dlci != -2)
221 					continue;
222 			if (chan == XXX_NUM_DLCIS)
223 				return (ENOBUFS);
224 		}
225 		if (xxxp->channel[chan].hook != NULL)
226 			return (EADDRINUSE);
227 		NG_HOOK_SET_PRIVATE(hook, xxxp->channel + chan);
228 		xxxp->channel[chan].hook = hook;
229 		return (0);
230 	} else if (strcmp(name, NG_XXX_HOOK_DOWNSTREAM) == 0) {
231 		/* Example of simple predefined hooks. */
232 		/* do something specific to the downstream connection */
233 		xxxp->downstream_hook.hook = hook;
234 		NG_HOOK_SET_PRIVATE(hook, &xxxp->downstream_hook);
235 	} else if (strcmp(name, NG_XXX_HOOK_DEBUG) == 0) {
236 		/* do something specific to a debug connection */
237 		xxxp->debughook = hook;
238 		NG_HOOK_SET_PRIVATE(hook, NULL);
239 	} else
240 		return (EINVAL);	/* not a hook we know about */
241 	return(0);
242 }
243 
244 /*
245  * Get a netgraph control message.
246  * We actually recieve a queue item that has a pointer to the message.
247  * If we free the item, the message will be freed too, unless we remove
248  * it from the item using NGI_GET_MSG();
249  * The return address is also stored in the item, as an ng_ID_t,
250  * accessible as NGI_RETADDR(item);
251  * Check it is one we understand. If needed, send a response.
252  * We could save the address for an async action later, but don't here.
253  * Always free the message.
254  * The response should be in a malloc'd region that the caller can 'free'.
255  * A response is not required.
256  * Theoretically you could respond defferently to old message types if
257  * the cookie in the header didn't match what we consider to be current
258  * (so that old userland programs could continue to work).
259  */
260 static int
261 ng_xxx_rcvmsg(node_p node, item_p item, hook_p lasthook)
262 {
263 	const xxx_p xxxp = NG_NODE_PRIVATE(node);
264 	struct ng_mesg *resp = NULL;
265 	int error = 0;
266 	struct ng_mesg *msg;
267 
268 	NGI_GET_MSG(item, msg);
269 	/* Deal with message according to cookie and command */
270 	switch (msg->header.typecookie) {
271 	case NGM_XXX_COOKIE:
272 		switch (msg->header.cmd) {
273 		case NGM_XXX_GET_STATUS:
274 		    {
275 			struct ngxxxstat *stats;
276 
277 			NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
278 			if (!resp) {
279 				error = ENOMEM;
280 				break;
281 			}
282 			stats = (struct ngxxxstat *) resp->data;
283 			stats->packets_in = xxxp->packets_in;
284 			stats->packets_out = xxxp->packets_out;
285 			break;
286 		    }
287 		case NGM_XXX_SET_FLAG:
288 			if (msg->header.arglen != sizeof(u_int32_t)) {
289 				error = EINVAL;
290 				break;
291 			}
292 			xxxp->flags = *((u_int32_t *) msg->data);
293 			break;
294 		default:
295 			error = EINVAL;		/* unknown command */
296 			break;
297 		}
298 		break;
299 	default:
300 		error = EINVAL;			/* unknown cookie type */
301 		break;
302 	}
303 
304 	/* Take care of synchronous response, if any */
305 	NG_RESPOND_MSG(error, node, item, resp);
306 	/* Free the message and return */
307 	NG_FREE_MSG(msg);
308 	return(error);
309 }
310 
311 /*
312  * Receive data, and do something with it.
313  * Actually we receive a queue item which holds the data.
314  * If we free the item it wil also froo the data and metadata unless
315  * we have previously disassociated them using the NGI_GET_xxx() macros.
316  * Possibly send it out on another link after processing.
317  * Possibly do something different if it comes from different
318  * hooks. the caller will never free m or meta, so
319  * if we use up this data or abort we must free BOTH of these.
320  *
321  * If we want, we may decide to force this data to be queued and reprocessed
322  * at the netgraph NETISR time.
323  * We would do that by setting the HK_QUEUE flag on our hook. We would do that
324  * in the connect() method.
325  */
326 static int
327 ng_xxx_rcvdata(hook_p hook, item_p item )
328 {
329 	const xxx_p xxxp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
330 	int chan = -2;
331 	int dlci = -2;
332 	int error;
333 	struct mbuf *m;
334 	meta_p meta;
335 
336 
337 	NGI_GET_M(item, m);
338 	if (NG_HOOK_PRIVATE(hook)) {
339 		dlci = ((struct XXX_hookinfo *) NG_HOOK_PRIVATE(hook))->dlci;
340 		chan = ((struct XXX_hookinfo *) NG_HOOK_PRIVATE(hook))->channel;
341 		if (dlci != -1) {
342 			/* If received on a DLCI hook process for this
343 			 * channel and pass it to the downstream module.
344 			 * Normally one would add a multiplexing header at
345 			 * the front here */
346 			/* M_PREPEND(....)	; */
347 			/* mtod(m, xxxxxx)->dlci = dlci; */
348 			NG_FWD_NEW_DATA(error, item,
349 				xxxp->downstream_hook.hook, m);
350 			xxxp->packets_out++;
351 		} else {
352 			/* data came from the multiplexed link */
353 			dlci = 1;	/* get dlci from header */
354 			/* madjust(....) *//* chop off header */
355 			for (chan = 0; chan < XXX_NUM_DLCIS; chan++)
356 				if (xxxp->channel[chan].dlci == dlci)
357 					break;
358 			if (chan == XXX_NUM_DLCIS) {
359 				NG_FREE_ITEM(item);
360 				NG_FREE_M(m);
361 				return (ENETUNREACH);
362 			}
363 			/* If we were called at splnet, use the following:
364 			 * NG_SEND_DATA(error, otherhook, m, meta); if this
365 			 * node is running at some SPL other than SPLNET
366 			 * then you should use instead: error =
367 			 * ng_queueit(otherhook, m, meta); m = NULL: meta =
368 			 * NULL; this queues the data using the standard
369 			 * NETISR system and schedules the data to be picked
370 			 * up again once the system has moved to SPLNET and
371 			 * the processing of the data can continue. after
372 			 * these are run 'm' and 'meta' should be considered
373 			 * as invalid and NG_SEND_DATA actually zaps them. */
374 			NG_FWD_NEW_DATA(error, item,
375 				xxxp->channel[chan].hook, m);
376 			xxxp->packets_in++;
377 		}
378 	} else {
379 		/* It's the debug hook, throw it away.. */
380 		if (hook == xxxp->downstream_hook.hook) {
381 			NG_FREE_ITEM(item);
382 			NG_FREE_M(m);
383 		}
384 	}
385 	return 0;
386 }
387 
388 #if 0
389 /*
390  * If this were a device node, the data may have been received in response
391  * to some interrupt.
392  * in which case it would probably look as follows:
393  */
394 devintr()
395 {
396 	int error;
397 				 * here */
398 
399 	/* get packet from device and send on */
400 	m = MGET(blah blah)
401 
402 	NG_SEND_DATA_ONLY(error, xxxp->upstream_hook.hook, m);
403 				/* see note above in xxx_rcvdata() */
404 				/* and ng_xxx_connect() */
405 }
406 
407 #endif				/* 0 */
408 
409 /*
410  * Do local shutdown processing..
411  * All our links and the name have already been removed.
412  * If we are a persistant device, we might refuse to go away.
413  * In the case of a persistant node we signal the framework that we
414  * are still in business by clearing the NG_INVALID bit. However
415  * If we find the NG_REALLY_DIE bit set, this means that
416  * we REALLY need to die (e.g. hardware removed).
417  * This would have been set using the NG_NODE_REALLY_DIE(node)
418  * macro in some device dependent function (not shown here) before
419  * calling ng_rmnode_self().
420  */
421 static int
422 ng_xxx_shutdown(node_p node)
423 {
424 	const xxx_p privdata = NG_NODE_PRIVATE(node);
425 	int error;
426 
427 #ifndef PERSISTANT_NODE
428 	NG_NODE_SET_PRIVATE(node, NULL);
429 	NG_NODE_UNREF(privdata->node);
430 	FREE(privdata, M_NETGRAPH);
431 #else
432 	if (node->nd_flags & NG_REALLY_DIE) {
433 		/*
434 		 * WE came here because the widget card is being unloaded,
435 		 * so stop being persistant.
436 		 * Actually undo all the things we did on creation.
437 		 */
438 		NG_NODE_SET_PRIVATE(node, NULL);
439 		NG_NODE_UNREF(privdata->node);
440 		FREE(privdata, M_NETGRAPH);
441 		return (0);
442         }
443 	node->nd_flags &= ~NG_INVALID;		/* reset invalid flag */
444 #endif /* PERSISTANT_NODE */
445 	return (0);
446 }
447 
448 /*
449  * This is called once we've already connected a new hook to the other node.
450  * It gives us a chance to balk at the last minute.
451  */
452 static int
453 ng_xxx_connect(hook_p hook)
454 {
455 #if 0
456 	/*
457 	 * If we were a driver running at other than splnet then
458 	 * we should set the QUEUE bit on the edge so that we
459 	 * will deliver by queing.
460 	 */
461 	if /*it is the upstream hook */
462 	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
463 #endif
464 #if 0
465 	/*
466 	 * If for some reason we want incoming date to be queued
467 	 * by the NETISR system and delivered later we can set the same bit on
468 	 * OUR hook. (maybe to allow unwinding of the stack)
469 	 */
470 
471 	if (NG_HOOK_PRIVATE(hook)) {
472 		int dlci;
473 		/*
474 		 * If it's dlci 1023, requeue it so that it's handled
475 		 * at a lower priority. This is how a node decides to
476 		 * defer a data message.
477 		 */
478 		dlci = ((struct XXX_hookinfo *) NG_HOOK_PRIVATE(hook))->dlci;
479 		if (dlci == 1023) {
480 			NG_HOOK_FORCE_QUEUE(hook);
481 		}
482 #endif
483 	/* otherwise be really amiable and just say "YUP that's OK by me! " */
484 	return (0);
485 }
486 
487 /*
488  * Dook disconnection
489  *
490  * For this type, removal of the last link destroys the node
491  */
492 static int
493 ng_xxx_disconnect(hook_p hook)
494 {
495 	if (NG_HOOK_PRIVATE(hook))
496 		((struct XXX_hookinfo *) (NG_HOOK_PRIVATE(hook)))->hook = NULL;
497 	if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
498 	&& (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))) /* already shutting down? */
499 		ng_rmnode_self(NG_HOOK_NODE(hook));
500 	return (0);
501 }
502 
503