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