1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (c) 2009 The FreeBSD Foundation
5 * All rights reserved.
6 *
7 * This software was developed by Ed Schouten under sponsorship from the
8 * FreeBSD Foundation.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD$");
34
35#include <sys/param.h>
36#include <sys/cons.h>
37#include <sys/consio.h>
38#include <sys/kernel.h>
39#include <sys/lock.h>
40#include <sys/malloc.h>
41#include <sys/mutex.h>
42#include <sys/systm.h>
43#include <sys/terminal.h>
44#include <sys/tty.h>
45
46#include <machine/stdarg.h>
47
48static MALLOC_DEFINE(M_TERMINAL, "terminal", "terminal device");
49
50/*
51 * Locking.
52 *
53 * Normally we don't need to lock down the terminal emulator, because
54 * the TTY lock is already held when calling teken_input().
55 * Unfortunately this is not the case when the terminal acts as a
56 * console device, because cnputc() can be called at the same time.
57 * This means terminals may need to be locked down using a spin lock.
58 */
59#define	TERMINAL_LOCK(tm)	do {					\
60	if ((tm)->tm_flags & TF_CONS)					\
61		mtx_lock_spin(&(tm)->tm_mtx);				\
62	else if ((tm)->tm_tty != NULL)					\
63		tty_lock((tm)->tm_tty);					\
64} while (0)
65#define	TERMINAL_UNLOCK(tm)	do {					\
66	if ((tm)->tm_flags & TF_CONS)					\
67		mtx_unlock_spin(&(tm)->tm_mtx);				\
68	else if ((tm)->tm_tty != NULL)					\
69		tty_unlock((tm)->tm_tty);				\
70} while (0)
71#define	TERMINAL_LOCK_TTY(tm)	do {					\
72	if ((tm)->tm_flags & TF_CONS)					\
73		mtx_lock_spin(&(tm)->tm_mtx);				\
74} while (0)
75#define	TERMINAL_UNLOCK_TTY(tm)	do {					\
76	if ((tm)->tm_flags & TF_CONS)					\
77		mtx_unlock_spin(&(tm)->tm_mtx);				\
78} while (0)
79#define	TERMINAL_LOCK_CONS(tm)		mtx_lock_spin(&(tm)->tm_mtx)
80#define	TERMINAL_UNLOCK_CONS(tm)	mtx_unlock_spin(&(tm)->tm_mtx)
81
82/*
83 * TTY routines.
84 */
85
86static tsw_open_t	termtty_open;
87static tsw_close_t	termtty_close;
88static tsw_outwakeup_t	termtty_outwakeup;
89static tsw_ioctl_t	termtty_ioctl;
90static tsw_mmap_t	termtty_mmap;
91
92static struct ttydevsw terminal_tty_class = {
93	.tsw_open	= termtty_open,
94	.tsw_close	= termtty_close,
95	.tsw_outwakeup	= termtty_outwakeup,
96	.tsw_ioctl	= termtty_ioctl,
97	.tsw_mmap	= termtty_mmap,
98};
99
100/*
101 * Terminal emulator routines.
102 */
103
104static tf_bell_t	termteken_bell;
105static tf_cursor_t	termteken_cursor;
106static tf_putchar_t	termteken_putchar;
107static tf_fill_t	termteken_fill;
108static tf_copy_t	termteken_copy;
109static tf_pre_input_t	termteken_pre_input;
110static tf_post_input_t	termteken_post_input;
111static tf_param_t	termteken_param;
112static tf_respond_t	termteken_respond;
113
114static teken_funcs_t terminal_drawmethods = {
115	.tf_bell	= termteken_bell,
116	.tf_cursor	= termteken_cursor,
117	.tf_putchar	= termteken_putchar,
118	.tf_fill	= termteken_fill,
119	.tf_copy	= termteken_copy,
120	.tf_pre_input	= termteken_pre_input,
121	.tf_post_input	= termteken_post_input,
122	.tf_param	= termteken_param,
123	.tf_respond	= termteken_respond,
124};
125
126/* Kernel message formatting. */
127static teken_attr_t kernel_message = {
128	.ta_fgcolor	= TCHAR_FGCOLOR(TERMINAL_KERN_ATTR),
129	.ta_bgcolor	= TCHAR_BGCOLOR(TERMINAL_KERN_ATTR),
130	.ta_format	= TCHAR_FORMAT(TERMINAL_KERN_ATTR)
131};
132
133static teken_attr_t default_message = {
134	.ta_fgcolor	= TCHAR_FGCOLOR(TERMINAL_NORM_ATTR),
135	.ta_bgcolor	= TCHAR_BGCOLOR(TERMINAL_NORM_ATTR),
136	.ta_format	= TCHAR_FORMAT(TERMINAL_NORM_ATTR)
137};
138
139/* Fudge fg brightness as TF_BOLD (shifted). */
140#define	TCOLOR_FG_FUDGED(color) __extension__ ({			\
141	teken_color_t _c;						\
142									\
143	_c = (color);							\
144	TCOLOR_FG(_c & 7) | ((_c & 8) << 18);				\
145})
146
147/* Fudge bg brightness as TF_BLINK (shifted). */
148#define	TCOLOR_BG_FUDGED(color) __extension__ ({			\
149	teken_color_t _c;						\
150									\
151	_c = (color);							\
152	TCOLOR_BG(_c & 7) | ((_c & 8) << 20);				\
153})
154
155#define	TCOLOR_256TO16(color) __extension__ ({				\
156	teken_color_t _c;						\
157									\
158	_c = (color);							\
159	if (_c >= 16)							\
160		_c = teken_256to16(_c);					\
161	_c;								\
162})
163
164#define	TCHAR_CREATE(c, a)	((c) | TFORMAT((a)->ta_format) |	\
165	TCOLOR_FG_FUDGED(TCOLOR_256TO16((a)->ta_fgcolor)) |		\
166	TCOLOR_BG_FUDGED(TCOLOR_256TO16((a)->ta_bgcolor)))
167
168static void
169terminal_init(struct terminal *tm)
170{
171	int fg, bg;
172
173	if (tm->tm_flags & TF_CONS)
174		mtx_init(&tm->tm_mtx, "trmlck", NULL, MTX_SPIN);
175
176	teken_init(&tm->tm_emulator, &terminal_drawmethods, tm);
177
178	fg = bg = -1;
179	TUNABLE_INT_FETCH("teken.fg_color", &fg);
180	TUNABLE_INT_FETCH("teken.bg_color", &bg);
181
182	if (fg != -1) {
183		default_message.ta_fgcolor = fg;
184		kernel_message.ta_fgcolor = fg;
185	}
186	if (bg != -1) {
187		default_message.ta_bgcolor = bg;
188		kernel_message.ta_bgcolor = bg;
189	}
190
191	if (default_message.ta_bgcolor == TC_WHITE) {
192		default_message.ta_bgcolor |= TC_LIGHT;
193		kernel_message.ta_bgcolor |= TC_LIGHT;
194	}
195
196	if (default_message.ta_bgcolor == TC_BLACK &&
197	    default_message.ta_fgcolor < TC_NCOLORS)
198		kernel_message.ta_fgcolor |= TC_LIGHT;
199	teken_set_defattr(&tm->tm_emulator, &default_message);
200}
201
202struct terminal *
203terminal_alloc(const struct terminal_class *tc, void *softc)
204{
205	struct terminal *tm;
206
207	tm = malloc(sizeof(struct terminal), M_TERMINAL, M_WAITOK|M_ZERO);
208	terminal_init(tm);
209
210	tm->tm_class = tc;
211	tm->tm_softc = softc;
212
213	return (tm);
214}
215
216static void
217terminal_sync_ttysize(struct terminal *tm)
218{
219	struct tty *tp;
220
221	tp = tm->tm_tty;
222	if (tp == NULL)
223		return;
224
225	tty_lock(tp);
226	tty_set_winsize(tp, &tm->tm_winsize);
227	tty_unlock(tp);
228}
229
230void
231terminal_maketty(struct terminal *tm, const char *fmt, ...)
232{
233	struct tty *tp;
234	char name[8];
235	va_list ap;
236
237	va_start(ap, fmt);
238	vsnrprintf(name, sizeof name, 32, fmt, ap);
239	va_end(ap);
240
241	tp = tty_alloc(&terminal_tty_class, tm);
242	tty_makedev(tp, NULL, "%s", name);
243	tm->tm_tty = tp;
244	terminal_sync_ttysize(tm);
245}
246
247void
248terminal_set_cursor(struct terminal *tm, const term_pos_t *pos)
249{
250
251	teken_set_cursor(&tm->tm_emulator, pos);
252}
253
254void
255terminal_set_winsize_blank(struct terminal *tm, const struct winsize *size,
256    int blank, const term_attr_t *attr)
257{
258	term_rect_t r;
259
260	tm->tm_winsize = *size;
261
262	r.tr_begin.tp_row = r.tr_begin.tp_col = 0;
263	r.tr_end.tp_row = size->ws_row;
264	r.tr_end.tp_col = size->ws_col;
265
266	TERMINAL_LOCK(tm);
267	if (blank == 0)
268		teken_set_winsize_noreset(&tm->tm_emulator, &r.tr_end);
269	else
270		teken_set_winsize(&tm->tm_emulator, &r.tr_end);
271	TERMINAL_UNLOCK(tm);
272
273	if ((blank != 0) && !(tm->tm_flags & TF_MUTE))
274		tm->tm_class->tc_fill(tm, &r,
275		    TCHAR_CREATE((teken_char_t)' ', attr));
276
277	terminal_sync_ttysize(tm);
278}
279
280void
281terminal_set_winsize(struct terminal *tm, const struct winsize *size)
282{
283
284	terminal_set_winsize_blank(tm, size, 1,
285	    (const term_attr_t *)&default_message);
286}
287
288/*
289 * XXX: This function is a kludge.  Drivers like vt(4) need to
290 * temporarily stop input when resizing, etc.  This should ideally be
291 * handled within the driver.
292 */
293
294void
295terminal_mute(struct terminal *tm, int yes)
296{
297
298	TERMINAL_LOCK(tm);
299	if (yes)
300		tm->tm_flags |= TF_MUTE;
301	else
302		tm->tm_flags &= ~TF_MUTE;
303	TERMINAL_UNLOCK(tm);
304}
305
306void
307terminal_input_char(struct terminal *tm, term_char_t c)
308{
309	struct tty *tp;
310
311	tp = tm->tm_tty;
312	if (tp == NULL)
313		return;
314
315	/*
316	 * Strip off any attributes. Also ignore input of second part of
317	 * CJK fullwidth characters, as we don't want to return these
318	 * characters twice.
319	 */
320	if (TCHAR_FORMAT(c) & TF_CJK_RIGHT)
321		return;
322	c = TCHAR_CHARACTER(c);
323
324	tty_lock(tp);
325	/*
326	 * Conversion to UTF-8.
327	 */
328	if (c < 0x80) {
329		ttydisc_rint(tp, c, 0);
330	} else if (c < 0x800) {
331		char str[2] = {
332			0xc0 | (c >> 6),
333			0x80 | (c & 0x3f)
334		};
335
336		ttydisc_rint_simple(tp, str, sizeof str);
337	} else if (c < 0x10000) {
338		char str[3] = {
339			0xe0 | (c >> 12),
340			0x80 | ((c >> 6) & 0x3f),
341			0x80 | (c & 0x3f)
342		};
343
344		ttydisc_rint_simple(tp, str, sizeof str);
345	} else {
346		char str[4] = {
347			0xf0 | (c >> 18),
348			0x80 | ((c >> 12) & 0x3f),
349			0x80 | ((c >> 6) & 0x3f),
350			0x80 | (c & 0x3f)
351		};
352
353		ttydisc_rint_simple(tp, str, sizeof str);
354	}
355	ttydisc_rint_done(tp);
356	tty_unlock(tp);
357}
358
359void
360terminal_input_raw(struct terminal *tm, char c)
361{
362	struct tty *tp;
363
364	tp = tm->tm_tty;
365	if (tp == NULL)
366		return;
367
368	tty_lock(tp);
369	ttydisc_rint(tp, c, 0);
370	ttydisc_rint_done(tp);
371	tty_unlock(tp);
372}
373
374void
375terminal_input_special(struct terminal *tm, unsigned int k)
376{
377	struct tty *tp;
378	const char *str;
379
380	tp = tm->tm_tty;
381	if (tp == NULL)
382		return;
383
384	str = teken_get_sequence(&tm->tm_emulator, k);
385	if (str == NULL)
386		return;
387
388	tty_lock(tp);
389	ttydisc_rint_simple(tp, str, strlen(str));
390	ttydisc_rint_done(tp);
391	tty_unlock(tp);
392}
393
394/*
395 * Binding with the TTY layer.
396 */
397
398static int
399termtty_open(struct tty *tp)
400{
401	struct terminal *tm = tty_softc(tp);
402
403	tm->tm_class->tc_opened(tm, 1);
404	return (0);
405}
406
407static void
408termtty_close(struct tty *tp)
409{
410	struct terminal *tm = tty_softc(tp);
411
412	tm->tm_class->tc_opened(tm, 0);
413}
414
415static void
416termtty_outwakeup(struct tty *tp)
417{
418	struct terminal *tm = tty_softc(tp);
419	char obuf[128];
420	size_t olen;
421	unsigned int flags = 0;
422
423	while ((olen = ttydisc_getc(tp, obuf, sizeof obuf)) > 0) {
424		TERMINAL_LOCK_TTY(tm);
425		if (!(tm->tm_flags & TF_MUTE)) {
426			tm->tm_flags &= ~TF_BELL;
427			teken_input(&tm->tm_emulator, obuf, olen);
428			flags |= tm->tm_flags;
429		}
430		TERMINAL_UNLOCK_TTY(tm);
431	}
432
433	TERMINAL_LOCK_TTY(tm);
434	if (!(tm->tm_flags & TF_MUTE))
435		tm->tm_class->tc_done(tm);
436	TERMINAL_UNLOCK_TTY(tm);
437	if (flags & TF_BELL)
438		tm->tm_class->tc_bell(tm);
439}
440
441static int
442termtty_ioctl(struct tty *tp, u_long cmd, caddr_t data, struct thread *td)
443{
444	struct terminal *tm = tty_softc(tp);
445	int error;
446
447	switch (cmd) {
448	case CONS_GETINFO: {
449		vid_info_t *vi = (vid_info_t *)data;
450		const teken_pos_t *p;
451		int fg, bg;
452
453		if (vi->size != sizeof(vid_info_t))
454			return (EINVAL);
455
456		/* Already help the console driver by filling in some data. */
457		p = teken_get_cursor(&tm->tm_emulator);
458		vi->mv_row = p->tp_row;
459		vi->mv_col = p->tp_col;
460
461		p = teken_get_winsize(&tm->tm_emulator);
462		vi->mv_rsz = p->tp_row;
463		vi->mv_csz = p->tp_col;
464
465		teken_get_defattr_cons25(&tm->tm_emulator, &fg, &bg);
466		vi->mv_norm.fore = fg;
467		vi->mv_norm.back = bg;
468		/* XXX: keep vidcontrol happy; bold backgrounds. */
469		vi->mv_rev.fore = bg;
470		vi->mv_rev.back = fg & 0x7;
471		break;
472	}
473	}
474
475	/*
476	 * Unlike various other drivers, this driver will never
477	 * deallocate TTYs.  This means it's safe to temporarily unlock
478	 * the TTY when handling ioctls.
479	 */
480	tty_unlock(tp);
481	error = tm->tm_class->tc_ioctl(tm, cmd, data, td);
482	tty_lock(tp);
483	if ((error == 0) && (cmd == CONS_CLRHIST)) {
484		/*
485		 * Scrollback history has been successfully cleared,
486		 * so reset the cursor position to the top left of the screen.
487		 */
488		teken_pos_t p;
489		p.tp_row = 0;
490		p.tp_col = 0;
491		teken_set_cursor(&tm->tm_emulator, &p);
492	}
493	return (error);
494}
495
496static int
497termtty_mmap(struct tty *tp, vm_ooffset_t offset, vm_paddr_t * paddr,
498    int nprot, vm_memattr_t *memattr)
499{
500	struct terminal *tm = tty_softc(tp);
501
502	return (tm->tm_class->tc_mmap(tm, offset, paddr, nprot, memattr));
503}
504
505/*
506 * Binding with the kernel and debug console.
507 */
508
509static cn_probe_t	termcn_cnprobe;
510static cn_init_t	termcn_cninit;
511static cn_term_t	termcn_cnterm;
512static cn_getc_t	termcn_cngetc;
513static cn_putc_t	termcn_cnputc;
514static cn_grab_t	termcn_cngrab;
515static cn_ungrab_t	termcn_cnungrab;
516
517const struct consdev_ops termcn_cnops = {
518	.cn_probe	= termcn_cnprobe,
519	.cn_init	= termcn_cninit,
520	.cn_term	= termcn_cnterm,
521	.cn_getc	= termcn_cngetc,
522	.cn_putc	= termcn_cnputc,
523	.cn_grab	= termcn_cngrab,
524	.cn_ungrab	= termcn_cnungrab,
525};
526
527void
528termcn_cnregister(struct terminal *tm)
529{
530	struct consdev *cp;
531
532	cp = tm->consdev;
533	if (cp == NULL) {
534		cp = malloc(sizeof(struct consdev), M_TERMINAL,
535		    M_WAITOK|M_ZERO);
536		cp->cn_ops = &termcn_cnops;
537		cp->cn_arg = tm;
538		cp->cn_pri = CN_INTERNAL;
539		sprintf(cp->cn_name, "ttyv0");
540
541		tm->tm_flags = TF_CONS;
542		tm->consdev = cp;
543
544		terminal_init(tm);
545	}
546
547	/* Attach terminal as console. */
548	cnadd(cp);
549}
550
551static void
552termcn_cngrab(struct consdev *cp)
553{
554	struct terminal *tm = cp->cn_arg;
555
556	tm->tm_class->tc_cngrab(tm);
557}
558
559static void
560termcn_cnungrab(struct consdev *cp)
561{
562	struct terminal *tm = cp->cn_arg;
563
564	tm->tm_class->tc_cnungrab(tm);
565}
566
567static void
568termcn_cnprobe(struct consdev *cp)
569{
570	struct terminal *tm = cp->cn_arg;
571
572	if (tm == NULL) {
573		cp->cn_pri = CN_DEAD;
574		return;
575	}
576
577	tm->consdev = cp;
578	terminal_init(tm);
579
580	tm->tm_class->tc_cnprobe(tm, cp);
581}
582
583static void
584termcn_cninit(struct consdev *cp)
585{
586
587}
588
589static void
590termcn_cnterm(struct consdev *cp)
591{
592
593}
594
595static int
596termcn_cngetc(struct consdev *cp)
597{
598	struct terminal *tm = cp->cn_arg;
599
600	return (tm->tm_class->tc_cngetc(tm));
601}
602
603static void
604termcn_cnputc(struct consdev *cp, int c)
605{
606	struct terminal *tm = cp->cn_arg;
607	teken_attr_t backup;
608	char cv = c;
609
610	TERMINAL_LOCK_CONS(tm);
611	if (!(tm->tm_flags & TF_MUTE)) {
612		backup = *teken_get_curattr(&tm->tm_emulator);
613		teken_set_curattr(&tm->tm_emulator, &kernel_message);
614		teken_input(&tm->tm_emulator, &cv, 1);
615		teken_set_curattr(&tm->tm_emulator, &backup);
616		tm->tm_class->tc_done(tm);
617	}
618	TERMINAL_UNLOCK_CONS(tm);
619}
620
621/*
622 * Binding with the terminal emulator.
623 */
624
625static void
626termteken_bell(void *softc)
627{
628	struct terminal *tm = softc;
629
630	tm->tm_flags |= TF_BELL;
631}
632
633static void
634termteken_cursor(void *softc, const teken_pos_t *p)
635{
636	struct terminal *tm = softc;
637
638	tm->tm_class->tc_cursor(tm, p);
639}
640
641static void
642termteken_putchar(void *softc, const teken_pos_t *p, teken_char_t c,
643    const teken_attr_t *a)
644{
645	struct terminal *tm = softc;
646
647	tm->tm_class->tc_putchar(tm, p, TCHAR_CREATE(c, a));
648}
649
650static void
651termteken_fill(void *softc, const teken_rect_t *r, teken_char_t c,
652    const teken_attr_t *a)
653{
654	struct terminal *tm = softc;
655
656	tm->tm_class->tc_fill(tm, r, TCHAR_CREATE(c, a));
657}
658
659static void
660termteken_copy(void *softc, const teken_rect_t *r, const teken_pos_t *p)
661{
662	struct terminal *tm = softc;
663
664	tm->tm_class->tc_copy(tm, r, p);
665}
666
667static void
668termteken_pre_input(void *softc)
669{
670	struct terminal *tm = softc;
671
672	tm->tm_class->tc_pre_input(tm);
673}
674
675static void
676termteken_post_input(void *softc)
677{
678	struct terminal *tm = softc;
679
680	tm->tm_class->tc_post_input(tm);
681}
682
683static void
684termteken_param(void *softc, int cmd, unsigned int arg)
685{
686	struct terminal *tm = softc;
687
688	tm->tm_class->tc_param(tm, cmd, arg);
689}
690
691static void
692termteken_respond(void *softc, const void *buf, size_t len)
693{
694#if 0
695	struct terminal *tm = softc;
696	struct tty *tp;
697
698	/*
699	 * Only inject a response into the TTY if the data actually
700	 * originated from the TTY.
701	 *
702	 * XXX: This cannot be done right now.  The TTY could pick up
703	 * other locks.  It could also in theory cause loops, when the
704	 * TTY performs echoing of a command that generates even more
705	 * input.
706	 */
707	tp = tm->tm_tty;
708	if (tp == NULL)
709		return;
710
711	ttydisc_rint_simple(tp, buf, len);
712	ttydisc_rint_done(tp);
713#endif
714}
715