xref: /freebsd/sys/netgraph/ng_sample.c (revision a0409676120c1e558d0ade943019934e0f15118d)
1 /*
2  * ng_sample.c
3  */
4 
5 /*-
6  * Copyright (c) 1996-1999 Whistle Communications, Inc.
7  * All rights reserved.
8  *
9  * Subject to the following obligations and disclaimer of warranty, use and
10  * redistribution of this software, in source or object code forms, with or
11  * without modifications are expressly permitted by Whistle Communications;
12  * provided, however, that:
13  * 1. Any and all reproductions of the source or object code must include the
14  *    copyright notice above and the following disclaimer of warranties; and
15  * 2. No rights are granted, in any manner or form, to use Whistle
16  *    Communications, Inc. trademarks, including the mark "WHISTLE
17  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
18  *    such appears in the above copyright notice or in the software.
19  *
20  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
21  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
22  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
23  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
25  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
26  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
27  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
28  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
29  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
36  * OF SUCH DAMAGE.
37  *
38  * Author: Julian Elischer <julian@freebsd.org>
39  *
40  * $FreeBSD$
41  * $Whistle: ng_sample.c,v 1.13 1999/11/01 09:24:52 julian Exp $
42  */
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/mbuf.h>
48 #include <sys/malloc.h>
49 #include <sys/ctype.h>
50 #include <sys/errno.h>
51 #include <sys/syslog.h>
52 
53 #include <netgraph/ng_message.h>
54 #include <netgraph/ng_parse.h>
55 #include <netgraph/ng_sample.h>
56 #include <netgraph/netgraph.h>
57 
58 /* If you do complicated mallocs you may want to do this */
59 /* and use it for your mallocs */
60 #ifdef NG_SEPARATE_MALLOC
61 static MALLOC_DEFINE(M_NETGRAPH_XXX, "netgraph_xxx", "netgraph xxx node");
62 #else
63 #define M_NETGRAPH_XXX M_NETGRAPH
64 #endif
65 
66 /*
67  * This section contains the netgraph method declarations for the
68  * sample node. These methods define the netgraph 'type'.
69  */
70 
71 static ng_constructor_t	ng_xxx_constructor;
72 static ng_rcvmsg_t	ng_xxx_rcvmsg;
73 static ng_shutdown_t	ng_xxx_shutdown;
74 static ng_newhook_t	ng_xxx_newhook;
75 static ng_connect_t	ng_xxx_connect;
76 static ng_rcvdata_t	ng_xxx_rcvdata;
77 static ng_disconnect_t	ng_xxx_disconnect;
78 
79 /* Parse type for struct ngxxxstat */
80 static const struct ng_parse_struct_field ng_xxx_stat_type_fields[]
81 	= NG_XXX_STATS_TYPE_INFO;
82 static const struct ng_parse_type ng_xxx_stat_type = {
83 	&ng_parse_struct_type,
84 	&ng_xxx_stat_type_fields
85 };
86 
87 /* List of commands and how to convert arguments to/from ASCII */
88 static const struct ng_cmdlist ng_xxx_cmdlist[] = {
89 	{
90 	  NGM_XXX_COOKIE,
91 	  NGM_XXX_GET_STATUS,
92 	  "getstatus",
93 	  NULL,
94 	  &ng_xxx_stat_type,
95 	},
96 	{
97 	  NGM_XXX_COOKIE,
98 	  NGM_XXX_SET_FLAG,
99 	  "setflag",
100 	  &ng_parse_int32_type,
101 	  NULL
102 	},
103 	{ 0 }
104 };
105 
106 /* Netgraph node type descriptor */
107 static struct ng_type typestruct = {
108 	.version =	NG_ABI_VERSION,
109 	.name =		NG_XXX_NODE_TYPE,
110 	.constructor =	ng_xxx_constructor,
111 	.rcvmsg =	ng_xxx_rcvmsg,
112 	.shutdown =	ng_xxx_shutdown,
113 	.newhook =	ng_xxx_newhook,
114 /*	.findhook =	ng_xxx_findhook, 	*/
115 	.connect =	ng_xxx_connect,
116 	.rcvdata =	ng_xxx_rcvdata,
117 	.disconnect =	ng_xxx_disconnect,
118 	.cmdlist =	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;
155 
156 	/* Initialize private descriptor */
157 	privdata = malloc(sizeof(*privdata), M_NETGRAPH, M_WAITOK | M_ZERO);
158 	for (i = 0; i < XXX_NUM_DLCIS; i++) {
159 		privdata->channel[i].dlci = -2;
160 		privdata->channel[i].channel = i;
161 	}
162 
163 	/* Link structs together; this counts as our one reference to *nodep */
164 	NG_NODE_SET_PRIVATE(node, privdata);
165 	privdata->node = node;
166 	return (0);
167 }
168 
169 /*
170  * Give our ok for a hook to be added...
171  * If we are not running this might kick a device into life.
172  * Possibly decode information out of the hook name.
173  * Add the hook's private info to the hook structure.
174  * (if we had some). In this example, we assume that there is a
175  * an array of structs, called 'channel' in the private info,
176  * one for each active channel. The private
177  * pointer of each hook points to the appropriate XXX_hookinfo struct
178  * so that the source of an input packet is easily identified.
179  * (a dlci is a frame relay channel)
180  */
181 static int
182 ng_xxx_newhook(node_p node, hook_p hook, const char *name)
183 {
184 	const xxx_p xxxp = NG_NODE_PRIVATE(node);
185 	const char *cp;
186 	int dlci = 0;
187 	int chan;
188 
189 #if 0
190 	/* Possibly start up the device if it's not already going */
191 	if ((xxxp->flags & SCF_RUNNING) == 0) {
192 		ng_xxx_start_hardware(xxxp);
193 	}
194 #endif
195 
196 	/* Example of how one might use hooks with embedded numbers: All
197 	 * hooks start with 'dlci' and have a decimal trailing channel
198 	 * number up to 4 digits Use the leadin defined int he associated .h
199 	 * file. */
200 	if (strncmp(name,
201 	    NG_XXX_HOOK_DLCI_LEADIN, strlen(NG_XXX_HOOK_DLCI_LEADIN)) == 0) {
202 		char *eptr;
203 
204 		cp = name + strlen(NG_XXX_HOOK_DLCI_LEADIN);
205 		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
206 			return (EINVAL);
207 		dlci = (int)strtoul(cp, &eptr, 10);
208 		if (*eptr != '\0' || dlci < 0 || dlci > 1023)
209 			return (EINVAL);
210 
211 		/* We have a dlci, now either find it, or allocate it */
212 		for (chan = 0; chan < XXX_NUM_DLCIS; chan++)
213 			if (xxxp->channel[chan].dlci == dlci)
214 				break;
215 		if (chan == XXX_NUM_DLCIS) {
216 			for (chan = 0; chan < XXX_NUM_DLCIS; chan++)
217 				if (xxxp->channel[chan].dlci == -2)
218 					break;
219 			if (chan == XXX_NUM_DLCIS)
220 				return (ENOBUFS);
221 			xxxp->channel[chan].dlci = dlci;
222 		}
223 		if (xxxp->channel[chan].hook != NULL)
224 			return (EADDRINUSE);
225 		NG_HOOK_SET_PRIVATE(hook, xxxp->channel + chan);
226 		xxxp->channel[chan].hook = hook;
227 		return (0);
228 	} else if (strcmp(name, NG_XXX_HOOK_DOWNSTREAM) == 0) {
229 		/* Example of simple predefined hooks. */
230 		/* do something specific to the downstream connection */
231 		xxxp->downstream_hook.hook = hook;
232 		NG_HOOK_SET_PRIVATE(hook, &xxxp->downstream_hook);
233 	} else if (strcmp(name, NG_XXX_HOOK_DEBUG) == 0) {
234 		/* do something specific to a debug connection */
235 		xxxp->debughook = hook;
236 		NG_HOOK_SET_PRIVATE(hook, NULL);
237 	} else
238 		return (EINVAL);	/* not a hook we know about */
239 	return(0);
240 }
241 
242 /*
243  * Get a netgraph control message.
244  * We actually receive a queue item that has a pointer to the message.
245  * If we free the item, the message will be freed too, unless we remove
246  * it from the item using NGI_GET_MSG();
247  * The return address is also stored in the item, as an ng_ID_t,
248  * accessible as NGI_RETADDR(item);
249  * Check it is one we understand. If needed, send a response.
250  * We could save the address for an async action later, but don't here.
251  * Always free the message.
252  * The response should be in a malloc'd region that the caller can 'free'.
253  * A response is not required.
254  * Theoretically you could respond defferently to old message types if
255  * the cookie in the header didn't match what we consider to be current
256  * (so that old userland programs could continue to work).
257  */
258 static int
259 ng_xxx_rcvmsg(node_p node, item_p item, hook_p lasthook)
260 {
261 	const xxx_p xxxp = NG_NODE_PRIVATE(node);
262 	struct ng_mesg *resp = NULL;
263 	int error = 0;
264 	struct ng_mesg *msg;
265 
266 	NGI_GET_MSG(item, msg);
267 	/* Deal with message according to cookie and command */
268 	switch (msg->header.typecookie) {
269 	case NGM_XXX_COOKIE:
270 		switch (msg->header.cmd) {
271 		case NGM_XXX_GET_STATUS:
272 		    {
273 			struct ngxxxstat *stats;
274 
275 			NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
276 			if (!resp) {
277 				error = ENOMEM;
278 				break;
279 			}
280 			stats = (struct ngxxxstat *) resp->data;
281 			stats->packets_in = xxxp->packets_in;
282 			stats->packets_out = xxxp->packets_out;
283 			break;
284 		    }
285 		case NGM_XXX_SET_FLAG:
286 			if (msg->header.arglen != sizeof(u_int32_t)) {
287 				error = EINVAL;
288 				break;
289 			}
290 			xxxp->flags = *((u_int32_t *) msg->data);
291 			break;
292 		default:
293 			error = EINVAL;		/* unknown command */
294 			break;
295 		}
296 		break;
297 	default:
298 		error = EINVAL;			/* unknown cookie type */
299 		break;
300 	}
301 
302 	/* Take care of synchronous response, if any */
303 	NG_RESPOND_MSG(error, node, item, resp);
304 	/* Free the message and return */
305 	NG_FREE_MSG(msg);
306 	return(error);
307 }
308 
309 /*
310  * Receive data, and do something with it.
311  * Actually we receive a queue item which holds the data.
312  * If we free the item it will also free the data unless we have
313  * previously disassociated it using the NGI_GET_M() macro.
314  * Possibly send it out on another link after processing.
315  * Possibly do something different if it comes from different
316  * hooks. The caller will never free m, so if we use up this data or
317  * abort we must free it.
318  *
319  * If we want, we may decide to force this data to be queued and reprocessed
320  * at the netgraph NETISR time.
321  * We would do that by setting the HK_QUEUE flag on our hook. We would do that
322  * in the connect() method.
323  */
324 static int
325 ng_xxx_rcvdata(hook_p hook, item_p item )
326 {
327 	const xxx_p xxxp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
328 	int chan = -2;
329 	int dlci = -2;
330 	int error;
331 	struct mbuf *m;
332 
333 	NGI_GET_M(item, m);
334 	if (NG_HOOK_PRIVATE(hook)) {
335 		dlci = ((struct XXX_hookinfo *) NG_HOOK_PRIVATE(hook))->dlci;
336 		chan = ((struct XXX_hookinfo *) NG_HOOK_PRIVATE(hook))->channel;
337 		if (dlci != -1) {
338 			/* If received on a DLCI hook process for this
339 			 * channel and pass it to the downstream module.
340 			 * Normally one would add a multiplexing header at
341 			 * the front here */
342 			/* M_PREPEND(....)	; */
343 			/* mtod(m, xxxxxx)->dlci = dlci; */
344 			NG_FWD_NEW_DATA(error, item,
345 				xxxp->downstream_hook.hook, m);
346 			xxxp->packets_out++;
347 		} else {
348 			/* data came from the multiplexed link */
349 			dlci = 1;	/* get dlci from header */
350 			/* madjust(....) *//* chop off header */
351 			for (chan = 0; chan < XXX_NUM_DLCIS; chan++)
352 				if (xxxp->channel[chan].dlci == dlci)
353 					break;
354 			if (chan == XXX_NUM_DLCIS) {
355 				NG_FREE_ITEM(item);
356 				NG_FREE_M(m);
357 				return (ENETUNREACH);
358 			}
359 			/* If we were called at splnet, use the following:
360 			 * NG_SEND_DATA_ONLY(error, otherhook, m); if this
361 			 * node is running at some SPL other than SPLNET
362 			 * then you should use instead: error =
363 			 * ng_queueit(otherhook, m, NULL); m = NULL;
364 			 * This queues the data using the standard NETISR
365 			 * system and schedules the data to be picked
366 			 * up again once the system has moved to SPLNET and
367 			 * the processing of the data can continue. After
368 			 * these are run 'm' should be considered
369 			 * as invalid and NG_SEND_DATA actually zaps them. */
370 			NG_FWD_NEW_DATA(error, item,
371 				xxxp->channel[chan].hook, m);
372 			xxxp->packets_in++;
373 		}
374 	} else {
375 		/* It's the debug hook, throw it away.. */
376 		if (hook == xxxp->downstream_hook.hook) {
377 			NG_FREE_ITEM(item);
378 			NG_FREE_M(m);
379 		}
380 	}
381 	return 0;
382 }
383 
384 #if 0
385 /*
386  * If this were a device node, the data may have been received in response
387  * to some interrupt.
388  * in which case it would probably look as follows:
389  */
390 devintr()
391 {
392 	int error;
393 
394 	/* get packet from device and send on */
395 	m = MGET(blah blah)
396 
397 	NG_SEND_DATA_ONLY(error, xxxp->upstream_hook.hook, m);
398 				/* see note above in xxx_rcvdata() */
399 				/* and ng_xxx_connect() */
400 }
401 
402 #endif				/* 0 */
403 
404 /*
405  * Do local shutdown processing..
406  * All our links and the name have already been removed.
407  * If we are a persistent device, we might refuse to go away.
408  * In the case of a persistent node we signal the framework that we
409  * are still in business by clearing the NGF_INVALID bit. However
410  * If we find the NGF_REALLY_DIE bit set, this means that
411  * we REALLY need to die (e.g. hardware removed).
412  * This would have been set using the NG_NODE_REALLY_DIE(node)
413  * macro in some device dependent function (not shown here) before
414  * calling ng_rmnode_self().
415  */
416 static int
417 ng_xxx_shutdown(node_p node)
418 {
419 	const xxx_p privdata = NG_NODE_PRIVATE(node);
420 
421 #ifndef PERSISTANT_NODE
422 	NG_NODE_SET_PRIVATE(node, NULL);
423 	NG_NODE_UNREF(node);
424 	free(privdata, M_NETGRAPH);
425 #else
426 	if (node->nd_flags & NGF_REALLY_DIE) {
427 		/*
428 		 * WE came here because the widget card is being unloaded,
429 		 * so stop being persistent.
430 		 * Actually undo all the things we did on creation.
431 		 */
432 		NG_NODE_SET_PRIVATE(node, NULL);
433 		NG_NODE_UNREF(privdata->node);
434 		free(privdata, M_NETGRAPH);
435 		return (0);
436 	}
437 	NG_NODE_REVIVE(node);		/* tell ng_rmnode() we will persist */
438 #endif /* PERSISTANT_NODE */
439 	return (0);
440 }
441 
442 /*
443  * This is called once we've already connected a new hook to the other node.
444  * It gives us a chance to balk at the last minute.
445  */
446 static int
447 ng_xxx_connect(hook_p hook)
448 {
449 #if 0
450 	/*
451 	 * If we were a driver running at other than splnet then
452 	 * we should set the QUEUE bit on the edge so that we
453 	 * will deliver by queing.
454 	 */
455 	if /*it is the upstream hook */
456 	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
457 #endif
458 #if 0
459 	/*
460 	 * If for some reason we want incoming date to be queued
461 	 * by the NETISR system and delivered later we can set the same bit on
462 	 * OUR hook. (maybe to allow unwinding of the stack)
463 	 */
464 
465 	if (NG_HOOK_PRIVATE(hook)) {
466 		int dlci;
467 		/*
468 		 * If it's dlci 1023, requeue it so that it's handled
469 		 * at a lower priority. This is how a node decides to
470 		 * defer a data message.
471 		 */
472 		dlci = ((struct XXX_hookinfo *) NG_HOOK_PRIVATE(hook))->dlci;
473 		if (dlci == 1023) {
474 			NG_HOOK_FORCE_QUEUE(hook);
475 		}
476 #endif
477 	/* otherwise be really amiable and just say "YUP that's OK by me! " */
478 	return (0);
479 }
480 
481 /*
482  * Hook disconnection
483  *
484  * For this type, removal of the last link destroys the node
485  */
486 static int
487 ng_xxx_disconnect(hook_p hook)
488 {
489 	if (NG_HOOK_PRIVATE(hook))
490 		((struct XXX_hookinfo *) (NG_HOOK_PRIVATE(hook)))->hook = NULL;
491 	if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
492 	&& (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))) /* already shutting down? */
493 		ng_rmnode_self(NG_HOOK_NODE(hook));
494 	return (0);
495 }
496