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