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