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