vt_core.c revision 268366
1/*-
2 * Copyright (c) 2009, 2013 The FreeBSD Foundation
3 * All rights reserved.
4 *
5 * This software was developed by Ed Schouten under sponsorship from the
6 * FreeBSD Foundation.
7 *
8 * Portions of this software were developed by Oleksandr Rybalko
9 * under sponsorship from the FreeBSD Foundation.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: stable/10/sys/dev/vt/vt_core.c 268366 2014-07-07 14:16:05Z ray $");
35
36#include "opt_compat.h"
37
38#include <sys/param.h>
39#include <sys/consio.h>
40#include <sys/eventhandler.h>
41#include <sys/fbio.h>
42#include <sys/kbio.h>
43#include <sys/kdb.h>
44#include <sys/kernel.h>
45#include <sys/lock.h>
46#include <sys/malloc.h>
47#include <sys/mutex.h>
48#include <sys/priv.h>
49#include <sys/proc.h>
50#include <sys/reboot.h>
51#include <sys/systm.h>
52#include <sys/terminal.h>
53
54#include <dev/kbd/kbdreg.h>
55#include <dev/vt/vt.h>
56
57#if defined(__i386__) || defined(__amd64__)
58#include <machine/psl.h>
59#include <machine/frame.h>
60#endif
61
62static tc_bell_t	vtterm_bell;
63static tc_cursor_t	vtterm_cursor;
64static tc_putchar_t	vtterm_putchar;
65static tc_fill_t	vtterm_fill;
66static tc_copy_t	vtterm_copy;
67static tc_param_t	vtterm_param;
68static tc_done_t	vtterm_done;
69
70static tc_cnprobe_t	vtterm_cnprobe;
71static tc_cngetc_t	vtterm_cngetc;
72
73static tc_opened_t	vtterm_opened;
74static tc_ioctl_t	vtterm_ioctl;
75static tc_mmap_t	vtterm_mmap;
76
77const struct terminal_class vt_termclass = {
78	.tc_bell	= vtterm_bell,
79	.tc_cursor	= vtterm_cursor,
80	.tc_putchar	= vtterm_putchar,
81	.tc_fill	= vtterm_fill,
82	.tc_copy	= vtterm_copy,
83	.tc_param	= vtterm_param,
84	.tc_done	= vtterm_done,
85
86	.tc_cnprobe	= vtterm_cnprobe,
87	.tc_cngetc	= vtterm_cngetc,
88
89	.tc_opened	= vtterm_opened,
90	.tc_ioctl	= vtterm_ioctl,
91	.tc_mmap	= vtterm_mmap,
92};
93
94/*
95 * Use a constant timer of 25 Hz to redraw the screen.
96 *
97 * XXX: In theory we should only fire up the timer when there is really
98 * activity. Unfortunately we cannot always start timers. We really
99 * don't want to process kernel messages synchronously, because it
100 * really slows down the system.
101 */
102#define	VT_TIMERFREQ	25
103
104/* Bell pitch/duration. */
105#define VT_BELLDURATION	((5 * hz + 99) / 100)
106#define VT_BELLPITCH	800
107
108#define	VT_LOCK(vd)	mtx_lock(&(vd)->vd_lock)
109#define	VT_UNLOCK(vd)	mtx_unlock(&(vd)->vd_lock)
110
111#define	VT_UNIT(vw)	((vw)->vw_device->vd_unit * VT_MAXWINDOWS + \
112			(vw)->vw_number)
113
114/* XXX while syscons is here. */
115int sc_txtmouse_no_retrace_wait;
116
117static SYSCTL_NODE(_kern, OID_AUTO, vt, CTLFLAG_RD, 0, "vt(9) parameters");
118VT_SYSCTL_INT(enable_altgr, 1, "Enable AltGr key (Do not assume R.Alt as Alt)");
119VT_SYSCTL_INT(debug, 0, "vt(9) debug level");
120VT_SYSCTL_INT(deadtimer, 15, "Time to wait busy process in VT_PROCESS mode");
121VT_SYSCTL_INT(suspendswitch, 1, "Switch to VT0 before suspend");
122
123static struct vt_device	vt_consdev;
124static unsigned int vt_unit = 0;
125static MALLOC_DEFINE(M_VT, "vt", "vt device");
126struct vt_device *main_vd = &vt_consdev;
127
128/* Boot logo. */
129extern unsigned int vt_logo_width;
130extern unsigned int vt_logo_height;
131extern unsigned int vt_logo_depth;
132extern unsigned char vt_logo_image[];
133
134/* Font. */
135extern struct vt_font vt_font_default;
136#ifndef SC_NO_CUTPASTE
137extern struct mouse_cursor vt_default_mouse_pointer;
138#endif
139
140static int signal_vt_rel(struct vt_window *);
141static int signal_vt_acq(struct vt_window *);
142static int finish_vt_rel(struct vt_window *, int, int *);
143static int finish_vt_acq(struct vt_window *);
144static int vt_window_switch(struct vt_window *);
145static int vt_late_window_switch(struct vt_window *);
146static int vt_proc_alive(struct vt_window *);
147static void vt_resize(struct vt_device *);
148static void vt_update_static(void *);
149
150SET_DECLARE(vt_drv_set, struct vt_driver);
151
152#define _VTDEFH MAX(100, PIXEL_HEIGHT(VT_FB_DEFAULT_HEIGHT))
153#define _VTDEFW MAX(200, PIXEL_WIDTH(VT_FB_DEFAULT_WIDTH))
154
155static struct terminal	vt_consterm;
156static struct vt_window	vt_conswindow;
157static struct vt_device	vt_consdev = {
158	.vd_driver = NULL,
159	.vd_softc = NULL,
160	.vd_flags = VDF_INVALID,
161	.vd_windows = { [VT_CONSWINDOW] =  &vt_conswindow, },
162	.vd_curwindow = &vt_conswindow,
163	.vd_markedwin = NULL,
164	.vd_kbstate = 0,
165};
166static term_char_t vt_constextbuf[(_VTDEFW) * (VBF_DEFAULT_HISTORY_SIZE)];
167static term_char_t *vt_constextbufrows[VBF_DEFAULT_HISTORY_SIZE];
168static struct vt_window	vt_conswindow = {
169	.vw_number = VT_CONSWINDOW,
170	.vw_flags = VWF_CONSOLE,
171	.vw_buf = {
172		.vb_buffer = vt_constextbuf,
173		.vb_rows = vt_constextbufrows,
174		.vb_history_size = VBF_DEFAULT_HISTORY_SIZE,
175		.vb_curroffset = 0,
176		.vb_roffset = 0,
177		.vb_flags = VBF_STATIC,
178		.vb_mark_start = {.tp_row = 0, .tp_col = 0,},
179		.vb_mark_end = {.tp_row = 0, .tp_col = 0,},
180		.vb_scr_size = {
181			.tp_row = _VTDEFH,
182			.tp_col = _VTDEFW,
183		},
184	},
185	.vw_device = &vt_consdev,
186	.vw_terminal = &vt_consterm,
187	.vw_kbdmode = K_XLATE,
188};
189static struct terminal vt_consterm = {
190	.tm_class = &vt_termclass,
191	.tm_softc = &vt_conswindow,
192	.tm_flags = TF_CONS,
193};
194static struct consdev vt_consterm_consdev = {
195	.cn_ops = &termcn_cnops,
196	.cn_arg = &vt_consterm,
197	.cn_name = "ttyv0",
198};
199
200/* Add to set of consoles. */
201DATA_SET(cons_set, vt_consterm_consdev);
202
203/*
204 * Right after kmem is done to allow early drivers to use locking and allocate
205 * memory.
206 */
207SYSINIT(vt_update_static, SI_SUB_KMEM, SI_ORDER_ANY, vt_update_static,
208    &vt_consdev);
209/* Delay until all devices attached, to not waste time. */
210SYSINIT(vt_early_cons, SI_SUB_INT_CONFIG_HOOKS, SI_ORDER_ANY, vt_upgrade,
211    &vt_consdev);
212
213/* Initialize locks/mem depended members. */
214static void
215vt_update_static(void *dummy)
216{
217
218	if (!vty_enabled(VTY_VT))
219		return;
220	if (main_vd->vd_driver != NULL)
221		printf("VT: running with driver \"%s\".\n",
222		    main_vd->vd_driver->vd_name);
223	else
224		printf("VT: init without driver.\n");
225
226	mtx_init(&main_vd->vd_lock, "vtdev", NULL, MTX_DEF);
227	cv_init(&main_vd->vd_winswitch, "vtwswt");
228}
229
230static void
231vt_switch_timer(void *arg)
232{
233
234	vt_late_window_switch((struct vt_window *)arg);
235}
236
237static int
238vt_window_preswitch(struct vt_window *vw, struct vt_window *curvw)
239{
240
241	DPRINTF(40, "%s\n", __func__);
242	curvw->vw_switch_to = vw;
243	/* Set timer to allow switch in case when process hang. */
244	callout_reset(&vw->vw_proc_dead_timer, hz * vt_deadtimer,
245	    vt_switch_timer, (void *)vw);
246	/* Notify process about vt switch attempt. */
247	DPRINTF(30, "%s: Notify process.\n", __func__);
248	signal_vt_rel(curvw);
249
250	return (0);
251}
252
253static int
254vt_window_postswitch(struct vt_window *vw)
255{
256
257	signal_vt_acq(vw);
258	return (0);
259}
260
261/* vt_late_window_switch will done VT switching for regular case. */
262static int
263vt_late_window_switch(struct vt_window *vw)
264{
265	int ret;
266
267	callout_stop(&vw->vw_proc_dead_timer);
268
269	ret = vt_window_switch(vw);
270	if (ret)
271		return (ret);
272
273	/* Notify owner process about terminal availability. */
274	if (vw->vw_smode.mode == VT_PROCESS) {
275		ret = vt_window_postswitch(vw);
276	}
277	return (ret);
278}
279
280/* Switch window. */
281static int
282vt_proc_window_switch(struct vt_window *vw)
283{
284	struct vt_window *curvw;
285	struct vt_device *vd;
286	int ret;
287
288	vd = vw->vw_device;
289	curvw = vd->vd_curwindow;
290
291	if (curvw->vw_flags & VWF_VTYLOCK)
292		return (EBUSY);
293
294	/* Ask current process permitions to switch away. */
295	if (curvw->vw_smode.mode == VT_PROCESS) {
296		DPRINTF(30, "%s: VT_PROCESS ", __func__);
297		if (vt_proc_alive(curvw) == FALSE) {
298			DPRINTF(30, "Dead. Cleaning.");
299			/* Dead */
300		} else {
301			DPRINTF(30, "%s: Signaling process.\n", __func__);
302			/* Alive, try to ask him. */
303			ret = vt_window_preswitch(vw, curvw);
304			/* Wait for process answer or timeout. */
305			return (ret);
306		}
307		DPRINTF(30, "\n");
308	}
309
310	ret = vt_late_window_switch(vw);
311	return (ret);
312}
313
314/* Switch window ignoring process locking. */
315static int
316vt_window_switch(struct vt_window *vw)
317{
318	struct vt_device *vd = vw->vw_device;
319	struct vt_window *curvw = vd->vd_curwindow;
320	keyboard_t *kbd;
321
322	VT_LOCK(vd);
323	if (curvw == vw) {
324		/* Nothing to do. */
325		VT_UNLOCK(vd);
326		return (0);
327	}
328	if (!(vw->vw_flags & (VWF_OPENED|VWF_CONSOLE))) {
329		VT_UNLOCK(vd);
330		return (EINVAL);
331	}
332
333	vd->vd_curwindow = vw;
334	vd->vd_flags |= VDF_INVALID;
335	cv_broadcast(&vd->vd_winswitch);
336	VT_UNLOCK(vd);
337
338	if (vd->vd_driver->vd_postswitch)
339		vd->vd_driver->vd_postswitch(vd);
340
341	/* Restore per-window keyboard mode. */
342	mtx_lock(&Giant);
343	kbd = kbd_get_keyboard(vd->vd_keyboard);
344	if (kbd != NULL) {
345		kbdd_ioctl(kbd, KDSKBMODE, (void *)&vw->vw_kbdmode);
346	}
347	mtx_unlock(&Giant);
348	DPRINTF(10, "%s(ttyv%d) done\n", __func__, vw->vw_number);
349
350	return (0);
351}
352
353static inline void
354vt_termsize(struct vt_device *vd, struct vt_font *vf, term_pos_t *size)
355{
356
357	size->tp_row = vd->vd_height;
358	size->tp_col = vd->vd_width;
359	if (vf != NULL) {
360		size->tp_row /= vf->vf_height;
361		size->tp_col /= vf->vf_width;
362	}
363}
364
365static inline void
366vt_winsize(struct vt_device *vd, struct vt_font *vf, struct winsize *size)
367{
368
369	size->ws_row = size->ws_ypixel = vd->vd_height;
370	size->ws_col = size->ws_xpixel = vd->vd_width;
371	if (vf != NULL) {
372		size->ws_row /= vf->vf_height;
373		size->ws_col /= vf->vf_width;
374	}
375}
376
377static void
378vt_scroll(struct vt_window *vw, int offset, int whence)
379{
380	int diff;
381	term_pos_t size;
382
383	if ((vw->vw_flags & VWF_SCROLL) == 0)
384		return;
385
386	vt_termsize(vw->vw_device, vw->vw_font, &size);
387
388	diff = vthistory_seek(&vw->vw_buf, offset, whence);
389	/*
390	 * Offset changed, please update Nth lines on sceen.
391	 * +N - Nth lines at top;
392	 * -N - Nth lines at bottom.
393	 */
394
395	if (diff < -size.tp_row || diff > size.tp_row) {
396		vw->vw_device->vd_flags |= VDF_INVALID;
397		return;
398	}
399	vw->vw_device->vd_flags |= VDF_INVALID; /*XXX*/
400}
401
402static int
403vt_machine_kbdevent(int c)
404{
405
406	switch (c) {
407	case SPCLKEY | DBG:
408		kdb_enter(KDB_WHY_BREAK, "manual escape to debugger");
409		return (1);
410	case SPCLKEY | RBT:
411		/* XXX: Make this configurable! */
412		shutdown_nice(0);
413		return (1);
414	case SPCLKEY | HALT:
415		shutdown_nice(RB_HALT);
416		return (1);
417	case SPCLKEY | PDWN:
418		shutdown_nice(RB_HALT|RB_POWEROFF);
419		return (1);
420	};
421
422	return (0);
423}
424
425static void
426vt_scrollmode_kbdevent(struct vt_window *vw, int c, int console)
427{
428	struct vt_device *vd;
429	term_pos_t size;
430
431	vd = vw->vw_device;
432	/* Only special keys handled in ScrollLock mode */
433	if ((c & SPCLKEY) == 0)
434		return;
435
436	c &= ~SPCLKEY;
437
438	if (console == 0) {
439		if (c >= F_SCR && c <= MIN(L_SCR, F_SCR + VT_MAXWINDOWS - 1)) {
440			vw = vd->vd_windows[c - F_SCR];
441			if (vw != NULL)
442				vt_proc_window_switch(vw);
443			return;
444		}
445		VT_LOCK(vd);
446	}
447
448	switch (c) {
449	case SLK: {
450		/* Turn scrolling off. */
451		vt_scroll(vw, 0, VHS_END);
452		VTBUF_SLCK_DISABLE(&vw->vw_buf);
453		vw->vw_flags &= ~VWF_SCROLL;
454		break;
455	}
456	case FKEY | F(49): /* Home key. */
457		vt_scroll(vw, 0, VHS_SET);
458		break;
459	case FKEY | F(50): /* Arrow up. */
460		vt_scroll(vw, -1, VHS_CUR);
461		break;
462	case FKEY | F(51): /* Page up. */
463		vt_termsize(vd, vw->vw_font, &size);
464		vt_scroll(vw, -size.tp_row, VHS_CUR);
465		break;
466	case FKEY | F(57): /* End key. */
467		vt_scroll(vw, 0, VHS_END);
468		break;
469	case FKEY | F(58): /* Arrow down. */
470		vt_scroll(vw, 1, VHS_CUR);
471		break;
472	case FKEY | F(59): /* Page down. */
473		vt_termsize(vd, vw->vw_font, &size);
474		vt_scroll(vw, size.tp_row, VHS_CUR);
475		break;
476	}
477
478	if (console == 0)
479		VT_UNLOCK(vd);
480}
481
482static int
483vt_processkey(keyboard_t *kbd, struct vt_device *vd, int c)
484{
485	struct vt_window *vw = vd->vd_curwindow;
486	int state = 0;
487
488#if VT_ALT_TO_ESC_HACK
489	if (c & RELKEY) {
490		switch (c & ~RELKEY) {
491		case (SPCLKEY | RALT):
492			if (vt_enable_altgr != 0)
493				break;
494		case (SPCLKEY | LALT):
495			vd->vd_kbstate &= ~ALKED;
496		}
497		/* Other keys ignored for RELKEY event. */
498		return (0);
499	} else {
500		switch (c & ~RELKEY) {
501		case (SPCLKEY | RALT):
502			if (vt_enable_altgr != 0)
503				break;
504		case (SPCLKEY | LALT):
505			vd->vd_kbstate |= ALKED;
506		}
507	}
508#else
509	if (c & RELKEY)
510		/* Other keys ignored for RELKEY event. */
511		return (0);
512#endif
513
514	if (vt_machine_kbdevent(c))
515		return (0);
516
517	if (vw->vw_flags & VWF_SCROLL) {
518		vt_scrollmode_kbdevent(vw, c, 0/* Not a console */);
519		/* Scroll mode keys handled, nothing to do more. */
520		return (0);
521	}
522
523	if (c & SPCLKEY) {
524		c &= ~SPCLKEY;
525
526		if (c >= F_SCR && c <= MIN(L_SCR, F_SCR + VT_MAXWINDOWS - 1)) {
527			vw = vd->vd_windows[c - F_SCR];
528			if (vw != NULL)
529				vt_proc_window_switch(vw);
530			return (0);
531		}
532
533		switch (c) {
534		case SLK: {
535
536			kbdd_ioctl(kbd, KDGKBSTATE, (caddr_t)&state);
537			VT_LOCK(vd);
538			if (state & SLKED) {
539				/* Turn scrolling on. */
540				vw->vw_flags |= VWF_SCROLL;
541				VTBUF_SLCK_ENABLE(&vw->vw_buf);
542			} else {
543				/* Turn scrolling off. */
544				vw->vw_flags &= ~VWF_SCROLL;
545				VTBUF_SLCK_DISABLE(&vw->vw_buf);
546				vt_scroll(vw, 0, VHS_END);
547			}
548			VT_UNLOCK(vd);
549			break;
550		}
551		case FKEY | F(1):  case FKEY | F(2):  case FKEY | F(3):
552		case FKEY | F(4):  case FKEY | F(5):  case FKEY | F(6):
553		case FKEY | F(7):  case FKEY | F(8):  case FKEY | F(9):
554		case FKEY | F(10): case FKEY | F(11): case FKEY | F(12):
555			/* F1 through F12 keys. */
556			terminal_input_special(vw->vw_terminal,
557			    TKEY_F1 + c - (FKEY | F(1)));
558			break;
559		case FKEY | F(49): /* Home key. */
560			terminal_input_special(vw->vw_terminal, TKEY_HOME);
561			break;
562		case FKEY | F(50): /* Arrow up. */
563			terminal_input_special(vw->vw_terminal, TKEY_UP);
564			break;
565		case FKEY | F(51): /* Page up. */
566			terminal_input_special(vw->vw_terminal, TKEY_PAGE_UP);
567			break;
568		case FKEY | F(53): /* Arrow left. */
569			terminal_input_special(vw->vw_terminal, TKEY_LEFT);
570			break;
571		case FKEY | F(55): /* Arrow right. */
572			terminal_input_special(vw->vw_terminal, TKEY_RIGHT);
573			break;
574		case FKEY | F(57): /* End key. */
575			terminal_input_special(vw->vw_terminal, TKEY_END);
576			break;
577		case FKEY | F(58): /* Arrow down. */
578			terminal_input_special(vw->vw_terminal, TKEY_DOWN);
579			break;
580		case FKEY | F(59): /* Page down. */
581			terminal_input_special(vw->vw_terminal, TKEY_PAGE_DOWN);
582			break;
583		case FKEY | F(60): /* Insert key. */
584			terminal_input_special(vw->vw_terminal, TKEY_INSERT);
585			break;
586		case FKEY | F(61): /* Delete key. */
587			terminal_input_special(vw->vw_terminal, TKEY_DELETE);
588			break;
589		}
590	} else if (KEYFLAGS(c) == 0) {
591		/* Don't do UTF-8 conversion when doing raw mode. */
592		if (vw->vw_kbdmode == K_XLATE) {
593#if VT_ALT_TO_ESC_HACK
594			if (vd->vd_kbstate & ALKED) {
595				/*
596				 * Prepend ESC sequence if one of ALT keys down.
597				 */
598				terminal_input_char(vw->vw_terminal, 0x1b);
599			}
600#endif
601
602			terminal_input_char(vw->vw_terminal, KEYCHAR(c));
603		} else
604			terminal_input_raw(vw->vw_terminal, c);
605	}
606	return (0);
607}
608
609static int
610vt_kbdevent(keyboard_t *kbd, int event, void *arg)
611{
612	struct vt_device *vd = arg;
613	int c;
614
615	switch (event) {
616	case KBDIO_KEYINPUT:
617		break;
618	case KBDIO_UNLOADING:
619		mtx_lock(&Giant);
620		vd->vd_keyboard = -1;
621		kbd_release(kbd, (void *)&vd->vd_keyboard);
622		mtx_unlock(&Giant);
623		return (0);
624	default:
625		return (EINVAL);
626	}
627
628	while ((c = kbdd_read_char(kbd, 0)) != NOKEY)
629		vt_processkey(kbd, vd, c);
630
631	return (0);
632}
633
634static int
635vt_allocate_keyboard(struct vt_device *vd)
636{
637	int		 idx0, idx;
638	keyboard_t	*k0, *k;
639	keyboard_info_t	 ki;
640
641	idx0 = kbd_allocate("kbdmux", -1, vd, vt_kbdevent, vd);
642	vd->vd_keyboard = idx0;
643	if (idx0 >= 0) {
644		DPRINTF(20, "%s: kbdmux allocated, idx = %d\n", __func__, idx0);
645		k0 = kbd_get_keyboard(idx0);
646
647		for (idx = kbd_find_keyboard2("*", -1, 0);
648		     idx != -1;
649		     idx = kbd_find_keyboard2("*", -1, idx + 1)) {
650			k = kbd_get_keyboard(idx);
651
652			if (idx == idx0 || KBD_IS_BUSY(k))
653				continue;
654
655			bzero(&ki, sizeof(ki));
656			strcpy(ki.kb_name, k->kb_name);
657			ki.kb_unit = k->kb_unit;
658
659			kbdd_ioctl(k0, KBADDKBD, (caddr_t) &ki);
660		}
661	} else {
662		DPRINTF(20, "%s: no kbdmux allocated\n", __func__);
663		idx0 = kbd_allocate("*", -1, vd, vt_kbdevent, vd);
664		if (idx0 < 0) {
665			DPRINTF(10, "%s: No keyboard found.\n", __func__);
666			return (-1);
667		}
668	}
669	DPRINTF(20, "%s: vd_keyboard = %d\n", __func__, vd->vd_keyboard);
670
671	return (idx0);
672}
673
674static void
675vtterm_bell(struct terminal *tm)
676{
677	struct vt_window *vw = tm->tm_softc;
678	struct vt_device *vd = vw->vw_device;
679
680	if (vd->vd_flags & VDF_QUIET_BELL)
681		return;
682
683	sysbeep(1193182 / VT_BELLPITCH, VT_BELLDURATION);
684}
685
686static void
687vtterm_beep(struct terminal *tm, u_int param)
688{
689	u_int freq, period;
690
691	if ((param == 0) || ((param & 0xffff) == 0)) {
692		vtterm_bell(tm);
693		return;
694	}
695
696	period = ((param >> 16) & 0xffff) * hz / 1000;
697	freq = 1193182 / (param & 0xffff);
698
699	sysbeep(freq, period);
700}
701
702static void
703vtterm_cursor(struct terminal *tm, const term_pos_t *p)
704{
705	struct vt_window *vw = tm->tm_softc;
706
707	vtbuf_cursor_position(&vw->vw_buf, p);
708}
709
710static void
711vtterm_putchar(struct terminal *tm, const term_pos_t *p, term_char_t c)
712{
713	struct vt_window *vw = tm->tm_softc;
714
715	vtbuf_putchar(&vw->vw_buf, p, c);
716}
717
718static void
719vtterm_fill(struct terminal *tm, const term_rect_t *r, term_char_t c)
720{
721	struct vt_window *vw = tm->tm_softc;
722
723	vtbuf_fill_locked(&vw->vw_buf, r, c);
724}
725
726static void
727vtterm_copy(struct terminal *tm, const term_rect_t *r,
728    const term_pos_t *p)
729{
730	struct vt_window *vw = tm->tm_softc;
731
732	vtbuf_copy(&vw->vw_buf, r, p);
733}
734
735static void
736vtterm_param(struct terminal *tm, int cmd, unsigned int arg)
737{
738	struct vt_window *vw = tm->tm_softc;
739
740	switch (cmd) {
741	case TP_SHOWCURSOR:
742		vtbuf_cursor_visibility(&vw->vw_buf, arg);
743		break;
744	case TP_MOUSE:
745		vw->vw_mouse_level = arg;
746		break;
747	}
748}
749
750static inline void
751vt_determine_colors(term_char_t c, int cursor,
752    term_color_t *fg, term_color_t *bg)
753{
754	term_color_t tmp;
755	int invert;
756
757	invert = 0;
758
759	*fg = TCHAR_FGCOLOR(c);
760	if (TCHAR_FORMAT(c) & TF_BOLD)
761		*fg = TCOLOR_LIGHT(*fg);
762	*bg = TCHAR_BGCOLOR(c);
763
764	if (TCHAR_FORMAT(c) & TF_REVERSE)
765		invert ^= 1;
766	if (cursor)
767		invert ^= 1;
768
769	if (invert) {
770		tmp = *fg;
771		*fg = *bg;
772		*bg = tmp;
773	}
774}
775
776static void
777vt_bitblt_char(struct vt_device *vd, struct vt_font *vf, term_char_t c,
778    int iscursor, unsigned int row, unsigned int col)
779{
780	term_color_t fg, bg;
781
782	vt_determine_colors(c, iscursor, &fg, &bg);
783
784	if (vf != NULL) {
785		const uint8_t *src;
786		vt_axis_t top, left;
787
788		src = vtfont_lookup(vf, c);
789
790		/*
791		 * Align the terminal to the centre of the screen.
792		 * Fonts may not always be able to fill the entire
793		 * screen.
794		 */
795		top = row * vf->vf_height + vd->vd_offset.tp_row;
796		left = col * vf->vf_width + vd->vd_offset.tp_col;
797
798		vd->vd_driver->vd_bitbltchr(vd, src, NULL, 0, top, left,
799		    vf->vf_width, vf->vf_height, fg, bg);
800	} else {
801		vd->vd_driver->vd_putchar(vd, TCHAR_CHARACTER(c),
802		    row, col, fg, bg);
803	}
804}
805
806static void
807vt_flush(struct vt_device *vd)
808{
809	struct vt_window *vw;
810	struct vt_font *vf;
811	struct vt_bufmask tmask;
812	unsigned int row, col;
813	term_rect_t tarea;
814	term_pos_t size;
815	term_char_t *r;
816#ifndef SC_NO_CUTPASTE
817	struct mouse_cursor *m;
818	int bpl, h, w;
819#endif
820
821	vw = vd->vd_curwindow;
822	if (vw == NULL)
823		return;
824	vf = vw->vw_font;
825	if (((vd->vd_flags & VDF_TEXTMODE) == 0) && (vf == NULL))
826		return;
827
828	if (vd->vd_flags & VDF_SPLASH || vw->vw_flags & VWF_BUSY)
829		return;
830
831	vtbuf_undirty(&vw->vw_buf, &tarea, &tmask);
832	vt_termsize(vd, vf, &size);
833
834	/* Force a full redraw when the screen contents are invalid. */
835	if (vd->vd_flags & VDF_INVALID) {
836		tarea.tr_begin.tp_row = tarea.tr_begin.tp_col = 0;
837		tarea.tr_end = size;
838		tmask.vbm_row = tmask.vbm_col = VBM_DIRTY;
839
840		vd->vd_flags &= ~VDF_INVALID;
841	}
842
843#ifndef SC_NO_CUTPASTE
844	if ((vw->vw_flags & VWF_MOUSE_HIDE) == 0) {
845		/* Mark last mouse position as dirty to erase. */
846		vtbuf_mouse_cursor_position(&vw->vw_buf, vd->vd_mdirtyx,
847		    vd->vd_mdirtyy);
848	}
849#endif
850
851	for (row = tarea.tr_begin.tp_row; row < tarea.tr_end.tp_row; row++) {
852		if (!VTBUF_DIRTYROW(&tmask, row))
853			continue;
854		r = VTBUF_GET_ROW(&vw->vw_buf, row);
855		for (col = tarea.tr_begin.tp_col;
856		    col < tarea.tr_end.tp_col; col++) {
857			if (!VTBUF_DIRTYCOL(&tmask, col))
858				continue;
859
860			vt_bitblt_char(vd, vf, r[col],
861			    VTBUF_ISCURSOR(&vw->vw_buf, row, col), row, col);
862		}
863	}
864
865#ifndef SC_NO_CUTPASTE
866	/* Mouse disabled. */
867	if (vw->vw_flags & VWF_MOUSE_HIDE)
868		return;
869
870	/* No mouse for DDB. */
871	if (kdb_active || panicstr != NULL)
872		return;
873
874	if ((vd->vd_flags & (VDF_MOUSECURSOR|VDF_TEXTMODE)) ==
875	    VDF_MOUSECURSOR) {
876		m = &vt_default_mouse_pointer;
877		bpl = (m->w + 7) >> 3; /* Bytes per source line. */
878		w = m->w;
879		h = m->h;
880
881		if ((vd->vd_mx + m->w) > (size.tp_col * vf->vf_width))
882			w = (size.tp_col * vf->vf_width) - vd->vd_mx - 1;
883		if ((vd->vd_my + m->h) > (size.tp_row * vf->vf_height))
884			h = (size.tp_row * vf->vf_height) - vd->vd_my - 1;
885
886		vd->vd_driver->vd_maskbitbltchr(vd, m->map, m->mask, bpl,
887		    vd->vd_offset.tp_row + vd->vd_my,
888		    vd->vd_offset.tp_col + vd->vd_mx,
889		    w, h, TC_WHITE, TC_BLACK);
890		/* Save point of last mouse cursor to erase it later. */
891		vd->vd_mdirtyx = vd->vd_mx / vf->vf_width;
892		vd->vd_mdirtyy = vd->vd_my / vf->vf_height;
893	}
894#endif
895}
896
897static void
898vt_timer(void *arg)
899{
900	struct vt_device *vd;
901
902	vd = arg;
903	/* Update screen if required. */
904	vt_flush(vd);
905
906	/* Schedule for next update. */
907	callout_schedule(&vd->vd_timer, hz / VT_TIMERFREQ);
908}
909
910static void
911vtterm_done(struct terminal *tm)
912{
913	struct vt_window *vw = tm->tm_softc;
914	struct vt_device *vd = vw->vw_device;
915
916	if (kdb_active || panicstr != NULL) {
917		/* Switch to the debugger. */
918		if (vd->vd_curwindow != vw) {
919			vd->vd_curwindow = vw;
920			vd->vd_flags |= VDF_INVALID;
921			if (vd->vd_driver->vd_postswitch)
922				vd->vd_driver->vd_postswitch(vd);
923		}
924		vd->vd_flags &= ~VDF_SPLASH;
925		vt_flush(vd);
926	} else if (!(vd->vd_flags & VDF_ASYNC)) {
927		vt_flush(vd);
928	}
929}
930
931#ifdef DEV_SPLASH
932static void
933vtterm_splash(struct vt_device *vd)
934{
935	vt_axis_t top, left;
936
937	/* Display a nice boot splash. */
938	if (!(vd->vd_flags & VDF_TEXTMODE) && (boothowto & RB_MUTE)) {
939
940		top = (vd->vd_height - vt_logo_height) / 2;
941		left = (vd->vd_width - vt_logo_width) / 2;
942		switch (vt_logo_depth) {
943		case 1:
944			/* XXX: Unhardcode colors! */
945			vd->vd_driver->vd_bitbltchr(vd, vt_logo_image, NULL, 0,
946			    top, left, vt_logo_width, vt_logo_height, 0xf, 0x0);
947		}
948		vd->vd_flags |= VDF_SPLASH;
949	}
950}
951#endif
952
953
954static void
955vtterm_cnprobe(struct terminal *tm, struct consdev *cp)
956{
957	struct vt_driver *vtd, **vtdlist, *vtdbest = NULL;
958	struct vt_window *vw = tm->tm_softc;
959	struct vt_device *vd = vw->vw_device;
960	struct winsize wsz;
961	term_attr_t attr;
962	term_char_t c;
963
964	if (!vty_enabled(VTY_VT))
965		return;
966
967	if (vd->vd_flags & VDF_INITIALIZED)
968		/* Initialization already done. */
969		return;
970
971	SET_FOREACH(vtdlist, vt_drv_set) {
972		vtd = *vtdlist;
973		if (vtd->vd_probe == NULL)
974			continue;
975		if (vtd->vd_probe(vd) == CN_DEAD)
976			continue;
977		if ((vtdbest == NULL) ||
978		    (vtd->vd_priority > vtdbest->vd_priority))
979			vtdbest = vtd;
980	}
981	if (vtdbest == NULL) {
982		cp->cn_pri = CN_DEAD;
983		vd->vd_flags |= VDF_DEAD;
984	} else {
985		vd->vd_driver = vtdbest;
986		cp->cn_pri = vd->vd_driver->vd_init(vd);
987	}
988
989	/* Check if driver's vt_init return CN_DEAD. */
990	if (cp->cn_pri == CN_DEAD) {
991		vd->vd_flags |= VDF_DEAD;
992	}
993
994	/* Initialize any early-boot keyboard drivers */
995	kbd_configure(KB_CONF_PROBE_ONLY);
996
997	vd->vd_unit = atomic_fetchadd_int(&vt_unit, 1);
998	vd->vd_windows[VT_CONSWINDOW] = vw;
999	sprintf(cp->cn_name, "ttyv%r", VT_UNIT(vw));
1000
1001	/* Attach default font if not in TEXTMODE. */
1002	if (!(vd->vd_flags & VDF_TEXTMODE))
1003		vw->vw_font = vtfont_ref(&vt_font_default);
1004
1005	vtbuf_init_early(&vw->vw_buf);
1006	vt_winsize(vd, vw->vw_font, &wsz);
1007	c = (boothowto & RB_MUTE) == 0 ? TERMINAL_KERN_ATTR :
1008	    TERMINAL_NORM_ATTR;
1009	attr.ta_format = TCHAR_FORMAT(c);
1010	attr.ta_fgcolor = TCHAR_FGCOLOR(c);
1011	attr.ta_bgcolor = TCHAR_BGCOLOR(c);
1012	terminal_set_winsize_blank(tm, &wsz, 1, &attr);
1013
1014	if (vtdbest != NULL) {
1015#ifdef DEV_SPLASH
1016		vtterm_splash(vd);
1017#endif
1018		vd->vd_flags |= VDF_INITIALIZED;
1019	}
1020}
1021
1022static int
1023vtterm_cngetc(struct terminal *tm)
1024{
1025	struct vt_window *vw = tm->tm_softc;
1026	struct vt_device *vd = vw->vw_device;
1027	keyboard_t *kbd;
1028	int state;
1029	u_int c;
1030
1031	if (vw->vw_kbdsq && *vw->vw_kbdsq)
1032		return (*vw->vw_kbdsq++);
1033
1034	state = 0;
1035	/* Make sure the splash screen is not there. */
1036	if (vd->vd_flags & VDF_SPLASH) {
1037		/* Remove splash */
1038		vd->vd_flags &= ~VDF_SPLASH;
1039		/* Mark screen as invalid to force update */
1040		vd->vd_flags |= VDF_INVALID;
1041		vt_flush(vd);
1042	}
1043
1044	/* Stripped down keyboard handler. */
1045	kbd = kbd_get_keyboard(vd->vd_keyboard);
1046	if (kbd == NULL)
1047		return (-1);
1048
1049	/* Force keyboard input mode to K_XLATE */
1050	c = K_XLATE;
1051	kbdd_ioctl(kbd, KDSKBMODE, (void *)&c);
1052
1053	/* Switch the keyboard to polling to make it work here. */
1054	kbdd_poll(kbd, TRUE);
1055	c = kbdd_read_char(kbd, 0);
1056	kbdd_poll(kbd, FALSE);
1057	if (c & RELKEY)
1058		return (-1);
1059
1060	if (vw->vw_flags & VWF_SCROLL) {
1061		vt_scrollmode_kbdevent(vw, c, 1/* Console mode */);
1062		vt_flush(vd);
1063		return (-1);
1064	}
1065
1066	/* Stripped down handling of vt_kbdevent(), without locking, etc. */
1067	if (c & SPCLKEY) {
1068		switch (c) {
1069		case SPCLKEY | SLK:
1070			kbdd_ioctl(kbd, KDGKBSTATE, (caddr_t)&state);
1071			if (state & SLKED) {
1072				/* Turn scrolling on. */
1073				vw->vw_flags |= VWF_SCROLL;
1074				VTBUF_SLCK_ENABLE(&vw->vw_buf);
1075			} else {
1076				/* Turn scrolling off. */
1077				vt_scroll(vw, 0, VHS_END);
1078				vw->vw_flags &= ~VWF_SCROLL;
1079				VTBUF_SLCK_DISABLE(&vw->vw_buf);
1080			}
1081			break;
1082		/* XXX: KDB can handle history. */
1083		case SPCLKEY | FKEY | F(50): /* Arrow up. */
1084			vw->vw_kbdsq = "\x1b[A";
1085			break;
1086		case SPCLKEY | FKEY | F(58): /* Arrow down. */
1087			vw->vw_kbdsq = "\x1b[B";
1088			break;
1089		case SPCLKEY | FKEY | F(55): /* Arrow right. */
1090			vw->vw_kbdsq = "\x1b[C";
1091			break;
1092		case SPCLKEY | FKEY | F(53): /* Arrow left. */
1093			vw->vw_kbdsq = "\x1b[D";
1094			break;
1095		}
1096
1097		/* Force refresh to make scrollback work. */
1098		vt_flush(vd);
1099	} else if (KEYFLAGS(c) == 0) {
1100		return (KEYCHAR(c));
1101	}
1102
1103	if (vw->vw_kbdsq && *vw->vw_kbdsq)
1104		return (*vw->vw_kbdsq++);
1105
1106	return (-1);
1107}
1108
1109static void
1110vtterm_opened(struct terminal *tm, int opened)
1111{
1112	struct vt_window *vw = tm->tm_softc;
1113	struct vt_device *vd = vw->vw_device;
1114
1115	VT_LOCK(vd);
1116	vd->vd_flags &= ~VDF_SPLASH;
1117	if (opened)
1118		vw->vw_flags |= VWF_OPENED;
1119	else {
1120		vw->vw_flags &= ~VWF_OPENED;
1121		/* TODO: finish ACQ/REL */
1122	}
1123	VT_UNLOCK(vd);
1124}
1125
1126static int
1127vt_change_font(struct vt_window *vw, struct vt_font *vf)
1128{
1129	struct vt_device *vd = vw->vw_device;
1130	struct terminal *tm = vw->vw_terminal;
1131	term_pos_t size;
1132	struct winsize wsz;
1133
1134	/*
1135	 * Changing fonts.
1136	 *
1137	 * Changing fonts is a little tricky.  We must prevent
1138	 * simultaneous access to the device, so we must stop
1139	 * the display timer and the terminal from accessing.
1140	 * We need to switch fonts and grow our screen buffer.
1141	 *
1142	 * XXX: Right now the code uses terminal_mute() to
1143	 * prevent data from reaching the console driver while
1144	 * resizing the screen buffer.  This isn't elegant...
1145	 */
1146
1147	VT_LOCK(vd);
1148	if (vw->vw_flags & VWF_BUSY) {
1149		/* Another process is changing the font. */
1150		VT_UNLOCK(vd);
1151		return (EBUSY);
1152	}
1153	if (vw->vw_font == NULL) {
1154		/* Our device doesn't need fonts. */
1155		VT_UNLOCK(vd);
1156		return (ENOTTY);
1157	}
1158	vw->vw_flags |= VWF_BUSY;
1159	VT_UNLOCK(vd);
1160
1161	vt_termsize(vd, vf, &size);
1162	vt_winsize(vd, vf, &wsz);
1163	/* Save offset to font aligned area. */
1164	vd->vd_offset.tp_col = (vd->vd_width % vf->vf_width) / 2;
1165	vd->vd_offset.tp_row = (vd->vd_height % vf->vf_height) / 2;
1166
1167	/* Grow the screen buffer and terminal. */
1168	terminal_mute(tm, 1);
1169	vtbuf_grow(&vw->vw_buf, &size, vw->vw_buf.vb_history_size);
1170	terminal_set_winsize_blank(tm, &wsz, 0, NULL);
1171	terminal_mute(tm, 0);
1172
1173	/* Actually apply the font to the current window. */
1174	VT_LOCK(vd);
1175	vtfont_unref(vw->vw_font);
1176	vw->vw_font = vtfont_ref(vf);
1177
1178	/* Force a full redraw the next timer tick. */
1179	if (vd->vd_curwindow == vw)
1180		vd->vd_flags |= VDF_INVALID;
1181	vw->vw_flags &= ~VWF_BUSY;
1182	VT_UNLOCK(vd);
1183	return (0);
1184}
1185
1186static int
1187vt_set_border(struct vt_window *vw, struct vt_font *vf, term_color_t c)
1188{
1189	struct vt_device *vd = vw->vw_device;
1190	int x, y, off_x, off_y;
1191
1192	if (vd->vd_driver->vd_drawrect == NULL)
1193		return (ENOTSUP);
1194
1195	x = vd->vd_width - 1;
1196	y = vd->vd_height - 1;
1197	off_x = vd->vd_offset.tp_col;
1198	off_y = vd->vd_offset.tp_row;
1199
1200	/* Top bar. */
1201	if (off_y > 0)
1202		vd->vd_driver->vd_drawrect(vd, 0, 0, x, off_y - 1, 1, c);
1203	/* Left bar. */
1204	if (off_x > 0)
1205		vd->vd_driver->vd_drawrect(vd, 0, off_y, off_x - 1, y - off_y,
1206		    1, c);
1207	/* Right bar.  May be 1 pixel wider than necessary due to rounding. */
1208	vd->vd_driver->vd_drawrect(vd, x - off_x, off_y, x, y - off_y, 1, c);
1209	/* Bottom bar.  May be 1 mixel taller than necessary due to rounding. */
1210	vd->vd_driver->vd_drawrect(vd, 0, y - off_y, x, y, 1, c);
1211
1212	return (0);
1213}
1214
1215static int
1216vt_proc_alive(struct vt_window *vw)
1217{
1218	struct proc *p;
1219
1220	if (vw->vw_smode.mode != VT_PROCESS)
1221		return (FALSE);
1222
1223	if (vw->vw_proc) {
1224		if ((p = pfind(vw->vw_pid)) != NULL)
1225			PROC_UNLOCK(p);
1226		if (vw->vw_proc == p)
1227			return (TRUE);
1228		vw->vw_proc = NULL;
1229		vw->vw_smode.mode = VT_AUTO;
1230		DPRINTF(1, "vt controlling process %d died\n", vw->vw_pid);
1231		vw->vw_pid = 0;
1232	}
1233	return (FALSE);
1234}
1235
1236static int
1237signal_vt_rel(struct vt_window *vw)
1238{
1239
1240	if (vw->vw_smode.mode != VT_PROCESS)
1241		return (FALSE);
1242	if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
1243		vw->vw_proc = NULL;
1244		vw->vw_pid = 0;
1245		return (TRUE);
1246	}
1247	vw->vw_flags |= VWF_SWWAIT_REL;
1248	PROC_LOCK(vw->vw_proc);
1249	kern_psignal(vw->vw_proc, vw->vw_smode.relsig);
1250	PROC_UNLOCK(vw->vw_proc);
1251	DPRINTF(1, "sending relsig to %d\n", vw->vw_pid);
1252	return (TRUE);
1253}
1254
1255static int
1256signal_vt_acq(struct vt_window *vw)
1257{
1258
1259	if (vw->vw_smode.mode != VT_PROCESS)
1260		return (FALSE);
1261	if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
1262		cnavailable(vw->vw_terminal->consdev, FALSE);
1263	if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
1264		vw->vw_proc = NULL;
1265		vw->vw_pid = 0;
1266		return (TRUE);
1267	}
1268	vw->vw_flags |= VWF_SWWAIT_ACQ;
1269	PROC_LOCK(vw->vw_proc);
1270	kern_psignal(vw->vw_proc, vw->vw_smode.acqsig);
1271	PROC_UNLOCK(vw->vw_proc);
1272	DPRINTF(1, "sending acqsig to %d\n", vw->vw_pid);
1273	return (TRUE);
1274}
1275
1276static int
1277finish_vt_rel(struct vt_window *vw, int release, int *s)
1278{
1279
1280	if (vw->vw_flags & VWF_SWWAIT_REL) {
1281		vw->vw_flags &= ~VWF_SWWAIT_REL;
1282		if (release) {
1283			callout_drain(&vw->vw_proc_dead_timer);
1284			vt_late_window_switch(vw->vw_switch_to);
1285		}
1286		return (0);
1287	}
1288	return (EINVAL);
1289}
1290
1291static int
1292finish_vt_acq(struct vt_window *vw)
1293{
1294
1295	if (vw->vw_flags & VWF_SWWAIT_ACQ) {
1296		vw->vw_flags &= ~VWF_SWWAIT_ACQ;
1297		return (0);
1298	}
1299	return (EINVAL);
1300}
1301
1302#ifndef SC_NO_CUTPASTE
1303static void
1304vt_mouse_terminput_button(struct vt_device *vd, int button)
1305{
1306	struct vt_window *vw;
1307	struct vt_font *vf;
1308	char mouseb[6] = "\x1B[M";
1309	int i, x, y;
1310
1311	vw = vd->vd_curwindow;
1312	vf = vw->vw_font;
1313
1314	/* Translate to char position. */
1315	x = vd->vd_mx / vf->vf_width;
1316	y = vd->vd_my / vf->vf_height;
1317	/* Avoid overflow. */
1318	x = MIN(x, 255 - '!');
1319	y = MIN(y, 255 - '!');
1320
1321	mouseb[3] = ' ' + button;
1322	mouseb[4] = '!' + x;
1323	mouseb[5] = '!' + y;
1324
1325	for (i = 0; i < sizeof(mouseb); i++ )
1326		terminal_input_char(vw->vw_terminal, mouseb[i]);
1327}
1328
1329static void
1330vt_mouse_terminput(struct vt_device *vd, int type, int x, int y, int event,
1331    int cnt)
1332{
1333
1334	switch (type) {
1335	case MOUSE_BUTTON_EVENT:
1336		if (cnt > 0) {
1337			/* Mouse button pressed. */
1338			if (event & MOUSE_BUTTON1DOWN)
1339				vt_mouse_terminput_button(vd, 0);
1340			if (event & MOUSE_BUTTON2DOWN)
1341				vt_mouse_terminput_button(vd, 1);
1342			if (event & MOUSE_BUTTON3DOWN)
1343				vt_mouse_terminput_button(vd, 2);
1344		} else {
1345			/* Mouse button released. */
1346			vt_mouse_terminput_button(vd, 3);
1347		}
1348		break;
1349#ifdef notyet
1350	case MOUSE_MOTION_EVENT:
1351		if (mouse->u.data.z < 0) {
1352			/* Scroll up. */
1353			sc_mouse_input_button(vd, 64);
1354		} else if (mouse->u.data.z > 0) {
1355			/* Scroll down. */
1356			sc_mouse_input_button(vd, 65);
1357		}
1358		break;
1359#endif
1360	}
1361}
1362
1363void
1364vt_mouse_event(int type, int x, int y, int event, int cnt, int mlevel)
1365{
1366	struct vt_device *vd;
1367	struct vt_window *vw;
1368	struct vt_font *vf;
1369	term_pos_t size;
1370	term_char_t *buf;
1371	int i, len, mark;
1372
1373	vd = main_vd;
1374	vw = vd->vd_curwindow;
1375	vf = vw->vw_font;
1376	mark = 0;
1377
1378	if (vw->vw_flags & VWF_MOUSE_HIDE)
1379		return; /* Mouse disabled. */
1380
1381	if (vf == NULL)	/* Text mode. */
1382		return;
1383
1384	/*
1385	 * TODO: add flag about pointer position changed, to not redraw chars
1386	 * under mouse pointer when nothing changed.
1387	 */
1388
1389	if (vw->vw_mouse_level > 0)
1390		vt_mouse_terminput(vd, type, x, y, event, cnt);
1391
1392	switch (type) {
1393	case MOUSE_ACTION:
1394	case MOUSE_MOTION_EVENT:
1395		/* Movement */
1396		x += vd->vd_mx;
1397		y += vd->vd_my;
1398
1399		vt_termsize(vd, vf, &size);
1400
1401		/* Apply limits. */
1402		x = MAX(x, 0);
1403		y = MAX(y, 0);
1404		x = MIN(x, (size.tp_col * vf->vf_width) - 1);
1405		y = MIN(y, (size.tp_row * vf->vf_height) - 1);
1406
1407		vd->vd_mx = x;
1408		vd->vd_my = y;
1409		if ((vd->vd_mstate & MOUSE_BUTTON1DOWN) &&
1410		    (vtbuf_set_mark(&vw->vw_buf, VTB_MARK_MOVE,
1411			vd->vd_mx / vf->vf_width,
1412			vd->vd_my / vf->vf_height) == 1)) {
1413
1414			/*
1415			 * We have something marked to copy, so update pointer
1416			 * to window with selection.
1417			 */
1418			vd->vd_markedwin = vw;
1419		}
1420		return; /* Done */
1421	case MOUSE_BUTTON_EVENT:
1422		/* Buttons */
1423		break;
1424	default:
1425		return; /* Done */
1426	}
1427
1428	switch (event) {
1429	case MOUSE_BUTTON1DOWN:
1430		switch (cnt % 4) {
1431		case 0:	/* up */
1432			mark = VTB_MARK_END;
1433			break;
1434		case 1: /* single click: start cut operation */
1435			mark = VTB_MARK_START;
1436			break;
1437		case 2:	/* double click: cut a word */
1438			mark = VTB_MARK_WORD;
1439			break;
1440		case 3:	/* triple click: cut a line */
1441			mark = VTB_MARK_ROW;
1442			break;
1443		}
1444		break;
1445	case VT_MOUSE_PASTEBUTTON:
1446		switch (cnt) {
1447		case 0:	/* up */
1448			break;
1449		default:
1450			if (vd->vd_markedwin == NULL)
1451				return;
1452			/* Get current selecton size in bytes. */
1453			len = vtbuf_get_marked_len(&vd->vd_markedwin->vw_buf);
1454			if (len <= 0)
1455				return;
1456
1457			buf = malloc(len, M_VT, M_WAITOK | M_ZERO);
1458			/* Request cupy/paste buffer data, no more than `len' */
1459			vtbuf_extract_marked(&vd->vd_markedwin->vw_buf, buf,
1460			    len);
1461
1462			len /= sizeof(term_char_t);
1463			for (i = 0; i < len; i++ ) {
1464				if (buf[i] == '\0')
1465					continue;
1466				terminal_input_char(vw->vw_terminal, buf[i]);
1467			}
1468
1469			/* Done, so cleanup. */
1470			free(buf, M_VT);
1471			break;
1472		}
1473		return; /* Done */
1474	case VT_MOUSE_EXTENDBUTTON:
1475		switch (cnt) {
1476		case 0:	/* up */
1477			if (!(vd->vd_mstate & MOUSE_BUTTON1DOWN))
1478				mark = VTB_MARK_EXTEND;
1479			else
1480				mark = 0;
1481			break;
1482		default:
1483			mark = VTB_MARK_EXTEND;
1484			break;
1485		}
1486		break;
1487	default:
1488		return; /* Done */
1489	}
1490
1491	/* Save buttons state. */
1492	if (cnt > 0)
1493		vd->vd_mstate |= event;
1494	else
1495		vd->vd_mstate &= ~event;
1496
1497	if (vtbuf_set_mark(&vw->vw_buf, mark, vd->vd_mx / vf->vf_width,
1498	    vd->vd_my / vf->vf_height) == 1) {
1499		/*
1500		 * We have something marked to copy, so update pointer to
1501		 * window with selection.
1502		 */
1503		vd->vd_markedwin = vw;
1504	}
1505}
1506
1507void
1508vt_mouse_state(int show)
1509{
1510	struct vt_device *vd;
1511	struct vt_window *vw;
1512
1513	vd = main_vd;
1514	vw = vd->vd_curwindow;
1515
1516	switch (show) {
1517	case VT_MOUSE_HIDE:
1518		vw->vw_flags |= VWF_MOUSE_HIDE;
1519		break;
1520	case VT_MOUSE_SHOW:
1521		vw->vw_flags &= ~VWF_MOUSE_HIDE;
1522		break;
1523	}
1524}
1525#endif
1526
1527static int
1528vtterm_mmap(struct terminal *tm, vm_ooffset_t offset, vm_paddr_t * paddr,
1529    int nprot, vm_memattr_t *memattr)
1530{
1531	struct vt_window *vw = tm->tm_softc;
1532	struct vt_device *vd = vw->vw_device;
1533
1534	if (vd->vd_driver->vd_fb_mmap)
1535		return (vd->vd_driver->vd_fb_mmap(vd, offset, paddr, nprot,
1536		    memattr));
1537
1538	return (ENXIO);
1539}
1540
1541static int
1542vtterm_ioctl(struct terminal *tm, u_long cmd, caddr_t data,
1543    struct thread *td)
1544{
1545	struct vt_window *vw = tm->tm_softc;
1546	struct vt_device *vd = vw->vw_device;
1547	keyboard_t *kbd;
1548	int error, i, s;
1549#if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1550    defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
1551	int ival;
1552
1553	switch (cmd) {
1554	case _IO('v', 4):
1555		cmd = VT_RELDISP;
1556		break;
1557	case _IO('v', 5):
1558		cmd = VT_ACTIVATE;
1559		break;
1560	case _IO('v', 6):
1561		cmd = VT_WAITACTIVE;
1562		break;
1563	case _IO('K', 20):
1564		cmd = KDSKBSTATE;
1565		break;
1566	case _IO('K', 67):
1567		cmd = KDSETRAD;
1568		break;
1569	case _IO('K', 7):
1570		cmd = KDSKBMODE;
1571		break;
1572	case _IO('K', 8):
1573		cmd = KDMKTONE;
1574		break;
1575	case _IO('K', 63):
1576		cmd = KIOCSOUND;
1577		break;
1578	case _IO('K', 66):
1579		cmd = KDSETLED;
1580		break;
1581	case _IO('c', 110):
1582		cmd = CONS_SETKBD;
1583		break;
1584	default:
1585		goto skip_thunk;
1586	}
1587	ival = IOCPARM_IVAL(data);
1588	data = (caddr_t)&ival;
1589skip_thunk:
1590#endif
1591
1592	switch (cmd) {
1593	case KDSETRAD:		/* set keyboard repeat & delay rates (old) */
1594		if (*(int *)data & ~0x7f)
1595			return (EINVAL);
1596	case GIO_KEYMAP:
1597	case PIO_KEYMAP:
1598	case GIO_DEADKEYMAP:
1599	case PIO_DEADKEYMAP:
1600	case GETFKEY:
1601	case SETFKEY:
1602	case KDGKBINFO:
1603	case KDGKBTYPE:
1604	case KDSKBSTATE:	/* set keyboard state (locks) */
1605	case KDGKBSTATE:	/* get keyboard state (locks) */
1606	case KDGETREPEAT:	/* get keyboard repeat & delay rates */
1607	case KDSETREPEAT:	/* set keyboard repeat & delay rates (new) */
1608	case KDSETLED:		/* set keyboard LED status */
1609	case KDGETLED:		/* get keyboard LED status */
1610	case KBADDKBD:		/* add/remove keyboard to/from mux */
1611	case KBRELKBD: {
1612		error = 0;
1613
1614		mtx_lock(&Giant);
1615		kbd = kbd_get_keyboard(vd->vd_keyboard);
1616		if (kbd != NULL)
1617			error = kbdd_ioctl(kbd, cmd, data);
1618		mtx_unlock(&Giant);
1619		if (error == ENOIOCTL) {
1620			if (cmd == KDGKBTYPE) {
1621				/* always return something? XXX */
1622				*(int *)data = 0;
1623			} else {
1624				return (ENODEV);
1625			}
1626		}
1627		return (error);
1628	}
1629	case KDGKBMODE: {
1630		int mode = -1;
1631
1632		mtx_lock(&Giant);
1633		kbd = kbd_get_keyboard(vd->vd_keyboard);
1634		if (kbd != NULL) {
1635			kbdd_ioctl(kbd, KDGKBMODE, (void *)&mode);
1636		}
1637		mtx_unlock(&Giant);
1638		DPRINTF(20, "mode %d, vw_kbdmode %d\n", mode, vw->vw_kbdmode);
1639		*(int *)data = mode;
1640		return (0);
1641	}
1642	case KDSKBMODE: {
1643		int mode;
1644
1645		mode = *(int *)data;
1646		switch (mode) {
1647		case K_XLATE:
1648		case K_RAW:
1649		case K_CODE:
1650			vw->vw_kbdmode = mode;
1651			if (vw == vd->vd_curwindow) {
1652				keyboard_t *kbd;
1653				error = 0;
1654
1655				mtx_lock(&Giant);
1656				kbd = kbd_get_keyboard(vd->vd_keyboard);
1657				if (kbd != NULL) {
1658					error = kbdd_ioctl(kbd, KDSKBMODE,
1659					    (void *)&mode);
1660				}
1661				mtx_unlock(&Giant);
1662			}
1663			return (0);
1664		default:
1665			return (EINVAL);
1666		}
1667	}
1668	case FBIOGTYPE:
1669	case FBIO_GETWINORG:	/* get frame buffer window origin */
1670	case FBIO_GETDISPSTART:	/* get display start address */
1671	case FBIO_GETLINEWIDTH:	/* get scan line width in bytes */
1672	case FBIO_BLANK:	/* blank display */
1673		if (vd->vd_driver->vd_fb_ioctl)
1674			return (vd->vd_driver->vd_fb_ioctl(vd, cmd, data, td));
1675		break;
1676	case CONS_BLANKTIME:
1677		/* XXX */
1678		return (0);
1679	case CONS_GET:
1680		/* XXX */
1681		*(int *)data = M_CG640x480;
1682		return (0);
1683	case CONS_BELLTYPE: 	/* set bell type sound */
1684		if ((*(int *)data) & CONS_QUIET_BELL)
1685			vd->vd_flags |= VDF_QUIET_BELL;
1686		else
1687			vd->vd_flags &= ~VDF_QUIET_BELL;
1688		return (0);
1689	case CONS_GETINFO: {
1690		vid_info_t *vi = (vid_info_t *)data;
1691
1692		vi->m_num = vd->vd_curwindow->vw_number + 1;
1693		/* XXX: other fields! */
1694		return (0);
1695	}
1696	case CONS_GETVERS:
1697		*(int *)data = 0x200;
1698		return (0);
1699	case CONS_MODEINFO:
1700		/* XXX */
1701		return (0);
1702	case CONS_MOUSECTL: {
1703		mouse_info_t *mouse = (mouse_info_t*)data;
1704
1705		/*
1706		 * This has no effect on vt(4).  We don't draw any mouse
1707		 * cursor.  Just ignore MOUSE_HIDE and MOUSE_SHOW to
1708		 * prevent excessive errors.  All the other commands
1709		 * should not be applied to individual TTYs, but only to
1710		 * consolectl.
1711		 */
1712		switch (mouse->operation) {
1713		case MOUSE_HIDE:
1714			vd->vd_flags &= ~VDF_MOUSECURSOR;
1715			return (0);
1716		case MOUSE_SHOW:
1717			vd->vd_mx = vd->vd_width / 2;
1718			vd->vd_my = vd->vd_height / 2;
1719			vd->vd_flags |= VDF_MOUSECURSOR;
1720			return (0);
1721		default:
1722			return (EINVAL);
1723		}
1724	}
1725	case PIO_VFONT: {
1726		struct vt_font *vf;
1727
1728		error = vtfont_load((void *)data, &vf);
1729		if (error != 0)
1730			return (error);
1731
1732		error = vt_change_font(vw, vf);
1733		if (error == 0) {
1734			/* XXX: replace 0 with current bg color. */
1735			vt_set_border(vw, vf, 0);
1736		}
1737		vtfont_unref(vf);
1738		return (error);
1739	}
1740	case GIO_SCRNMAP: {
1741		scrmap_t *sm = (scrmap_t *)data;
1742		int i;
1743
1744		/* We don't have screen maps, so return a handcrafted one. */
1745		for (i = 0; i < 256; i++)
1746			sm->scrmap[i] = i;
1747		return (0);
1748	}
1749	case KDSETMODE:
1750		/* XXX */
1751		return (0);
1752	case KDENABIO:      	/* allow io operations */
1753		error = priv_check(td, PRIV_IO);
1754		if (error != 0)
1755			return (error);
1756		error = securelevel_gt(td->td_ucred, 0);
1757		if (error != 0)
1758			return (error);
1759#if defined(__i386__)
1760		td->td_frame->tf_eflags |= PSL_IOPL;
1761#elif defined(__amd64__)
1762		td->td_frame->tf_rflags |= PSL_IOPL;
1763#endif
1764		return (0);
1765	case KDDISABIO:     	/* disallow io operations (default) */
1766#if defined(__i386__)
1767		td->td_frame->tf_eflags &= ~PSL_IOPL;
1768#elif defined(__amd64__)
1769		td->td_frame->tf_rflags &= ~PSL_IOPL;
1770#endif
1771		return (0);
1772	case KDMKTONE:      	/* sound the bell */
1773		vtterm_beep(tm, *(u_int *)data);
1774		return (0);
1775	case KIOCSOUND:     	/* make tone (*data) hz */
1776		/* TODO */
1777		return (0);
1778	case CONS_SETKBD: 		/* set the new keyboard */
1779		mtx_lock(&Giant);
1780		error = 0;
1781		if (vd->vd_keyboard != *(int *)data) {
1782			kbd = kbd_get_keyboard(*(int *)data);
1783			if (kbd == NULL) {
1784				mtx_unlock(&Giant);
1785				return (EINVAL);
1786			}
1787			i = kbd_allocate(kbd->kb_name, kbd->kb_unit,
1788			    (void *)&vd->vd_keyboard, vt_kbdevent, vd);
1789			if (i >= 0) {
1790				if (vd->vd_keyboard != -1) {
1791					kbd_release(kbd,
1792					    (void *)&vd->vd_keyboard);
1793				}
1794				kbd = kbd_get_keyboard(i);
1795				vd->vd_keyboard = i;
1796
1797				(void)kbdd_ioctl(kbd, KDSKBMODE,
1798				    (caddr_t)&vd->vd_curwindow->vw_kbdmode);
1799			} else {
1800				error = EPERM;	/* XXX */
1801			}
1802		}
1803		mtx_unlock(&Giant);
1804		return (error);
1805	case CONS_RELKBD: 		/* release the current keyboard */
1806		mtx_lock(&Giant);
1807		error = 0;
1808		if (vd->vd_keyboard != -1) {
1809			kbd = kbd_get_keyboard(vd->vd_keyboard);
1810			if (kbd == NULL) {
1811				mtx_unlock(&Giant);
1812				return (EINVAL);
1813			}
1814			error = kbd_release(kbd, (void *)&vd->vd_keyboard);
1815			if (error == 0) {
1816				vd->vd_keyboard = -1;
1817			}
1818		}
1819		mtx_unlock(&Giant);
1820		return (error);
1821	case VT_ACTIVATE: {
1822		int win;
1823		win = *(int *)data - 1;
1824		DPRINTF(5, "%s%d: VT_ACTIVATE ttyv%d ", SC_DRIVER_NAME,
1825		    VT_UNIT(vw), win);
1826		if ((win > VT_MAXWINDOWS) || (win < 0))
1827			return (EINVAL);
1828		return (vt_proc_window_switch(vd->vd_windows[win]));
1829	}
1830	case VT_GETACTIVE:
1831		*(int *)data = vd->vd_curwindow->vw_number + 1;
1832		return (0);
1833	case VT_GETINDEX:
1834		*(int *)data = vw->vw_number + 1;
1835		return (0);
1836	case VT_LOCKSWITCH:
1837		/* TODO: Check current state, switching can be in progress. */
1838		if ((*(int *)data) == 0x01)
1839			vw->vw_flags |= VWF_VTYLOCK;
1840		else if ((*(int *)data) == 0x02)
1841			vw->vw_flags &= ~VWF_VTYLOCK;
1842		else
1843			return (EINVAL);
1844		return (0);
1845	case VT_OPENQRY:
1846		VT_LOCK(vd);
1847		for (i = 0; i < VT_MAXWINDOWS; i++) {
1848			vw = vd->vd_windows[i];
1849			if (vw == NULL)
1850				continue;
1851			if (!(vw->vw_flags & VWF_OPENED)) {
1852				*(int *)data = vw->vw_number + 1;
1853				VT_UNLOCK(vd);
1854				return (0);
1855			}
1856		}
1857		VT_UNLOCK(vd);
1858		return (EINVAL);
1859	case VT_WAITACTIVE:
1860		error = 0;
1861
1862		i = *(unsigned int *)data;
1863		if (i > VT_MAXWINDOWS)
1864			return (EINVAL);
1865		if (i != 0)
1866			vw = vd->vd_windows[i - 1];
1867
1868		VT_LOCK(vd);
1869		while (vd->vd_curwindow != vw && error == 0)
1870			error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
1871		VT_UNLOCK(vd);
1872		return (error);
1873	case VT_SETMODE: {    	/* set screen switcher mode */
1874		struct vt_mode *mode;
1875		struct proc *p1;
1876
1877		mode = (struct vt_mode *)data;
1878		DPRINTF(5, "%s%d: VT_SETMODE ", SC_DRIVER_NAME, VT_UNIT(vw));
1879		if (vw->vw_smode.mode == VT_PROCESS) {
1880			p1 = pfind(vw->vw_pid);
1881			if (vw->vw_proc == p1 && vw->vw_proc != td->td_proc) {
1882				if (p1)
1883					PROC_UNLOCK(p1);
1884				DPRINTF(5, "error EPERM\n");
1885				return (EPERM);
1886			}
1887			if (p1)
1888				PROC_UNLOCK(p1);
1889		}
1890		if (mode->mode == VT_AUTO) {
1891			vw->vw_smode.mode = VT_AUTO;
1892			vw->vw_proc = NULL;
1893			vw->vw_pid = 0;
1894			DPRINTF(5, "VT_AUTO, ");
1895			if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
1896				cnavailable(vw->vw_terminal->consdev, TRUE);
1897			/* were we in the middle of the vty switching process? */
1898			if (finish_vt_rel(vw, TRUE, &s) == 0)
1899				DPRINTF(5, "reset WAIT_REL, ");
1900			if (finish_vt_acq(vw) == 0)
1901				DPRINTF(5, "reset WAIT_ACQ, ");
1902			return (0);
1903		} else if (mode->mode == VT_PROCESS) {
1904			if (!ISSIGVALID(mode->relsig) ||
1905			    !ISSIGVALID(mode->acqsig) ||
1906			    !ISSIGVALID(mode->frsig)) {
1907				DPRINTF(5, "error EINVAL\n");
1908				return (EINVAL);
1909			}
1910			DPRINTF(5, "VT_PROCESS %d, ", td->td_proc->p_pid);
1911			bcopy(data, &vw->vw_smode, sizeof(struct vt_mode));
1912			vw->vw_proc = td->td_proc;
1913			vw->vw_pid = vw->vw_proc->p_pid;
1914			if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
1915				cnavailable(vw->vw_terminal->consdev, FALSE);
1916		} else {
1917			DPRINTF(5, "VT_SETMODE failed, unknown mode %d\n",
1918			    mode->mode);
1919			return (EINVAL);
1920		}
1921		DPRINTF(5, "\n");
1922		return (0);
1923	}
1924	case VT_GETMODE:	/* get screen switcher mode */
1925		bcopy(&vw->vw_smode, data, sizeof(struct vt_mode));
1926		return (0);
1927
1928	case VT_RELDISP:	/* screen switcher ioctl */
1929		/*
1930		 * This must be the current vty which is in the VT_PROCESS
1931		 * switching mode...
1932		 */
1933		if ((vw != vd->vd_curwindow) || (vw->vw_smode.mode !=
1934		    VT_PROCESS)) {
1935			return (EINVAL);
1936		}
1937		/* ...and this process is controlling it. */
1938		if (vw->vw_proc != td->td_proc) {
1939			return (EPERM);
1940		}
1941		error = EINVAL;
1942		switch(*(int *)data) {
1943		case VT_FALSE:	/* user refuses to release screen, abort */
1944			if ((error = finish_vt_rel(vw, FALSE, &s)) == 0)
1945				DPRINTF(5, "%s%d: VT_RELDISP: VT_FALSE\n",
1946				    SC_DRIVER_NAME, VT_UNIT(vw));
1947			break;
1948		case VT_TRUE:	/* user has released screen, go on */
1949			/* finish_vt_rel(..., TRUE, ...) should not be locked */
1950			if (vw->vw_flags & VWF_SWWAIT_REL) {
1951				if ((error = finish_vt_rel(vw, TRUE, &s)) == 0)
1952					DPRINTF(5, "%s%d: VT_RELDISP: VT_TRUE\n",
1953					    SC_DRIVER_NAME, VT_UNIT(vw));
1954			} else {
1955				error = EINVAL;
1956			}
1957			return (error);
1958		case VT_ACKACQ:	/* acquire acknowledged, switch completed */
1959			if ((error = finish_vt_acq(vw)) == 0)
1960				DPRINTF(5, "%s%d: VT_RELDISP: VT_ACKACQ\n",
1961				    SC_DRIVER_NAME, VT_UNIT(vw));
1962			break;
1963		default:
1964			break;
1965		}
1966		return (error);
1967	}
1968
1969	return (ENOIOCTL);
1970}
1971
1972static struct vt_window *
1973vt_allocate_window(struct vt_device *vd, unsigned int window)
1974{
1975	struct vt_window *vw;
1976	struct terminal *tm;
1977	term_pos_t size;
1978	struct winsize wsz;
1979
1980	vw = malloc(sizeof *vw, M_VT, M_WAITOK|M_ZERO);
1981	vw->vw_device = vd;
1982	vw->vw_number = window;
1983	vw->vw_kbdmode = K_XLATE;
1984
1985	if (!(vd->vd_flags & VDF_TEXTMODE))
1986		vw->vw_font = vtfont_ref(&vt_font_default);
1987
1988	vt_termsize(vd, vw->vw_font, &size);
1989	vt_winsize(vd, vw->vw_font, &wsz);
1990	vtbuf_init(&vw->vw_buf, &size);
1991
1992	tm = vw->vw_terminal = terminal_alloc(&vt_termclass, vw);
1993	terminal_set_winsize(tm, &wsz);
1994	vd->vd_windows[window] = vw;
1995	callout_init(&vw->vw_proc_dead_timer, 0);
1996
1997	return (vw);
1998}
1999
2000void
2001vt_upgrade(struct vt_device *vd)
2002{
2003	struct vt_window *vw;
2004	unsigned int i;
2005
2006	if (!vty_enabled(VTY_VT))
2007		return;
2008
2009	for (i = 0; i < VT_MAXWINDOWS; i++) {
2010		vw = vd->vd_windows[i];
2011		if (vw == NULL) {
2012			/* New window. */
2013			vw = vt_allocate_window(vd, i);
2014		}
2015		if (!(vw->vw_flags & VWF_READY)) {
2016			callout_init(&vw->vw_proc_dead_timer, 0);
2017			terminal_maketty(vw->vw_terminal, "v%r", VT_UNIT(vw));
2018			vw->vw_flags |= VWF_READY;
2019			if (vw->vw_flags & VWF_CONSOLE) {
2020				/* For existing console window. */
2021				EVENTHANDLER_REGISTER(shutdown_pre_sync,
2022				    vt_window_switch, vw, SHUTDOWN_PRI_DEFAULT);
2023			}
2024		}
2025
2026	}
2027	VT_LOCK(vd);
2028	if (vd->vd_curwindow == NULL)
2029		vd->vd_curwindow = vd->vd_windows[VT_CONSWINDOW];
2030
2031	if (!(vd->vd_flags & VDF_ASYNC)) {
2032	/* Attach keyboard. */
2033	vt_allocate_keyboard(vd);
2034	DPRINTF(20, "%s: vd_keyboard = %d\n", __func__, vd->vd_keyboard);
2035
2036		/* Init 25 Hz timer. */
2037		callout_init_mtx(&vd->vd_timer, &vd->vd_lock, 0);
2038
2039		/* Start timer when everything ready. */
2040		vd->vd_flags |= VDF_ASYNC;
2041		callout_reset(&vd->vd_timer, hz / VT_TIMERFREQ, vt_timer, vd);
2042	}
2043
2044	VT_UNLOCK(vd);
2045
2046	/* Refill settings with new sizes. */
2047	vt_resize(vd);
2048}
2049
2050static void
2051vt_resize(struct vt_device *vd)
2052{
2053	struct vt_window *vw;
2054	int i;
2055
2056	for (i = 0; i < VT_MAXWINDOWS; i++) {
2057		vw = vd->vd_windows[i];
2058		VT_LOCK(vd);
2059		/* Assign default font to window, if not textmode. */
2060		if (!(vd->vd_flags & VDF_TEXTMODE) && vw->vw_font == NULL)
2061			vw->vw_font = vtfont_ref(&vt_font_default);
2062		VT_UNLOCK(vd);
2063		/* Resize terminal windows */
2064		vt_change_font(vw, vw->vw_font);
2065	}
2066}
2067
2068void
2069vt_allocate(struct vt_driver *drv, void *softc)
2070{
2071	struct vt_device *vd;
2072	struct winsize wsz;
2073
2074	if (!vty_enabled(VTY_VT))
2075		return;
2076
2077	if (main_vd->vd_driver == NULL) {
2078		main_vd->vd_driver = drv;
2079		printf("VT: initialize with new VT driver \"%s\".\n",
2080		    drv->vd_name);
2081	} else {
2082		/*
2083		 * Check if have rights to replace current driver. For example:
2084		 * it is bad idea to replace KMS driver with generic VGA one.
2085		 */
2086		if (drv->vd_priority <= main_vd->vd_driver->vd_priority) {
2087			printf("VT: Driver priority %d too low. Current %d\n ",
2088			    drv->vd_priority, main_vd->vd_driver->vd_priority);
2089			return;
2090		}
2091		printf("VT: Replacing driver \"%s\" with new \"%s\".\n",
2092		    main_vd->vd_driver->vd_name, drv->vd_name);
2093	}
2094	vd = main_vd;
2095	VT_LOCK(vd);
2096	if (drv->vd_maskbitbltchr == NULL)
2097		drv->vd_maskbitbltchr = drv->vd_bitbltchr;
2098
2099	if (vd->vd_flags & VDF_ASYNC) {
2100		/* Stop vt_flush periodic task. */
2101		callout_drain(&vd->vd_timer);
2102		/*
2103		 * Mute current terminal until we done. vt_change_font (called
2104		 * from vt_resize) will unmute it.
2105		 */
2106		terminal_mute(vd->vd_curwindow->vw_terminal, 1);
2107	}
2108
2109	/*
2110	 * Reset VDF_TEXTMODE flag, driver who require that flag (vt_vga) will
2111	 * set it.
2112	 */
2113	vd->vd_flags &= ~VDF_TEXTMODE;
2114
2115	vd->vd_driver = drv;
2116	vd->vd_softc = softc;
2117	vd->vd_driver->vd_init(vd);
2118	VT_UNLOCK(vd);
2119
2120	vt_upgrade(vd);
2121
2122#ifdef DEV_SPLASH
2123	if (vd->vd_flags & VDF_SPLASH)
2124		vtterm_splash(vd);
2125#endif
2126
2127	if (vd->vd_flags & VDF_ASYNC) {
2128		terminal_mute(vd->vd_curwindow->vw_terminal, 0);
2129		callout_schedule(&vd->vd_timer, hz / VT_TIMERFREQ);
2130	}
2131
2132	termcn_cnregister(vd->vd_windows[VT_CONSWINDOW]->vw_terminal);
2133
2134	/* Update console window sizes to actual. */
2135	vt_winsize(vd, vd->vd_windows[VT_CONSWINDOW]->vw_font, &wsz);
2136	terminal_set_winsize_blank(vd->vd_windows[VT_CONSWINDOW]->vw_terminal,
2137	    &wsz, 0, NULL);
2138}
2139
2140void
2141vt_suspend()
2142{
2143
2144	if (vt_suspendswitch == 0)
2145		return;
2146	/* Save current window. */
2147	main_vd->vd_savedwindow = main_vd->vd_curwindow;
2148	/* Ask holding process to free window and switch to console window */
2149	vt_proc_window_switch(main_vd->vd_windows[VT_CONSWINDOW]);
2150}
2151
2152void
2153vt_resume()
2154{
2155
2156	if (vt_suspendswitch == 0)
2157		return;
2158	/* Switch back to saved window */
2159	if (main_vd->vd_savedwindow != NULL)
2160		vt_proc_window_switch(main_vd->vd_savedwindow);
2161	main_vd->vd_savedwindow = NULL;
2162}
2163