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