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