xref: /freebsd/sys/netgraph/ng_tty.c (revision 031beb4e239bfce798af17f5fe8dba8bcaf13d99)
1 /*
2  * ng_tty.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: Archie Cobbs <archie@freebsd.org>
39  *
40  * Updated by Andrew Thompson <thompsa@FreeBSD.org> for MPSAFE TTY.
41  * $Whistle: ng_tty.c,v 1.21 1999/11/01 09:24:52 julian Exp $
42  */
43 
44 /*
45  * This file implements TTY hooks to link in to the netgraph system.  The node
46  * is created and then passed the callers opened TTY file descriptor number to
47  * NGM_TTY_SET_TTY, this will hook the tty via ttyhook_register().
48  *
49  * Incoming data is delivered directly to ng_tty via the TTY bypass hook as a
50  * buffer pointer and length, this is converted to a mbuf and passed to the
51  * peer.
52  *
53  * If the TTY device does not support bypass then incoming characters are
54  * delivered to the hook one at a time, each in its own mbuf. You may
55  * optionally define a ``hotchar,'' which causes incoming characters to be
56  * buffered up until either the hotchar is seen or the mbuf is full (MHLEN
57  * bytes). Then all buffered characters are immediately delivered.
58  */
59 
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/conf.h>
63 #include <sys/errno.h>
64 #include <sys/fcntl.h>
65 #include <sys/ioccom.h>
66 #include <sys/kernel.h>
67 #include <sys/malloc.h>
68 #include <sys/mbuf.h>
69 #include <sys/priv.h>
70 #include <sys/socket.h>
71 #include <sys/syslog.h>
72 #include <sys/tty.h>
73 #include <sys/ttycom.h>
74 #include <sys/proc.h>
75 
76 #include <net/if.h>
77 #include <net/if_var.h>
78 
79 #include <netgraph/ng_message.h>
80 #include <netgraph/netgraph.h>
81 #include <netgraph/ng_tty.h>
82 
83 /* Per-node private info */
84 struct ngt_softc {
85 	struct tty	*tp;		/* Terminal device */
86 	node_p		node;		/* Netgraph node */
87 	hook_p		hook;		/* Netgraph hook */
88 	struct ifqueue	outq;		/* Queue of outgoing data */
89 	size_t		outqlen;	/* Number of bytes in outq */
90 	struct mbuf	*m;		/* Incoming non-bypass data buffer */
91 	short		hotchar;	/* Hotchar, or -1 if none */
92 	u_int		flags;		/* Flags */
93 };
94 typedef struct ngt_softc *sc_p;
95 
96 /* Flags */
97 #define FLG_DEBUG		0x0002
98 
99 /* Netgraph methods */
100 static ng_constructor_t		ngt_constructor;
101 static ng_rcvmsg_t		ngt_rcvmsg;
102 static ng_shutdown_t		ngt_shutdown;
103 static ng_newhook_t		ngt_newhook;
104 static ng_connect_t		ngt_connect;
105 static ng_rcvdata_t		ngt_rcvdata;
106 static ng_disconnect_t		ngt_disconnect;
107 
108 #define ERROUT(x)		do { error = (x); goto done; } while (0)
109 
110 static th_getc_inject_t		ngt_getc_inject;
111 static th_getc_poll_t		ngt_getc_poll;
112 static th_rint_t		ngt_rint;
113 static th_rint_bypass_t		ngt_rint_bypass;
114 static th_rint_poll_t		ngt_rint_poll;
115 
116 static struct ttyhook ngt_hook = {
117 	.th_getc_inject = ngt_getc_inject,
118 	.th_getc_poll = ngt_getc_poll,
119 	.th_rint = ngt_rint,
120 	.th_rint_bypass = ngt_rint_bypass,
121 	.th_rint_poll = ngt_rint_poll,
122 };
123 
124 /* Netgraph node type descriptor */
125 static struct ng_type typestruct = {
126 	.version =	NG_ABI_VERSION,
127 	.name =		NG_TTY_NODE_TYPE,
128 	.constructor =	ngt_constructor,
129 	.rcvmsg =	ngt_rcvmsg,
130 	.shutdown =	ngt_shutdown,
131 	.newhook =	ngt_newhook,
132 	.connect =	ngt_connect,
133 	.rcvdata =	ngt_rcvdata,
134 	.disconnect =	ngt_disconnect,
135 };
136 NETGRAPH_INIT(tty, &typestruct);
137 
138 #define	NGTLOCK(sc)	IF_LOCK(&sc->outq)
139 #define	NGTUNLOCK(sc)	IF_UNLOCK(&sc->outq)
140 
141 /******************************************************************
142 		    NETGRAPH NODE METHODS
143 ******************************************************************/
144 
145 /*
146  * Initialize a new node of this type.
147  *
148  * We only allow nodes to be created as a result of setting
149  * the line discipline on a tty, so always return an error if not.
150  */
151 static int
152 ngt_constructor(node_p node)
153 {
154 	sc_p sc;
155 
156 	/* Allocate private structure */
157 	sc = malloc(sizeof(*sc), M_NETGRAPH, M_WAITOK | M_ZERO);
158 
159 	NG_NODE_SET_PRIVATE(node, sc);
160 	sc->node = node;
161 
162 	mtx_init(&sc->outq.ifq_mtx, "ng_tty node+queue", NULL, MTX_DEF);
163 	IFQ_SET_MAXLEN(&sc->outq, ifqmaxlen);
164 
165 	return (0);
166 }
167 
168 /*
169  * Add a new hook. There can only be one.
170  */
171 static int
172 ngt_newhook(node_p node, hook_p hook, const char *name)
173 {
174 	const sc_p sc = NG_NODE_PRIVATE(node);
175 
176 	if (strcmp(name, NG_TTY_HOOK))
177 		return (EINVAL);
178 
179 	if (sc->hook)
180 		return (EISCONN);
181 
182 	NGTLOCK(sc);
183 	sc->hook = hook;
184 	NGTUNLOCK(sc);
185 
186 	return (0);
187 }
188 
189 /*
190  * Set the hook into queueing mode (for outgoing packets),
191  * so that we wont deliver mbuf through the whole graph holding
192  * tty locks.
193  */
194 static int
195 ngt_connect(hook_p hook)
196 {
197 	NG_HOOK_FORCE_QUEUE(hook);
198 	return (0);
199 }
200 
201 /*
202  * Disconnect the hook
203  */
204 static int
205 ngt_disconnect(hook_p hook)
206 {
207 	const sc_p sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
208 
209 	if (hook != sc->hook)
210 		panic("%s", __func__);
211 
212 	NGTLOCK(sc);
213 	sc->hook = NULL;
214 	NGTUNLOCK(sc);
215 
216 	return (0);
217 }
218 
219 /*
220  * Remove this node. The does the netgraph portion of the shutdown.
221  */
222 static int
223 ngt_shutdown(node_p node)
224 {
225 	const sc_p sc = NG_NODE_PRIVATE(node);
226 	struct tty *tp;
227 
228 	tp = sc->tp;
229 	if (tp != NULL) {
230 		tty_lock(tp);
231 		ttyhook_unregister(tp);
232 	}
233 	/* Free resources */
234 	IF_DRAIN(&sc->outq);
235 	mtx_destroy(&(sc)->outq.ifq_mtx);
236 	NG_NODE_UNREF(sc->node);
237 	free(sc, M_NETGRAPH);
238 
239 	return (0);
240 }
241 
242 /*
243  * Receive control message
244  */
245 static int
246 ngt_rcvmsg(node_p node, item_p item, hook_p lasthook)
247 {
248 	struct proc *p;
249 	const sc_p sc = NG_NODE_PRIVATE(node);
250 	struct ng_mesg *msg, *resp = NULL;
251 	int error = 0;
252 
253 	NGI_GET_MSG(item, msg);
254 	switch (msg->header.typecookie) {
255 	case NGM_TTY_COOKIE:
256 		switch (msg->header.cmd) {
257 		case NGM_TTY_SET_TTY:
258 			if (sc->tp != NULL)
259 				return (EBUSY);
260 
261 			p = pfind(((int *)msg->data)[0]);
262 			if (p == NULL || (p->p_flag & P_WEXIT))
263 				return (ESRCH);
264 			_PHOLD(p);
265 			PROC_UNLOCK(p);
266 			error = ttyhook_register(&sc->tp, p, ((int *)msg->data)[1],
267 			    &ngt_hook, sc);
268 			PRELE(p);
269 			if (error != 0)
270 				return (error);
271 			break;
272 		case NGM_TTY_SET_HOTCHAR:
273 		    {
274 			int     hotchar;
275 
276 			if (msg->header.arglen != sizeof(int))
277 				ERROUT(EINVAL);
278 			hotchar = *((int *) msg->data);
279 			if (hotchar != (u_char) hotchar && hotchar != -1)
280 				ERROUT(EINVAL);
281 			sc->hotchar = hotchar;	/* race condition is OK */
282 			break;
283 		    }
284 		case NGM_TTY_GET_HOTCHAR:
285 			NG_MKRESPONSE(resp, msg, sizeof(int), M_NOWAIT);
286 			if (!resp)
287 				ERROUT(ENOMEM);
288 			/* Race condition here is OK */
289 			*((int *) resp->data) = sc->hotchar;
290 			break;
291 		default:
292 			ERROUT(EINVAL);
293 		}
294 		break;
295 	default:
296 		ERROUT(EINVAL);
297 	}
298 done:
299 	NG_RESPOND_MSG(error, node, item, resp);
300 	NG_FREE_MSG(msg);
301 	return (error);
302 }
303 
304 /*
305  * Receive incoming data from netgraph system. Put it on our
306  * output queue and start output if necessary.
307  */
308 static int
309 ngt_rcvdata(hook_p hook, item_p item)
310 {
311 	const sc_p sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
312 	struct tty *tp = sc->tp;
313 	struct mbuf *m;
314 
315 	if (hook != sc->hook)
316 		panic("%s", __func__);
317 
318 	NGI_GET_M(item, m);
319 	NG_FREE_ITEM(item);
320 
321 	if (tp == NULL) {
322 		NG_FREE_M(m);
323 		return (ENXIO);
324 	}
325 
326 	IF_LOCK(&sc->outq);
327 	if (_IF_QFULL(&sc->outq)) {
328 		IF_UNLOCK(&sc->outq);
329 		NG_FREE_M(m);
330 		return (ENOBUFS);
331 	}
332 
333 	_IF_ENQUEUE(&sc->outq, m);
334 	sc->outqlen += m->m_pkthdr.len;
335 	IF_UNLOCK(&sc->outq);
336 
337 	/* notify the TTY that data is ready */
338 	tty_lock(tp);
339 	if (!tty_gone(tp))
340 		ttydevsw_outwakeup(tp);
341 	tty_unlock(tp);
342 
343 	return (0);
344 }
345 
346 static size_t
347 ngt_getc_inject(struct tty *tp, void *buf, size_t len)
348 {
349 	sc_p sc = ttyhook_softc(tp);
350 	size_t total = 0;
351 	int length;
352 
353 	while (len) {
354 		struct mbuf *m;
355 
356 		/* Remove first mbuf from queue */
357 		IF_DEQUEUE(&sc->outq, m);
358 		if (m == NULL)
359 			break;
360 
361 		/* Send as much of it as possible */
362 		while (m != NULL) {
363 			length = min(m->m_len, len);
364 			memcpy((char *)buf + total, mtod(m, char *), length);
365 
366 			m->m_data += length;
367 			m->m_len -= length;
368 			total += length;
369 			len -= length;
370 
371 			if (m->m_len > 0)
372 				break;	/* device can't take any more */
373 			m = m_free(m);
374 		}
375 
376 		/* Put remainder of mbuf chain (if any) back on queue */
377 		if (m != NULL) {
378 			IF_PREPEND(&sc->outq, m);
379 			break;
380 		}
381 	}
382 	IF_LOCK(&sc->outq);
383 	sc->outqlen -= total;
384 	IF_UNLOCK(&sc->outq);
385 	MPASS(sc->outqlen >= 0);
386 
387 	return (total);
388 }
389 
390 static size_t
391 ngt_getc_poll(struct tty *tp)
392 {
393 	sc_p sc = ttyhook_softc(tp);
394 
395 	return (sc->outqlen);
396 }
397 
398 /*
399  * Optimised TTY input.
400  *
401  * We get a buffer pointer to hopefully a complete data frame. Do not check for
402  * the hotchar, just pass it on.
403  */
404 static size_t
405 ngt_rint_bypass(struct tty *tp, const void *buf, size_t len)
406 {
407 	sc_p sc = ttyhook_softc(tp);
408 	node_p node = sc->node;
409 	struct mbuf *m, *mb;
410 	size_t total = 0;
411 	int error = 0, length;
412 
413 	tty_assert_locked(tp);
414 
415 	if (sc->hook == NULL)
416 		return (0);
417 
418 	m = m_getm2(NULL, len, M_NOWAIT, MT_DATA, M_PKTHDR);
419 	if (m == NULL) {
420 		if (sc->flags & FLG_DEBUG)
421 			log(LOG_ERR,
422 			    "%s: can't get mbuf\n", NG_NODE_NAME(node));
423 		return (0);
424 	}
425 	m->m_pkthdr.rcvif = NULL;
426 
427 	for (mb = m; mb != NULL; mb = mb->m_next) {
428 		length = min(M_TRAILINGSPACE(mb), len - total);
429 
430 		memcpy(mtod(m, char *), (const char *)buf + total, length);
431 		mb->m_len = length;
432 		total += length;
433 		m->m_pkthdr.len += length;
434 	}
435 	if (sc->m != NULL) {
436 		/*
437 		 * Odd, we have changed from non-bypass to bypass. It is
438 		 * unlikely but not impossible, flush the data first.
439 		 */
440 		NG_SEND_DATA_ONLY(error, sc->hook, sc->m);
441 		sc->m = NULL;
442 	}
443 	NG_SEND_DATA_ONLY(error, sc->hook, m);
444 
445 	return (total);
446 }
447 
448 /*
449  * Receive data coming from the device one char at a time, when it is not in
450  * bypass mode.
451  */
452 static int
453 ngt_rint(struct tty *tp, char c, int flags)
454 {
455 	sc_p sc = ttyhook_softc(tp);
456 	node_p node = sc->node;
457 	struct mbuf *m;
458 	int error = 0;
459 
460 	tty_assert_locked(tp);
461 
462 	if (sc->hook == NULL)
463 		return (0);
464 
465 	if (flags != 0) {
466 		/* framing error or overrun on this char */
467 		if (sc->flags & FLG_DEBUG)
468 			log(LOG_DEBUG, "%s: line error %x\n",
469 			    NG_NODE_NAME(node), flags);
470 		return (0);
471 	}
472 
473 	/* Get a new header mbuf if we need one */
474 	if (!(m = sc->m)) {
475 		MGETHDR(m, M_NOWAIT, MT_DATA);
476 		if (!m) {
477 			if (sc->flags & FLG_DEBUG)
478 				log(LOG_ERR,
479 				    "%s: can't get mbuf\n", NG_NODE_NAME(node));
480 			return (ENOBUFS);
481 		}
482 		m->m_len = m->m_pkthdr.len = 0;
483 		m->m_pkthdr.rcvif = NULL;
484 		sc->m = m;
485 	}
486 
487 	/* Add char to mbuf */
488 	*mtod(m, u_char *) = c;
489 	m->m_data++;
490 	m->m_len++;
491 	m->m_pkthdr.len++;
492 
493 	/* Ship off mbuf if it's time */
494 	if (sc->hotchar == -1 || c == sc->hotchar || m->m_len >= MHLEN) {
495 		sc->m = NULL;
496 		NG_SEND_DATA_ONLY(error, sc->hook, m);	/* Will queue */
497 	}
498 
499 	return (error);
500 }
501 
502 static size_t
503 ngt_rint_poll(struct tty *tp)
504 {
505 	/* We can always accept input */
506 	return (1);
507 }
508