ng_tty.c revision 132163
1
2/*
3 * ng_tty.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: Archie Cobbs <archie@freebsd.org>
38 *
39 * $FreeBSD: head/sys/netgraph/ng_tty.c 132163 2004-07-14 20:31:05Z rwatson $
40 * $Whistle: ng_tty.c,v 1.21 1999/11/01 09:24:52 julian Exp $
41 */
42
43/*
44 * This file implements a terminal line discipline that is also a
45 * netgraph node. Installing this line discipline on a terminal device
46 * instantiates a new netgraph node of this type, which allows access
47 * to the device via the "hook" hook of the node.
48 *
49 * Once the line discipline is installed, you can find out the name
50 * of the corresponding netgraph node via a NGIOCGINFO ioctl().
51 *
52 * Incoming characters are delievered to the hook one at a time, each
53 * in its own mbuf. You may optionally define a ``hotchar,'' which causes
54 * incoming characters to be buffered up until either the hotchar is
55 * seen or the mbuf is full (MHLEN bytes). Then all buffered characters
56 * are immediately delivered.
57 *
58 * NOTE: This node operates at spltty().
59 */
60
61#include <sys/param.h>
62#include <sys/systm.h>
63#include <sys/kernel.h>
64#include <sys/conf.h>
65#include <sys/mbuf.h>
66#include <sys/malloc.h>
67#include <sys/fcntl.h>
68#include <sys/tty.h>
69#include <sys/ttycom.h>
70#include <sys/syslog.h>
71#include <sys/errno.h>
72#include <sys/ioccom.h>
73
74#include <netgraph/ng_message.h>
75#include <netgraph/netgraph.h>
76#include <netgraph/ng_tty.h>
77
78/* Misc defs */
79#define MAX_MBUFQ		3	/* Max number of queued mbufs */
80#define NGT_HIWATER		400	/* High water mark on output */
81
82/* Per-node private info */
83struct ngt_sc {
84	struct	tty *tp;		/* Terminal device */
85	node_p	node;			/* Netgraph node */
86	hook_p	hook;			/* Netgraph hook */
87	struct	mbuf *m;		/* Incoming data buffer */
88	struct	mbuf *qhead, **qtail;	/* Queue of outgoing mbuf's */
89	short	qlen;			/* Length of queue */
90	short	hotchar;		/* Hotchar, or -1 if none */
91	u_int	flags;			/* Flags */
92	struct	callout_handle chand;	/* See man timeout(9) */
93};
94typedef struct ngt_sc *sc_p;
95
96/* Flags */
97#define FLG_TIMEOUT		0x0001	/* A timeout is pending */
98#define FLG_DEBUG		0x0002
99
100/* Debugging */
101#ifdef INVARIANTS
102#define QUEUECHECK(sc)							\
103    do {								\
104      struct mbuf	**mp;						\
105      int		k;						\
106									\
107      for (k = 0, mp = &sc->qhead;					\
108	k <= MAX_MBUFQ && *mp;						\
109	k++, mp = &(*mp)->m_nextpkt);					\
110      if (k != sc->qlen || k > MAX_MBUFQ || *mp || mp != sc->qtail)	\
111	panic("%s: queue", __func__);					\
112    } while (0)
113#else
114#define QUEUECHECK(sc)	do {} while (0)
115#endif
116
117/* Line discipline methods */
118static int	ngt_open(struct cdev *dev, struct tty *tp);
119static int	ngt_close(struct tty *tp, int flag);
120static int	ngt_read(struct tty *tp, struct uio *uio, int flag);
121static int	ngt_write(struct tty *tp, struct uio *uio, int flag);
122static int	ngt_tioctl(struct tty *tp,
123		    u_long cmd, caddr_t data, int flag, struct thread *);
124static int	ngt_input(int c, struct tty *tp);
125static int	ngt_start(struct tty *tp);
126
127/* Netgraph methods */
128static ng_constructor_t	ngt_constructor;
129static ng_rcvmsg_t	ngt_rcvmsg;
130static ng_shutdown_t	ngt_shutdown;
131static ng_newhook_t	ngt_newhook;
132static ng_connect_t	ngt_connect;
133static ng_rcvdata_t	ngt_rcvdata;
134static ng_disconnect_t	ngt_disconnect;
135static int	ngt_mod_event(module_t mod, int event, void *data);
136
137/* Other stuff */
138static void	ngt_timeout(void *arg);
139
140#define ERROUT(x)		do { error = (x); goto done; } while (0)
141
142/* Line discipline descriptor */
143static struct linesw ngt_disc = {
144	ngt_open,
145	ngt_close,
146	ngt_read,
147	ngt_write,
148	ngt_tioctl,
149	ngt_input,
150	ngt_start,
151	ttymodem
152};
153
154/* Netgraph node type descriptor */
155static struct ng_type typestruct = {
156	.version =	NG_ABI_VERSION,
157	.name =		NG_TTY_NODE_TYPE,
158	.mod_event =	ngt_mod_event,
159	.constructor =	ngt_constructor,
160	.rcvmsg =	ngt_rcvmsg,
161	.shutdown =	ngt_shutdown,
162	.newhook =	ngt_newhook,
163	.connect =	ngt_connect,
164	.rcvdata =	ngt_rcvdata,
165	.disconnect =	ngt_disconnect,
166};
167NETGRAPH_INIT(tty, &typestruct);
168
169/*
170 * XXXRW: ngt_unit is protected by ng_tty_mtx.  ngt_ldisc is constant once
171 * ng_tty is initialized.  ngt_nodeop_ok is untouched, and might want to be a
172 * sleep lock in the future?
173 */
174static int ngt_unit;
175static int ngt_nodeop_ok;	/* OK to create/remove node */
176static int ngt_ldisc;
177
178static struct mtx	ng_tty_mtx;
179MTX_SYSINIT(ng_tty, &ng_tty_mtx, "ng_tty", MTX_DEF);
180
181/******************************************************************
182		    LINE DISCIPLINE METHODS
183******************************************************************/
184
185/*
186 * Set our line discipline on the tty.
187 * Called from device open routine or ttioctl() at >= splsofttty()
188 */
189static int
190ngt_open(struct cdev *dev, struct tty *tp)
191{
192	struct thread *const td = curthread;	/* XXX */
193	char name[sizeof(NG_TTY_NODE_TYPE) + 8];
194	sc_p sc;
195	int s, error;
196
197	/* Super-user only */
198	if ((error = suser(td)))
199		return (error);
200	s = splnet();
201	(void) spltty();	/* XXX is this necessary? */
202
203	tp->t_hotchar = NG_TTY_DFL_HOTCHAR;
204
205	/* Initialize private struct */
206	MALLOC(sc, sc_p, sizeof(*sc), M_NETGRAPH, M_WAITOK | M_ZERO);
207	if (sc == NULL) {
208		error = ENOMEM;
209		goto done;
210	}
211	sc->tp = tp;
212	sc->hotchar = NG_TTY_DFL_HOTCHAR;
213	sc->qtail = &sc->qhead;
214	QUEUECHECK(sc);
215	callout_handle_init(&sc->chand);
216
217	/* Setup netgraph node */
218	ngt_nodeop_ok = 1;
219	error = ng_make_node_common(&typestruct, &sc->node);
220	ngt_nodeop_ok = 0;
221	if (error) {
222		FREE(sc, M_NETGRAPH);
223		goto done;
224	}
225	mtx_lock(&ng_tty_mtx);
226	snprintf(name, sizeof(name), "%s%d", typestruct.name, ngt_unit++);
227	mtx_unlock(&ng_tty_mtx);
228
229	/* Assign node its name */
230	if ((error = ng_name_node(sc->node, name))) {
231		log(LOG_ERR, "%s: node name exists?\n", name);
232		ngt_nodeop_ok = 1;
233		NG_NODE_UNREF(sc->node);
234		ngt_nodeop_ok = 0;
235		goto done;
236	}
237
238	/* Set back pointers */
239	NG_NODE_SET_PRIVATE(sc->node, sc);
240	tp->t_sc = (caddr_t) sc;
241
242	/*
243	 * Pre-allocate cblocks to the an appropriate amount.
244	 * I'm not sure what is appropriate.
245	 */
246	ttyflush(tp, FREAD | FWRITE);
247	clist_alloc_cblocks(&tp->t_canq, 0, 0);
248	clist_alloc_cblocks(&tp->t_rawq, 0, 0);
249	clist_alloc_cblocks(&tp->t_outq,
250	    MLEN + NGT_HIWATER, MLEN + NGT_HIWATER);
251
252done:
253	/* Done */
254	splx(s);
255	return (error);
256}
257
258/*
259 * Line specific close routine, called from device close routine
260 * and from ttioctl at >= splsofttty(). This causes the node to
261 * be destroyed as well.
262 */
263static int
264ngt_close(struct tty *tp, int flag)
265{
266	const sc_p sc = (sc_p) tp->t_sc;
267	int s;
268
269	s = spltty();
270	ttyflush(tp, FREAD | FWRITE);
271	clist_free_cblocks(&tp->t_outq);
272	if (sc != NULL) {
273		if (sc->flags & FLG_TIMEOUT) {
274			untimeout(ngt_timeout, sc, sc->chand);
275			sc->flags &= ~FLG_TIMEOUT;
276		}
277		ngt_nodeop_ok = 1;
278		ng_rmnode_self(sc->node);
279		ngt_nodeop_ok = 0;
280		tp->t_sc = NULL;
281	}
282	splx(s);
283	return (0);
284}
285
286/*
287 * Once the device has been turned into a node, we don't allow reading.
288 */
289static int
290ngt_read(struct tty *tp, struct uio *uio, int flag)
291{
292	return (EIO);
293}
294
295/*
296 * Once the device has been turned into a node, we don't allow writing.
297 */
298static int
299ngt_write(struct tty *tp, struct uio *uio, int flag)
300{
301	return (EIO);
302}
303
304/*
305 * We implement the NGIOCGINFO ioctl() defined in ng_message.h.
306 */
307static int
308ngt_tioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, struct thread *td)
309{
310	const sc_p sc = (sc_p) tp->t_sc;
311	int s, error = 0;
312
313	s = spltty();
314	switch (cmd) {
315	case NGIOCGINFO:
316	    {
317		struct nodeinfo *const ni = (struct nodeinfo *) data;
318		const node_p node = sc->node;
319
320		bzero(ni, sizeof(*ni));
321		if (NG_NODE_HAS_NAME(node))
322			strncpy(ni->name, NG_NODE_NAME(node), sizeof(ni->name) - 1);
323		strncpy(ni->type, node->nd_type->name, sizeof(ni->type) - 1);
324		ni->id = (u_int32_t) ng_node2ID(node);
325		ni->hooks = NG_NODE_NUMHOOKS(node);
326		break;
327	    }
328	default:
329		ERROUT(ENOIOCTL);
330	}
331done:
332	splx(s);
333	return (error);
334}
335
336/*
337 * Receive data coming from the device. We get one character at
338 * a time, which is kindof silly.
339 * Only guaranteed to be at splsofttty() or spltty().
340 */
341static int
342ngt_input(int c, struct tty *tp)
343{
344	const sc_p sc = (sc_p) tp->t_sc;
345	const node_p node = sc->node;
346	struct mbuf *m;
347	int s, error = 0;
348
349	if (!sc || tp != sc->tp)
350		return (0);
351	s = spltty();
352	if (!sc->hook)
353		ERROUT(0);
354
355	/* Check for error conditions */
356	if ((tp->t_state & TS_CONNECTED) == 0) {
357		if (sc->flags & FLG_DEBUG)
358			log(LOG_DEBUG, "%s: no carrier\n", NG_NODE_NAME(node));
359		ERROUT(0);
360	}
361	if (c & TTY_ERRORMASK) {
362		/* framing error or overrun on this char */
363		if (sc->flags & FLG_DEBUG)
364			log(LOG_DEBUG, "%s: line error %x\n",
365			    NG_NODE_NAME(node), c & TTY_ERRORMASK);
366		ERROUT(0);
367	}
368	c &= TTY_CHARMASK;
369
370	/* Get a new header mbuf if we need one */
371	if (!(m = sc->m)) {
372		MGETHDR(m, M_DONTWAIT, MT_DATA);
373		if (!m) {
374			if (sc->flags & FLG_DEBUG)
375				log(LOG_ERR,
376				    "%s: can't get mbuf\n", NG_NODE_NAME(node));
377			ERROUT(ENOBUFS);
378		}
379		m->m_len = m->m_pkthdr.len = 0;
380		m->m_pkthdr.rcvif = NULL;
381		sc->m = m;
382	}
383
384	/* Add char to mbuf */
385	*mtod(m, u_char *) = c;
386	m->m_data++;
387	m->m_len++;
388	m->m_pkthdr.len++;
389
390	/* Ship off mbuf if it's time */
391	if (sc->hotchar == -1 || c == sc->hotchar || m->m_len >= MHLEN) {
392		m->m_data = m->m_pktdat;
393		NG_SEND_DATA_ONLY(error, sc->hook, m);
394		sc->m = NULL;
395	}
396done:
397	splx(s);
398	return (error);
399}
400
401/*
402 * This is called when the device driver is ready for more output.
403 * Called from tty system at splsofttty() or spltty().
404 * Also call from ngt_rcv_data() when a new mbuf is available for output.
405 */
406static int
407ngt_start(struct tty *tp)
408{
409	const sc_p sc = (sc_p) tp->t_sc;
410	int s;
411
412	s = spltty();
413	while (tp->t_outq.c_cc < NGT_HIWATER) {	/* XXX 2.2 specific ? */
414		struct mbuf *m = sc->qhead;
415
416		/* Remove first mbuf from queue */
417		if (!m)
418			break;
419		if ((sc->qhead = m->m_nextpkt) == NULL)
420			sc->qtail = &sc->qhead;
421		sc->qlen--;
422		QUEUECHECK(sc);
423
424		/* Send as much of it as possible */
425		while (m) {
426			int     sent;
427
428			sent = m->m_len
429			    - b_to_q(mtod(m, u_char *), m->m_len, &tp->t_outq);
430			m->m_data += sent;
431			m->m_len -= sent;
432			if (m->m_len > 0)
433				break;	/* device can't take no more */
434			m = m_free(m);
435		}
436
437		/* Put remainder of mbuf chain (if any) back on queue */
438		if (m) {
439			m->m_nextpkt = sc->qhead;
440			sc->qhead = m;
441			if (sc->qtail == &sc->qhead)
442				sc->qtail = &m->m_nextpkt;
443			sc->qlen++;
444			QUEUECHECK(sc);
445			break;
446		}
447	}
448
449	/* Call output process whether or not there is any output. We are
450	 * being called in lieu of ttstart and must do what it would. */
451	if (tp->t_oproc != NULL)
452		(*tp->t_oproc) (tp);
453
454	/* This timeout is needed for operation on a pseudo-tty, because the
455	 * pty code doesn't call pppstart after it has drained the t_outq. */
456	if (sc->qhead && (sc->flags & FLG_TIMEOUT) == 0) {
457		sc->chand = timeout(ngt_timeout, sc, 1);
458		sc->flags |= FLG_TIMEOUT;
459	}
460	splx(s);
461	return (0);
462}
463
464/*
465 * We still have data to output to the device, so try sending more.
466 */
467static void
468ngt_timeout(void *arg)
469{
470	const sc_p sc = (sc_p) arg;
471	int s;
472
473	s = spltty();
474	sc->flags &= ~FLG_TIMEOUT;
475	ngt_start(sc->tp);
476	splx(s);
477}
478
479/******************************************************************
480		    NETGRAPH NODE METHODS
481******************************************************************/
482
483/*
484 * Initialize a new node of this type.
485 *
486 * We only allow nodes to be created as a result of setting
487 * the line discipline on a tty, so always return an error if not.
488 */
489static int
490ngt_constructor(node_p node)
491{
492	return (EOPNOTSUPP);
493}
494
495/*
496 * Add a new hook. There can only be one.
497 */
498static int
499ngt_newhook(node_p node, hook_p hook, const char *name)
500{
501	const sc_p sc = NG_NODE_PRIVATE(node);
502	int s, error = 0;
503
504	if (strcmp(name, NG_TTY_HOOK))
505		return (EINVAL);
506	s = spltty();
507	if (sc->hook)
508		ERROUT(EISCONN);
509	sc->hook = hook;
510done:
511	splx(s);
512	return (error);
513}
514
515/*
516 * Set the hooks into queueing mode (for outgoing packets)
517 * Force single client at a time.
518 */
519static int
520ngt_connect(hook_p hook)
521{
522	/*NG_HOOK_FORCE_WRITER(hook);
523	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));*/
524	return (0);
525}
526
527/*
528 * Disconnect the hook
529 */
530static int
531ngt_disconnect(hook_p hook)
532{
533	const sc_p sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
534	int s;
535
536	s = spltty();
537	if (hook != sc->hook)
538		panic(__func__);
539	sc->hook = NULL;
540	m_freem(sc->m);
541	sc->m = NULL;
542	splx(s);
543	return (0);
544}
545
546/*
547 * Remove this node. The does the netgraph portion of the shutdown.
548 * This should only be called indirectly from ngt_close().
549 */
550static int
551ngt_shutdown(node_p node)
552{
553	const sc_p sc = NG_NODE_PRIVATE(node);
554
555	if (!ngt_nodeop_ok)
556		return (EOPNOTSUPP);
557	NG_NODE_SET_PRIVATE(node, NULL);
558	NG_NODE_UNREF(sc->node);
559	m_freem(sc->qhead);
560	m_freem(sc->m);
561	bzero(sc, sizeof(*sc));
562	FREE(sc, M_NETGRAPH);
563	return (0);
564}
565
566/*
567 * Receive incoming data from netgraph system. Put it on our
568 * output queue and start output if necessary.
569 */
570static int
571ngt_rcvdata(hook_p hook, item_p item)
572{
573	const sc_p sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
574	int s, error = 0;
575	struct mbuf *m;
576
577	if (hook != sc->hook)
578		panic(__func__);
579
580	NGI_GET_M(item, m);
581	NG_FREE_ITEM(item);
582	s = spltty();
583	if (sc->qlen >= MAX_MBUFQ)
584		ERROUT(ENOBUFS);
585	m->m_nextpkt = NULL;
586	*sc->qtail = m;
587	sc->qtail = &m->m_nextpkt;
588	sc->qlen++;
589	QUEUECHECK(sc);
590	m = NULL;
591	if (sc->qlen == 1)
592		ngt_start(sc->tp);
593done:
594	splx(s);
595	if (m)
596		m_freem(m);
597	return (error);
598}
599
600/*
601 * Receive control message
602 */
603static int
604ngt_rcvmsg(node_p node, item_p item, hook_p lasthook)
605{
606	const sc_p sc = NG_NODE_PRIVATE(node);
607	struct ng_mesg *resp = NULL;
608	int error = 0;
609	struct ng_mesg *msg;
610
611	NGI_GET_MSG(item, msg);
612	switch (msg->header.typecookie) {
613	case NGM_TTY_COOKIE:
614		switch (msg->header.cmd) {
615		case NGM_TTY_SET_HOTCHAR:
616		    {
617			int     hotchar;
618
619			if (msg->header.arglen != sizeof(int))
620				ERROUT(EINVAL);
621			hotchar = *((int *) msg->data);
622			if (hotchar != (u_char) hotchar && hotchar != -1)
623				ERROUT(EINVAL);
624			sc->hotchar = hotchar;	/* race condition is OK */
625			break;
626		    }
627		case NGM_TTY_GET_HOTCHAR:
628			NG_MKRESPONSE(resp, msg, sizeof(int), M_NOWAIT);
629			if (!resp)
630				ERROUT(ENOMEM);
631			/* Race condition here is OK */
632			*((int *) resp->data) = sc->hotchar;
633			break;
634		default:
635			ERROUT(EINVAL);
636		}
637		break;
638	default:
639		ERROUT(EINVAL);
640	}
641done:
642	NG_RESPOND_MSG(error, node, item, resp);
643	NG_FREE_MSG(msg);
644	return (error);
645}
646
647/******************************************************************
648		    	INITIALIZATION
649******************************************************************/
650
651/*
652 * Handle loading and unloading for this node type
653 */
654static int
655ngt_mod_event(module_t mod, int event, void *data)
656{
657	/* struct ng_type *const type = data;*/
658	int s, error = 0;
659
660	switch (event) {
661	case MOD_LOAD:
662
663		/* Register line discipline */
664		s = spltty();
665		if ((ngt_ldisc = ldisc_register(NETGRAPHDISC, &ngt_disc)) < 0) {
666			splx(s);
667			log(LOG_ERR, "%s: can't register line discipline",
668			    __func__);
669			return (EIO);
670		}
671		splx(s);
672		break;
673
674	case MOD_UNLOAD:
675
676		/* Unregister line discipline */
677		s = spltty();
678		ldisc_deregister(ngt_ldisc);
679		splx(s);
680		break;
681
682	default:
683		error = EOPNOTSUPP;
684		break;
685	}
686	return (error);
687}
688
689