xref: /freebsd/sys/dev/vt/vt_core.c (revision d93a896ef95946b0bf1219866fcb324b78543444)
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_SHOWCURSOR:
1056 		vtbuf_cursor_visibility(&vw->vw_buf, arg);
1057 		vt_resume_flush_timer(vw->vw_device, 0);
1058 		break;
1059 	case TP_MOUSE:
1060 		vw->vw_mouse_level = arg;
1061 		break;
1062 	}
1063 }
1064 
1065 void
1066 vt_determine_colors(term_char_t c, int cursor,
1067     term_color_t *fg, term_color_t *bg)
1068 {
1069 	term_color_t tmp;
1070 	int invert;
1071 
1072 	invert = 0;
1073 
1074 	*fg = TCHAR_FGCOLOR(c);
1075 	if (TCHAR_FORMAT(c) & TF_BOLD)
1076 		*fg = TCOLOR_LIGHT(*fg);
1077 	*bg = TCHAR_BGCOLOR(c);
1078 	if (TCHAR_FORMAT(c) & TF_BLINK)
1079 		*bg = TCOLOR_LIGHT(*bg);
1080 
1081 	if (TCHAR_FORMAT(c) & TF_REVERSE)
1082 		invert ^= 1;
1083 	if (cursor)
1084 		invert ^= 1;
1085 
1086 	if (invert) {
1087 		tmp = *fg;
1088 		*fg = *bg;
1089 		*bg = tmp;
1090 	}
1091 }
1092 
1093 #ifndef SC_NO_CUTPASTE
1094 int
1095 vt_is_cursor_in_area(const struct vt_device *vd, const term_rect_t *area)
1096 {
1097 	unsigned int mx, my;
1098 
1099 	/*
1100 	 * We use the cursor position saved during the current refresh,
1101 	 * in case the cursor moved since.
1102 	 */
1103 	mx = vd->vd_mx_drawn + vd->vd_curwindow->vw_draw_area.tr_begin.tp_col;
1104 	my = vd->vd_my_drawn + vd->vd_curwindow->vw_draw_area.tr_begin.tp_row;
1105 
1106 	if (mx >= area->tr_end.tp_col ||
1107 	    mx + vd->vd_mcursor->width <= area->tr_begin.tp_col ||
1108 	    my >= area->tr_end.tp_row ||
1109 	    my + vd->vd_mcursor->height <= area->tr_begin.tp_row)
1110 		return (0);
1111 	return (1);
1112 }
1113 
1114 static void
1115 vt_mark_mouse_position_as_dirty(struct vt_device *vd)
1116 {
1117 	term_rect_t area;
1118 	struct vt_window *vw;
1119 	struct vt_font *vf;
1120 	int x, y;
1121 
1122 	vw = vd->vd_curwindow;
1123 	vf = vw->vw_font;
1124 
1125 	x = vd->vd_mx_drawn;
1126 	y = vd->vd_my_drawn;
1127 
1128 	if (vf != NULL) {
1129 		area.tr_begin.tp_col = x / vf->vf_width;
1130 		area.tr_begin.tp_row = y / vf->vf_height;
1131 		area.tr_end.tp_col =
1132 		    ((x + vd->vd_mcursor->width) / vf->vf_width) + 1;
1133 		area.tr_end.tp_row =
1134 		    ((y + vd->vd_mcursor->height) / vf->vf_height) + 1;
1135 	} else {
1136 		/*
1137 		 * No font loaded (ie. vt_vga operating in textmode).
1138 		 *
1139 		 * FIXME: This fake area needs to be revisited once the
1140 		 * mouse cursor is supported in vt_vga's textmode.
1141 		 */
1142 		area.tr_begin.tp_col = x;
1143 		area.tr_begin.tp_row = y;
1144 		area.tr_end.tp_col = x + 2;
1145 		area.tr_end.tp_row = y + 2;
1146 	}
1147 
1148 	vtbuf_dirty(&vw->vw_buf, &area);
1149 }
1150 #endif
1151 
1152 static void
1153 vt_set_border(struct vt_device *vd, const term_rect_t *area,
1154     const term_color_t c)
1155 {
1156 	vd_drawrect_t *drawrect = vd->vd_driver->vd_drawrect;
1157 
1158 	if (drawrect == NULL)
1159 		return;
1160 
1161 	/* Top bar */
1162 	if (area->tr_begin.tp_row > 0)
1163 		drawrect(vd, 0, 0, vd->vd_width - 1,
1164 		    area->tr_begin.tp_row - 1, 1, c);
1165 
1166 	/* Left bar */
1167 	if (area->tr_begin.tp_col > 0)
1168 		drawrect(vd, 0, area->tr_begin.tp_row,
1169 		    area->tr_begin.tp_col - 1, area->tr_end.tp_row - 1, 1, c);
1170 
1171 	/* Right bar */
1172 	if (area->tr_end.tp_col < vd->vd_width)
1173 		drawrect(vd, area->tr_end.tp_col, area->tr_begin.tp_row,
1174 		    vd->vd_width - 1, area->tr_end.tp_row - 1, 1, c);
1175 
1176 	/* Bottom bar */
1177 	if (area->tr_end.tp_row < vd->vd_height)
1178 		drawrect(vd, 0, area->tr_end.tp_row, vd->vd_width - 1,
1179 		    vd->vd_height - 1, 1, c);
1180 }
1181 
1182 static int
1183 vt_flush(struct vt_device *vd)
1184 {
1185 	struct vt_window *vw;
1186 	struct vt_font *vf;
1187 	term_rect_t tarea;
1188 #ifndef SC_NO_CUTPASTE
1189 	int cursor_was_shown, cursor_moved;
1190 #endif
1191 
1192 	vw = vd->vd_curwindow;
1193 	if (vw == NULL)
1194 		return (0);
1195 
1196 	if (vd->vd_flags & VDF_SPLASH || vw->vw_flags & VWF_BUSY)
1197 		return (0);
1198 
1199 	vf = vw->vw_font;
1200 	if (((vd->vd_flags & VDF_TEXTMODE) == 0) && (vf == NULL))
1201 		return (0);
1202 
1203 #ifndef SC_NO_CUTPASTE
1204 	cursor_was_shown = vd->vd_mshown;
1205 	cursor_moved = (vd->vd_mx != vd->vd_mx_drawn ||
1206 	    vd->vd_my != vd->vd_my_drawn);
1207 
1208 	/* Check if the cursor should be displayed or not. */
1209 	if ((vd->vd_flags & VDF_MOUSECURSOR) && /* Mouse support enabled. */
1210 	    !(vw->vw_flags & VWF_MOUSE_HIDE) && /* Cursor displayed.      */
1211 	    !kdb_active && panicstr == NULL) {  /* DDB inactive.          */
1212 		vd->vd_mshown = 1;
1213 	} else {
1214 		vd->vd_mshown = 0;
1215 	}
1216 
1217 	/*
1218 	 * If the cursor changed display state or moved, we must mark
1219 	 * the old position as dirty, so that it's erased.
1220 	 */
1221 	if (cursor_was_shown != vd->vd_mshown ||
1222 	    (vd->vd_mshown && cursor_moved))
1223 		vt_mark_mouse_position_as_dirty(vd);
1224 
1225 	/*
1226          * Save position of the mouse cursor. It's used by backends to
1227          * know where to draw the cursor and during the next refresh to
1228          * erase the previous position.
1229 	 */
1230 	vd->vd_mx_drawn = vd->vd_mx;
1231 	vd->vd_my_drawn = vd->vd_my;
1232 
1233 	/*
1234 	 * If the cursor is displayed and has moved since last refresh,
1235 	 * mark the new position as dirty.
1236 	 */
1237 	if (vd->vd_mshown && cursor_moved)
1238 		vt_mark_mouse_position_as_dirty(vd);
1239 #endif
1240 
1241 	vtbuf_undirty(&vw->vw_buf, &tarea);
1242 
1243 	/* Force a full redraw when the screen contents are invalid. */
1244 	if (vd->vd_flags & VDF_INVALID) {
1245 		vd->vd_flags &= ~VDF_INVALID;
1246 
1247 		vt_set_border(vd, &vw->vw_draw_area, TC_BLACK);
1248 		vt_termrect(vd, vf, &tarea);
1249 		if (vt_draw_logo_cpus)
1250 			vtterm_draw_cpu_logos(vd);
1251 	}
1252 
1253 	if (tarea.tr_begin.tp_col < tarea.tr_end.tp_col) {
1254 		vd->vd_driver->vd_bitblt_text(vd, vw, &tarea);
1255 		return (1);
1256 	}
1257 
1258 	return (0);
1259 }
1260 
1261 static void
1262 vt_timer(void *arg)
1263 {
1264 	struct vt_device *vd;
1265 	int changed;
1266 
1267 	vd = arg;
1268 	/* Update screen if required. */
1269 	changed = vt_flush(vd);
1270 
1271 	/* Schedule for next update. */
1272 	if (changed)
1273 		vt_schedule_flush(vd, 0);
1274 	else
1275 		vd->vd_timer_armed = 0;
1276 }
1277 
1278 static void
1279 vtterm_done(struct terminal *tm)
1280 {
1281 	struct vt_window *vw = tm->tm_softc;
1282 	struct vt_device *vd = vw->vw_device;
1283 
1284 	if (kdb_active || panicstr != NULL) {
1285 		/* Switch to the debugger. */
1286 		if (vd->vd_curwindow != vw) {
1287 			vd->vd_curwindow = vw;
1288 			vd->vd_flags |= VDF_INVALID;
1289 			if (vd->vd_driver->vd_postswitch)
1290 				vd->vd_driver->vd_postswitch(vd);
1291 		}
1292 		vd->vd_flags &= ~VDF_SPLASH;
1293 		vt_flush(vd);
1294 	} else if (!(vd->vd_flags & VDF_ASYNC)) {
1295 		vt_flush(vd);
1296 	}
1297 }
1298 
1299 #ifdef DEV_SPLASH
1300 static void
1301 vtterm_splash(struct vt_device *vd)
1302 {
1303 	vt_axis_t top, left;
1304 
1305 	/* Display a nice boot splash. */
1306 	if (!(vd->vd_flags & VDF_TEXTMODE) && (boothowto & RB_MUTE)) {
1307 
1308 		top = (vd->vd_height - vt_logo_height) / 2;
1309 		left = (vd->vd_width - vt_logo_width) / 2;
1310 		switch (vt_logo_depth) {
1311 		case 1:
1312 			/* XXX: Unhardcode colors! */
1313 			vd->vd_driver->vd_bitblt_bmp(vd, vd->vd_curwindow,
1314 			    vt_logo_image, NULL, vt_logo_width, vt_logo_height,
1315 			    left, top, TC_WHITE, TC_BLACK);
1316 		}
1317 		vd->vd_flags |= VDF_SPLASH;
1318 	}
1319 }
1320 #endif
1321 
1322 
1323 static void
1324 vtterm_cnprobe(struct terminal *tm, struct consdev *cp)
1325 {
1326 	struct vt_driver *vtd, **vtdlist, *vtdbest = NULL;
1327 	struct vt_window *vw = tm->tm_softc;
1328 	struct vt_device *vd = vw->vw_device;
1329 	struct winsize wsz;
1330 	term_attr_t attr;
1331 	term_char_t c;
1332 
1333 	if (!vty_enabled(VTY_VT))
1334 		return;
1335 
1336 	if (vd->vd_flags & VDF_INITIALIZED)
1337 		/* Initialization already done. */
1338 		return;
1339 
1340 	SET_FOREACH(vtdlist, vt_drv_set) {
1341 		vtd = *vtdlist;
1342 		if (vtd->vd_probe == NULL)
1343 			continue;
1344 		if (vtd->vd_probe(vd) == CN_DEAD)
1345 			continue;
1346 		if ((vtdbest == NULL) ||
1347 		    (vtd->vd_priority > vtdbest->vd_priority))
1348 			vtdbest = vtd;
1349 	}
1350 	if (vtdbest == NULL) {
1351 		cp->cn_pri = CN_DEAD;
1352 		vd->vd_flags |= VDF_DEAD;
1353 	} else {
1354 		vd->vd_driver = vtdbest;
1355 		cp->cn_pri = vd->vd_driver->vd_init(vd);
1356 	}
1357 
1358 	/* Check if driver's vt_init return CN_DEAD. */
1359 	if (cp->cn_pri == CN_DEAD) {
1360 		vd->vd_flags |= VDF_DEAD;
1361 	}
1362 
1363 	/* Initialize any early-boot keyboard drivers */
1364 	kbd_configure(KB_CONF_PROBE_ONLY);
1365 
1366 	vd->vd_unit = atomic_fetchadd_int(&vt_unit, 1);
1367 	vd->vd_windows[VT_CONSWINDOW] = vw;
1368 	sprintf(cp->cn_name, "ttyv%r", VT_UNIT(vw));
1369 
1370 	/* Attach default font if not in TEXTMODE. */
1371 	if ((vd->vd_flags & VDF_TEXTMODE) == 0) {
1372 		vw->vw_font = vtfont_ref(&vt_font_default);
1373 		vt_compute_drawable_area(vw);
1374 	}
1375 
1376 	/*
1377 	 * The original screen size was faked (_VTDEFW x _VTDEFH). Now
1378 	 * that we have the real viewable size, fix it in the static
1379 	 * buffer.
1380 	 */
1381 	if (vd->vd_width != 0 && vd->vd_height != 0)
1382 		vt_termsize(vd, vw->vw_font, &vw->vw_buf.vb_scr_size);
1383 
1384 	vtbuf_init_early(&vw->vw_buf);
1385 	vt_winsize(vd, vw->vw_font, &wsz);
1386 	c = (boothowto & RB_MUTE) == 0 ? TERMINAL_KERN_ATTR :
1387 	    TERMINAL_NORM_ATTR;
1388 	attr.ta_format = TCHAR_FORMAT(c);
1389 	attr.ta_fgcolor = TCHAR_FGCOLOR(c);
1390 	attr.ta_bgcolor = TCHAR_BGCOLOR(c);
1391 	terminal_set_winsize_blank(tm, &wsz, 1, &attr);
1392 
1393 	if (vtdbest != NULL) {
1394 #ifdef DEV_SPLASH
1395 		if (!vt_splash_cpu)
1396 			vtterm_splash(vd);
1397 #endif
1398 		vd->vd_flags |= VDF_INITIALIZED;
1399 	}
1400 }
1401 
1402 static int
1403 vtterm_cngetc(struct terminal *tm)
1404 {
1405 	struct vt_window *vw = tm->tm_softc;
1406 	struct vt_device *vd = vw->vw_device;
1407 	keyboard_t *kbd;
1408 	u_int c;
1409 
1410 	if (vw->vw_kbdsq && *vw->vw_kbdsq)
1411 		return (*vw->vw_kbdsq++);
1412 
1413 	/* Make sure the splash screen is not there. */
1414 	if (vd->vd_flags & VDF_SPLASH) {
1415 		/* Remove splash */
1416 		vd->vd_flags &= ~VDF_SPLASH;
1417 		/* Mark screen as invalid to force update */
1418 		vd->vd_flags |= VDF_INVALID;
1419 		vt_flush(vd);
1420 	}
1421 
1422 	/* Stripped down keyboard handler. */
1423 	kbd = kbd_get_keyboard(vd->vd_keyboard);
1424 	if (kbd == NULL)
1425 		return (-1);
1426 
1427 	/* Force keyboard input mode to K_XLATE */
1428 	vw->vw_kbdmode = K_XLATE;
1429 	vt_update_kbd_mode(vw, kbd);
1430 
1431 	/* Switch the keyboard to polling to make it work here. */
1432 	kbdd_poll(kbd, TRUE);
1433 	c = kbdd_read_char(kbd, 0);
1434 	kbdd_poll(kbd, FALSE);
1435 	if (c & RELKEY)
1436 		return (-1);
1437 
1438 	if (vw->vw_flags & VWF_SCROLL) {
1439 		vt_scrollmode_kbdevent(vw, c, 1/* Console mode */);
1440 		vt_flush(vd);
1441 		return (-1);
1442 	}
1443 
1444 	/* Stripped down handling of vt_kbdevent(), without locking, etc. */
1445 	if (c & SPCLKEY) {
1446 		switch (c) {
1447 		case SPCLKEY | SLK:
1448 			vt_save_kbd_state(vw, kbd);
1449 			if (vw->vw_kbdstate & SLKED) {
1450 				/* Turn scrolling on. */
1451 				vw->vw_flags |= VWF_SCROLL;
1452 				VTBUF_SLCK_ENABLE(&vw->vw_buf);
1453 			} else {
1454 				/* Turn scrolling off. */
1455 				vt_scroll(vw, 0, VHS_END);
1456 				vw->vw_flags &= ~VWF_SCROLL;
1457 				VTBUF_SLCK_DISABLE(&vw->vw_buf);
1458 			}
1459 			break;
1460 		/* XXX: KDB can handle history. */
1461 		case SPCLKEY | FKEY | F(50): /* Arrow up. */
1462 			vw->vw_kbdsq = "\x1b[A";
1463 			break;
1464 		case SPCLKEY | FKEY | F(58): /* Arrow down. */
1465 			vw->vw_kbdsq = "\x1b[B";
1466 			break;
1467 		case SPCLKEY | FKEY | F(55): /* Arrow right. */
1468 			vw->vw_kbdsq = "\x1b[C";
1469 			break;
1470 		case SPCLKEY | FKEY | F(53): /* Arrow left. */
1471 			vw->vw_kbdsq = "\x1b[D";
1472 			break;
1473 		}
1474 
1475 		/* Force refresh to make scrollback work. */
1476 		vt_flush(vd);
1477 	} else if (KEYFLAGS(c) == 0) {
1478 		return (KEYCHAR(c));
1479 	}
1480 
1481 	if (vw->vw_kbdsq && *vw->vw_kbdsq)
1482 		return (*vw->vw_kbdsq++);
1483 
1484 	return (-1);
1485 }
1486 
1487 static void
1488 vtterm_cngrab(struct terminal *tm)
1489 {
1490 	struct vt_device *vd;
1491 	struct vt_window *vw;
1492 	keyboard_t *kbd;
1493 
1494 	vw = tm->tm_softc;
1495 	vd = vw->vw_device;
1496 
1497 	if (!cold)
1498 		vt_window_switch(vw);
1499 
1500 	kbd = kbd_get_keyboard(vd->vd_keyboard);
1501 	if (kbd == NULL)
1502 		return;
1503 
1504 	if (vw->vw_grabbed++ > 0)
1505 		return;
1506 
1507 	/*
1508 	 * Make sure the keyboard is accessible even when the kbd device
1509 	 * driver is disabled.
1510 	 */
1511 	kbdd_enable(kbd);
1512 
1513 	/* We shall always use the keyboard in the XLATE mode here. */
1514 	vw->vw_prev_kbdmode = vw->vw_kbdmode;
1515 	vw->vw_kbdmode = K_XLATE;
1516 	vt_update_kbd_mode(vw, kbd);
1517 
1518 	kbdd_poll(kbd, TRUE);
1519 }
1520 
1521 static void
1522 vtterm_cnungrab(struct terminal *tm)
1523 {
1524 	struct vt_device *vd;
1525 	struct vt_window *vw;
1526 	keyboard_t *kbd;
1527 
1528 	vw = tm->tm_softc;
1529 	vd = vw->vw_device;
1530 
1531 	kbd = kbd_get_keyboard(vd->vd_keyboard);
1532 	if (kbd == NULL)
1533 		return;
1534 
1535 	if (--vw->vw_grabbed > 0)
1536 		return;
1537 
1538 	kbdd_poll(kbd, FALSE);
1539 
1540 	vw->vw_kbdmode = vw->vw_prev_kbdmode;
1541 	vt_update_kbd_mode(vw, kbd);
1542 	kbdd_disable(kbd);
1543 }
1544 
1545 static void
1546 vtterm_opened(struct terminal *tm, int opened)
1547 {
1548 	struct vt_window *vw = tm->tm_softc;
1549 	struct vt_device *vd = vw->vw_device;
1550 
1551 	VT_LOCK(vd);
1552 	vd->vd_flags &= ~VDF_SPLASH;
1553 	if (opened)
1554 		vw->vw_flags |= VWF_OPENED;
1555 	else {
1556 		vw->vw_flags &= ~VWF_OPENED;
1557 		/* TODO: finish ACQ/REL */
1558 	}
1559 	VT_UNLOCK(vd);
1560 }
1561 
1562 static int
1563 vt_change_font(struct vt_window *vw, struct vt_font *vf)
1564 {
1565 	struct vt_device *vd = vw->vw_device;
1566 	struct terminal *tm = vw->vw_terminal;
1567 	term_pos_t size;
1568 	struct winsize wsz;
1569 
1570 	/*
1571 	 * Changing fonts.
1572 	 *
1573 	 * Changing fonts is a little tricky.  We must prevent
1574 	 * simultaneous access to the device, so we must stop
1575 	 * the display timer and the terminal from accessing.
1576 	 * We need to switch fonts and grow our screen buffer.
1577 	 *
1578 	 * XXX: Right now the code uses terminal_mute() to
1579 	 * prevent data from reaching the console driver while
1580 	 * resizing the screen buffer.  This isn't elegant...
1581 	 */
1582 
1583 	VT_LOCK(vd);
1584 	if (vw->vw_flags & VWF_BUSY) {
1585 		/* Another process is changing the font. */
1586 		VT_UNLOCK(vd);
1587 		return (EBUSY);
1588 	}
1589 	vw->vw_flags |= VWF_BUSY;
1590 	VT_UNLOCK(vd);
1591 
1592 	vt_termsize(vd, vf, &size);
1593 	vt_winsize(vd, vf, &wsz);
1594 
1595 	/* Grow the screen buffer and terminal. */
1596 	terminal_mute(tm, 1);
1597 	vtbuf_grow(&vw->vw_buf, &size, vw->vw_buf.vb_history_size);
1598 	terminal_set_winsize_blank(tm, &wsz, 0, NULL);
1599 	terminal_set_cursor(tm, &vw->vw_buf.vb_cursor);
1600 	terminal_mute(tm, 0);
1601 
1602 	/* Actually apply the font to the current window. */
1603 	VT_LOCK(vd);
1604 	if (vw->vw_font != vf && vw->vw_font != NULL && vf != NULL) {
1605 		/*
1606 		 * In case vt_change_font called to update size we don't need
1607 		 * to update font link.
1608 		 */
1609 		vtfont_unref(vw->vw_font);
1610 		vw->vw_font = vtfont_ref(vf);
1611 	}
1612 
1613 	/*
1614 	 * Compute the drawable area and move the mouse cursor inside
1615 	 * it, in case the new area is smaller than the previous one.
1616 	 */
1617 	vt_compute_drawable_area(vw);
1618 	vd->vd_mx = min(vd->vd_mx,
1619 	    vw->vw_draw_area.tr_end.tp_col -
1620 	    vw->vw_draw_area.tr_begin.tp_col - 1);
1621 	vd->vd_my = min(vd->vd_my,
1622 	    vw->vw_draw_area.tr_end.tp_row -
1623 	    vw->vw_draw_area.tr_begin.tp_row - 1);
1624 
1625 	/* Force a full redraw the next timer tick. */
1626 	if (vd->vd_curwindow == vw) {
1627 		vd->vd_flags |= VDF_INVALID;
1628 		vt_resume_flush_timer(vw->vw_device, 0);
1629 	}
1630 	vw->vw_flags &= ~VWF_BUSY;
1631 	VT_UNLOCK(vd);
1632 	return (0);
1633 }
1634 
1635 static int
1636 vt_proc_alive(struct vt_window *vw)
1637 {
1638 	struct proc *p;
1639 
1640 	if (vw->vw_smode.mode != VT_PROCESS)
1641 		return (FALSE);
1642 
1643 	if (vw->vw_proc) {
1644 		if ((p = pfind(vw->vw_pid)) != NULL)
1645 			PROC_UNLOCK(p);
1646 		if (vw->vw_proc == p)
1647 			return (TRUE);
1648 		vw->vw_proc = NULL;
1649 		vw->vw_smode.mode = VT_AUTO;
1650 		DPRINTF(1, "vt controlling process %d died\n", vw->vw_pid);
1651 		vw->vw_pid = 0;
1652 	}
1653 	return (FALSE);
1654 }
1655 
1656 static int
1657 signal_vt_rel(struct vt_window *vw)
1658 {
1659 
1660 	if (vw->vw_smode.mode != VT_PROCESS)
1661 		return (FALSE);
1662 	if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
1663 		vw->vw_proc = NULL;
1664 		vw->vw_pid = 0;
1665 		return (TRUE);
1666 	}
1667 	vw->vw_flags |= VWF_SWWAIT_REL;
1668 	PROC_LOCK(vw->vw_proc);
1669 	kern_psignal(vw->vw_proc, vw->vw_smode.relsig);
1670 	PROC_UNLOCK(vw->vw_proc);
1671 	DPRINTF(1, "sending relsig to %d\n", vw->vw_pid);
1672 	return (TRUE);
1673 }
1674 
1675 static int
1676 signal_vt_acq(struct vt_window *vw)
1677 {
1678 
1679 	if (vw->vw_smode.mode != VT_PROCESS)
1680 		return (FALSE);
1681 	if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
1682 		cnavailable(vw->vw_terminal->consdev, FALSE);
1683 	if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
1684 		vw->vw_proc = NULL;
1685 		vw->vw_pid = 0;
1686 		return (TRUE);
1687 	}
1688 	vw->vw_flags |= VWF_SWWAIT_ACQ;
1689 	PROC_LOCK(vw->vw_proc);
1690 	kern_psignal(vw->vw_proc, vw->vw_smode.acqsig);
1691 	PROC_UNLOCK(vw->vw_proc);
1692 	DPRINTF(1, "sending acqsig to %d\n", vw->vw_pid);
1693 	return (TRUE);
1694 }
1695 
1696 static int
1697 finish_vt_rel(struct vt_window *vw, int release, int *s)
1698 {
1699 
1700 	if (vw->vw_flags & VWF_SWWAIT_REL) {
1701 		vw->vw_flags &= ~VWF_SWWAIT_REL;
1702 		if (release) {
1703 			callout_drain(&vw->vw_proc_dead_timer);
1704 			vt_late_window_switch(vw->vw_switch_to);
1705 		}
1706 		return (0);
1707 	}
1708 	return (EINVAL);
1709 }
1710 
1711 static int
1712 finish_vt_acq(struct vt_window *vw)
1713 {
1714 
1715 	if (vw->vw_flags & VWF_SWWAIT_ACQ) {
1716 		vw->vw_flags &= ~VWF_SWWAIT_ACQ;
1717 		return (0);
1718 	}
1719 	return (EINVAL);
1720 }
1721 
1722 #ifndef SC_NO_CUTPASTE
1723 static void
1724 vt_mouse_terminput_button(struct vt_device *vd, int button)
1725 {
1726 	struct vt_window *vw;
1727 	struct vt_font *vf;
1728 	char mouseb[6] = "\x1B[M";
1729 	int i, x, y;
1730 
1731 	vw = vd->vd_curwindow;
1732 	vf = vw->vw_font;
1733 
1734 	/* Translate to char position. */
1735 	x = vd->vd_mx / vf->vf_width;
1736 	y = vd->vd_my / vf->vf_height;
1737 	/* Avoid overflow. */
1738 	x = MIN(x, 255 - '!');
1739 	y = MIN(y, 255 - '!');
1740 
1741 	mouseb[3] = ' ' + button;
1742 	mouseb[4] = '!' + x;
1743 	mouseb[5] = '!' + y;
1744 
1745 	for (i = 0; i < sizeof(mouseb); i++)
1746 		terminal_input_char(vw->vw_terminal, mouseb[i]);
1747 }
1748 
1749 static void
1750 vt_mouse_terminput(struct vt_device *vd, int type, int x, int y, int event,
1751     int cnt)
1752 {
1753 
1754 	switch (type) {
1755 	case MOUSE_BUTTON_EVENT:
1756 		if (cnt > 0) {
1757 			/* Mouse button pressed. */
1758 			if (event & MOUSE_BUTTON1DOWN)
1759 				vt_mouse_terminput_button(vd, 0);
1760 			if (event & MOUSE_BUTTON2DOWN)
1761 				vt_mouse_terminput_button(vd, 1);
1762 			if (event & MOUSE_BUTTON3DOWN)
1763 				vt_mouse_terminput_button(vd, 2);
1764 		} else {
1765 			/* Mouse button released. */
1766 			vt_mouse_terminput_button(vd, 3);
1767 		}
1768 		break;
1769 #ifdef notyet
1770 	case MOUSE_MOTION_EVENT:
1771 		if (mouse->u.data.z < 0) {
1772 			/* Scroll up. */
1773 			sc_mouse_input_button(vd, 64);
1774 		} else if (mouse->u.data.z > 0) {
1775 			/* Scroll down. */
1776 			sc_mouse_input_button(vd, 65);
1777 		}
1778 		break;
1779 #endif
1780 	}
1781 }
1782 
1783 static void
1784 vt_mouse_paste()
1785 {
1786 	term_char_t *buf;
1787 	int i, len;
1788 
1789 	len = VD_PASTEBUFLEN(main_vd);
1790 	buf = VD_PASTEBUF(main_vd);
1791 	len /= sizeof(term_char_t);
1792 	for (i = 0; i < len; i++) {
1793 		if (buf[i] == '\0')
1794 			continue;
1795 		terminal_input_char(main_vd->vd_curwindow->vw_terminal,
1796 		    buf[i]);
1797 	}
1798 }
1799 
1800 void
1801 vt_mouse_event(int type, int x, int y, int event, int cnt, int mlevel)
1802 {
1803 	struct vt_device *vd;
1804 	struct vt_window *vw;
1805 	struct vt_font *vf;
1806 	term_pos_t size;
1807 	int len, mark;
1808 
1809 	vd = main_vd;
1810 	vw = vd->vd_curwindow;
1811 	vf = vw->vw_font;
1812 	mark = 0;
1813 
1814 	if (vw->vw_flags & (VWF_MOUSE_HIDE | VWF_GRAPHICS))
1815 		/*
1816 		 * Either the mouse is disabled, or the window is in
1817 		 * "graphics mode". The graphics mode is usually set by
1818 		 * an X server, using the KDSETMODE ioctl.
1819 		 */
1820 		return;
1821 
1822 	if (vf == NULL)	/* Text mode. */
1823 		return;
1824 
1825 	/*
1826 	 * TODO: add flag about pointer position changed, to not redraw chars
1827 	 * under mouse pointer when nothing changed.
1828 	 */
1829 
1830 	if (vw->vw_mouse_level > 0)
1831 		vt_mouse_terminput(vd, type, x, y, event, cnt);
1832 
1833 	switch (type) {
1834 	case MOUSE_ACTION:
1835 	case MOUSE_MOTION_EVENT:
1836 		/* Movement */
1837 		x += vd->vd_mx;
1838 		y += vd->vd_my;
1839 
1840 		vt_termsize(vd, vf, &size);
1841 
1842 		/* Apply limits. */
1843 		x = MAX(x, 0);
1844 		y = MAX(y, 0);
1845 		x = MIN(x, (size.tp_col * vf->vf_width) - 1);
1846 		y = MIN(y, (size.tp_row * vf->vf_height) - 1);
1847 
1848 		vd->vd_mx = x;
1849 		vd->vd_my = y;
1850 		if (vd->vd_mstate & MOUSE_BUTTON1DOWN)
1851 			vtbuf_set_mark(&vw->vw_buf, VTB_MARK_MOVE,
1852 			    vd->vd_mx / vf->vf_width,
1853 			    vd->vd_my / vf->vf_height);
1854 
1855 		vt_resume_flush_timer(vw->vw_device, 0);
1856 		return; /* Done */
1857 	case MOUSE_BUTTON_EVENT:
1858 		/* Buttons */
1859 		break;
1860 	default:
1861 		return; /* Done */
1862 	}
1863 
1864 	switch (event) {
1865 	case MOUSE_BUTTON1DOWN:
1866 		switch (cnt % 4) {
1867 		case 0:	/* up */
1868 			mark = VTB_MARK_END;
1869 			break;
1870 		case 1: /* single click: start cut operation */
1871 			mark = VTB_MARK_START;
1872 			break;
1873 		case 2:	/* double click: cut a word */
1874 			mark = VTB_MARK_WORD;
1875 			break;
1876 		case 3:	/* triple click: cut a line */
1877 			mark = VTB_MARK_ROW;
1878 			break;
1879 		}
1880 		break;
1881 	case VT_MOUSE_PASTEBUTTON:
1882 		switch (cnt) {
1883 		case 0:	/* up */
1884 			break;
1885 		default:
1886 			vt_mouse_paste();
1887 			break;
1888 		}
1889 		return; /* Done */
1890 	case VT_MOUSE_EXTENDBUTTON:
1891 		switch (cnt) {
1892 		case 0:	/* up */
1893 			if (!(vd->vd_mstate & MOUSE_BUTTON1DOWN))
1894 				mark = VTB_MARK_EXTEND;
1895 			else
1896 				mark = 0;
1897 			break;
1898 		default:
1899 			mark = VTB_MARK_EXTEND;
1900 			break;
1901 		}
1902 		break;
1903 	default:
1904 		return; /* Done */
1905 	}
1906 
1907 	/* Save buttons state. */
1908 	if (cnt > 0)
1909 		vd->vd_mstate |= event;
1910 	else
1911 		vd->vd_mstate &= ~event;
1912 
1913 	if (vtbuf_set_mark(&vw->vw_buf, mark, vd->vd_mx / vf->vf_width,
1914 	    vd->vd_my / vf->vf_height) == 1) {
1915 		/*
1916 		 * We have something marked to copy, so update pointer to
1917 		 * window with selection.
1918 		 */
1919 		vt_resume_flush_timer(vw->vw_device, 0);
1920 
1921 		switch (mark) {
1922 		case VTB_MARK_END:
1923 		case VTB_MARK_WORD:
1924 		case VTB_MARK_ROW:
1925 		case VTB_MARK_EXTEND:
1926 			break;
1927 		default:
1928 			/* Other types of mark do not require to copy data. */
1929 			return;
1930 		}
1931 
1932 		/* Get current selection size in bytes. */
1933 		len = vtbuf_get_marked_len(&vw->vw_buf);
1934 		if (len <= 0)
1935 			return;
1936 
1937 		/* Reallocate buffer only if old one is too small. */
1938 		if (len > VD_PASTEBUFSZ(vd)) {
1939 			VD_PASTEBUF(vd) = realloc(VD_PASTEBUF(vd), len, M_VT,
1940 			    M_WAITOK | M_ZERO);
1941 			/* Update buffer size. */
1942 			VD_PASTEBUFSZ(vd) = len;
1943 		}
1944 		/* Request copy/paste buffer data, no more than `len' */
1945 		vtbuf_extract_marked(&vw->vw_buf, VD_PASTEBUF(vd),
1946 		    VD_PASTEBUFSZ(vd));
1947 
1948 		VD_PASTEBUFLEN(vd) = len;
1949 
1950 		/* XXX VD_PASTEBUF(vd) have to be freed on shutdown/unload. */
1951 	}
1952 }
1953 
1954 void
1955 vt_mouse_state(int show)
1956 {
1957 	struct vt_device *vd;
1958 	struct vt_window *vw;
1959 
1960 	vd = main_vd;
1961 	vw = vd->vd_curwindow;
1962 
1963 	switch (show) {
1964 	case VT_MOUSE_HIDE:
1965 		vw->vw_flags |= VWF_MOUSE_HIDE;
1966 		break;
1967 	case VT_MOUSE_SHOW:
1968 		vw->vw_flags &= ~VWF_MOUSE_HIDE;
1969 		break;
1970 	}
1971 
1972 	/* Mark mouse position as dirty. */
1973 	vt_mark_mouse_position_as_dirty(vd);
1974 	vt_resume_flush_timer(vw->vw_device, 0);
1975 }
1976 #endif
1977 
1978 static int
1979 vtterm_mmap(struct terminal *tm, vm_ooffset_t offset, vm_paddr_t * paddr,
1980     int nprot, vm_memattr_t *memattr)
1981 {
1982 	struct vt_window *vw = tm->tm_softc;
1983 	struct vt_device *vd = vw->vw_device;
1984 
1985 	if (vd->vd_driver->vd_fb_mmap)
1986 		return (vd->vd_driver->vd_fb_mmap(vd, offset, paddr, nprot,
1987 		    memattr));
1988 
1989 	return (ENXIO);
1990 }
1991 
1992 static int
1993 vtterm_ioctl(struct terminal *tm, u_long cmd, caddr_t data,
1994     struct thread *td)
1995 {
1996 	struct vt_window *vw = tm->tm_softc;
1997 	struct vt_device *vd = vw->vw_device;
1998 	keyboard_t *kbd;
1999 	int error, i, s;
2000 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
2001     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
2002 	int ival;
2003 
2004 	switch (cmd) {
2005 	case _IO('v', 4):
2006 		cmd = VT_RELDISP;
2007 		break;
2008 	case _IO('v', 5):
2009 		cmd = VT_ACTIVATE;
2010 		break;
2011 	case _IO('v', 6):
2012 		cmd = VT_WAITACTIVE;
2013 		break;
2014 	case _IO('K', 20):
2015 		cmd = KDSKBSTATE;
2016 		break;
2017 	case _IO('K', 67):
2018 		cmd = KDSETRAD;
2019 		break;
2020 	case _IO('K', 7):
2021 		cmd = KDSKBMODE;
2022 		break;
2023 	case _IO('K', 8):
2024 		cmd = KDMKTONE;
2025 		break;
2026 	case _IO('K', 63):
2027 		cmd = KIOCSOUND;
2028 		break;
2029 	case _IO('K', 66):
2030 		cmd = KDSETLED;
2031 		break;
2032 	case _IO('c', 110):
2033 		cmd = CONS_SETKBD;
2034 		break;
2035 	default:
2036 		goto skip_thunk;
2037 	}
2038 	ival = IOCPARM_IVAL(data);
2039 	data = (caddr_t)&ival;
2040 skip_thunk:
2041 #endif
2042 
2043 	switch (cmd) {
2044 	case KDSETRAD:		/* set keyboard repeat & delay rates (old) */
2045 		if (*(int *)data & ~0x7f)
2046 			return (EINVAL);
2047 		/* FALLTHROUGH */
2048 	case GIO_KEYMAP:
2049 	case PIO_KEYMAP:
2050 	case GIO_DEADKEYMAP:
2051 	case PIO_DEADKEYMAP:
2052 	case GETFKEY:
2053 	case SETFKEY:
2054 	case KDGKBINFO:
2055 	case KDGKBTYPE:
2056 	case KDGETREPEAT:	/* get keyboard repeat & delay rates */
2057 	case KDSETREPEAT:	/* set keyboard repeat & delay rates (new) */
2058 	case KBADDKBD:		/* add/remove keyboard to/from mux */
2059 	case KBRELKBD: {
2060 		error = 0;
2061 
2062 		mtx_lock(&Giant);
2063 		kbd = kbd_get_keyboard(vd->vd_keyboard);
2064 		if (kbd != NULL)
2065 			error = kbdd_ioctl(kbd, cmd, data);
2066 		mtx_unlock(&Giant);
2067 		if (error == ENOIOCTL) {
2068 			if (cmd == KDGKBTYPE) {
2069 				/* always return something? XXX */
2070 				*(int *)data = 0;
2071 			} else {
2072 				return (ENODEV);
2073 			}
2074 		}
2075 		return (error);
2076 	}
2077 	case KDGKBSTATE: {	/* get keyboard state (locks) */
2078 		error = 0;
2079 
2080 		if (vw == vd->vd_curwindow) {
2081 			mtx_lock(&Giant);
2082 			kbd = kbd_get_keyboard(vd->vd_keyboard);
2083 			if (kbd != NULL)
2084 				error = vt_save_kbd_state(vw, kbd);
2085 			mtx_unlock(&Giant);
2086 
2087 			if (error != 0)
2088 				return (error);
2089 		}
2090 
2091 		*(int *)data = vw->vw_kbdstate & LOCK_MASK;
2092 
2093 		return (error);
2094 	}
2095 	case KDSKBSTATE: {	/* set keyboard state (locks) */
2096 		int state;
2097 
2098 		state = *(int *)data;
2099 		if (state & ~LOCK_MASK)
2100 			return (EINVAL);
2101 
2102 		vw->vw_kbdstate &= ~LOCK_MASK;
2103 		vw->vw_kbdstate |= state;
2104 
2105 		error = 0;
2106 		if (vw == vd->vd_curwindow) {
2107 			mtx_lock(&Giant);
2108 			kbd = kbd_get_keyboard(vd->vd_keyboard);
2109 			if (kbd != NULL)
2110 				error = vt_update_kbd_state(vw, kbd);
2111 			mtx_unlock(&Giant);
2112 		}
2113 
2114 		return (error);
2115 	}
2116 	case KDGETLED: {	/* get keyboard LED status */
2117 		error = 0;
2118 
2119 		if (vw == vd->vd_curwindow) {
2120 			mtx_lock(&Giant);
2121 			kbd = kbd_get_keyboard(vd->vd_keyboard);
2122 			if (kbd != NULL)
2123 				error = vt_save_kbd_leds(vw, kbd);
2124 			mtx_unlock(&Giant);
2125 
2126 			if (error != 0)
2127 				return (error);
2128 		}
2129 
2130 		*(int *)data = vw->vw_kbdstate & LED_MASK;
2131 
2132 		return (error);
2133 	}
2134 	case KDSETLED: {	/* set keyboard LED status */
2135 		int leds;
2136 
2137 		leds = *(int *)data;
2138 		if (leds & ~LED_MASK)
2139 			return (EINVAL);
2140 
2141 		vw->vw_kbdstate &= ~LED_MASK;
2142 		vw->vw_kbdstate |= leds;
2143 
2144 		error = 0;
2145 		if (vw == vd->vd_curwindow) {
2146 			mtx_lock(&Giant);
2147 			kbd = kbd_get_keyboard(vd->vd_keyboard);
2148 			if (kbd != NULL)
2149 				error = vt_update_kbd_leds(vw, kbd);
2150 			mtx_unlock(&Giant);
2151 		}
2152 
2153 		return (error);
2154 	}
2155 	case KDGKBMODE: {
2156 		error = 0;
2157 
2158 		if (vw == vd->vd_curwindow) {
2159 			mtx_lock(&Giant);
2160 			kbd = kbd_get_keyboard(vd->vd_keyboard);
2161 			if (kbd != NULL)
2162 				error = vt_save_kbd_mode(vw, kbd);
2163 			mtx_unlock(&Giant);
2164 
2165 			if (error != 0)
2166 				return (error);
2167 		}
2168 
2169 		*(int *)data = vw->vw_kbdmode;
2170 
2171 		return (error);
2172 	}
2173 	case KDSKBMODE: {
2174 		int mode;
2175 
2176 		mode = *(int *)data;
2177 		switch (mode) {
2178 		case K_XLATE:
2179 		case K_RAW:
2180 		case K_CODE:
2181 			vw->vw_kbdmode = mode;
2182 
2183 			error = 0;
2184 			if (vw == vd->vd_curwindow) {
2185 				mtx_lock(&Giant);
2186 				kbd = kbd_get_keyboard(vd->vd_keyboard);
2187 				if (kbd != NULL)
2188 					error = vt_update_kbd_mode(vw, kbd);
2189 				mtx_unlock(&Giant);
2190 			}
2191 
2192 			return (error);
2193 		default:
2194 			return (EINVAL);
2195 		}
2196 	}
2197 	case FBIOGTYPE:
2198 	case FBIO_GETWINORG:	/* get frame buffer window origin */
2199 	case FBIO_GETDISPSTART:	/* get display start address */
2200 	case FBIO_GETLINEWIDTH:	/* get scan line width in bytes */
2201 	case FBIO_BLANK:	/* blank display */
2202 		if (vd->vd_driver->vd_fb_ioctl)
2203 			return (vd->vd_driver->vd_fb_ioctl(vd, cmd, data, td));
2204 		break;
2205 	case CONS_BLANKTIME:
2206 		/* XXX */
2207 		return (0);
2208 	case CONS_GET:
2209 		/* XXX */
2210 		*(int *)data = M_CG640x480;
2211 		return (0);
2212 	case CONS_BELLTYPE: 	/* set bell type sound */
2213 		if ((*(int *)data) & CONS_QUIET_BELL)
2214 			vd->vd_flags |= VDF_QUIET_BELL;
2215 		else
2216 			vd->vd_flags &= ~VDF_QUIET_BELL;
2217 		return (0);
2218 	case CONS_GETINFO: {
2219 		vid_info_t *vi = (vid_info_t *)data;
2220 		if (vi->size != sizeof(struct vid_info))
2221 			return (EINVAL);
2222 
2223 		if (vw == vd->vd_curwindow) {
2224 			mtx_lock(&Giant);
2225 			kbd = kbd_get_keyboard(vd->vd_keyboard);
2226 			if (kbd != NULL)
2227 				vt_save_kbd_state(vw, kbd);
2228 			mtx_unlock(&Giant);
2229 		}
2230 
2231 		vi->m_num = vd->vd_curwindow->vw_number + 1;
2232 		vi->mk_keylock = vw->vw_kbdstate & LOCK_MASK;
2233 		/* XXX: other fields! */
2234 		return (0);
2235 	}
2236 	case CONS_GETVERS:
2237 		*(int *)data = 0x200;
2238 		return (0);
2239 	case CONS_MODEINFO:
2240 		/* XXX */
2241 		return (0);
2242 	case CONS_MOUSECTL: {
2243 		mouse_info_t *mouse = (mouse_info_t*)data;
2244 
2245 		/*
2246 		 * All the commands except MOUSE_SHOW nd MOUSE_HIDE
2247 		 * should not be applied to individual TTYs, but only to
2248 		 * consolectl.
2249 		 */
2250 		switch (mouse->operation) {
2251 		case MOUSE_HIDE:
2252 			if (vd->vd_flags & VDF_MOUSECURSOR) {
2253 				vd->vd_flags &= ~VDF_MOUSECURSOR;
2254 #ifndef SC_NO_CUTPASTE
2255 				vt_mouse_state(VT_MOUSE_HIDE);
2256 #endif
2257 			}
2258 			return (0);
2259 		case MOUSE_SHOW:
2260 			if (!(vd->vd_flags & VDF_MOUSECURSOR)) {
2261 				vd->vd_flags |= VDF_MOUSECURSOR;
2262 				vd->vd_mx = vd->vd_width / 2;
2263 				vd->vd_my = vd->vd_height / 2;
2264 #ifndef SC_NO_CUTPASTE
2265 				vt_mouse_state(VT_MOUSE_SHOW);
2266 #endif
2267 			}
2268 			return (0);
2269 		default:
2270 			return (EINVAL);
2271 		}
2272 	}
2273 	case PIO_VFONT: {
2274 		struct vt_font *vf;
2275 
2276 		if (vd->vd_flags & VDF_TEXTMODE)
2277 			return (ENOTSUP);
2278 
2279 		error = vtfont_load((void *)data, &vf);
2280 		if (error != 0)
2281 			return (error);
2282 
2283 		error = vt_change_font(vw, vf);
2284 		vtfont_unref(vf);
2285 		return (error);
2286 	}
2287 	case PIO_VFONT_DEFAULT: {
2288 		/* Reset to default font. */
2289 		error = vt_change_font(vw, &vt_font_default);
2290 		return (error);
2291 	}
2292 	case GIO_SCRNMAP: {
2293 		scrmap_t *sm = (scrmap_t *)data;
2294 
2295 		/* We don't have screen maps, so return a handcrafted one. */
2296 		for (i = 0; i < 256; i++)
2297 			sm->scrmap[i] = i;
2298 		return (0);
2299 	}
2300 	case KDSETMODE:
2301 		/*
2302 		 * FIXME: This implementation is incomplete compared to
2303 		 * syscons.
2304 		 */
2305 		switch (*(int *)data) {
2306 		case KD_TEXT:
2307 		case KD_TEXT1:
2308 		case KD_PIXEL:
2309 			vw->vw_flags &= ~VWF_GRAPHICS;
2310 			break;
2311 		case KD_GRAPHICS:
2312 			vw->vw_flags |= VWF_GRAPHICS;
2313 			break;
2314 		}
2315 		return (0);
2316 	case KDENABIO:      	/* allow io operations */
2317 		error = priv_check(td, PRIV_IO);
2318 		if (error != 0)
2319 			return (error);
2320 		error = securelevel_gt(td->td_ucred, 0);
2321 		if (error != 0)
2322 			return (error);
2323 #if defined(__i386__)
2324 		td->td_frame->tf_eflags |= PSL_IOPL;
2325 #elif defined(__amd64__)
2326 		td->td_frame->tf_rflags |= PSL_IOPL;
2327 #endif
2328 		return (0);
2329 	case KDDISABIO:     	/* disallow io operations (default) */
2330 #if defined(__i386__)
2331 		td->td_frame->tf_eflags &= ~PSL_IOPL;
2332 #elif defined(__amd64__)
2333 		td->td_frame->tf_rflags &= ~PSL_IOPL;
2334 #endif
2335 		return (0);
2336 	case KDMKTONE:      	/* sound the bell */
2337 		vtterm_beep(tm, *(u_int *)data);
2338 		return (0);
2339 	case KIOCSOUND:     	/* make tone (*data) hz */
2340 		/* TODO */
2341 		return (0);
2342 	case CONS_SETKBD: 		/* set the new keyboard */
2343 		mtx_lock(&Giant);
2344 		error = 0;
2345 		if (vd->vd_keyboard != *(int *)data) {
2346 			kbd = kbd_get_keyboard(*(int *)data);
2347 			if (kbd == NULL) {
2348 				mtx_unlock(&Giant);
2349 				return (EINVAL);
2350 			}
2351 			i = kbd_allocate(kbd->kb_name, kbd->kb_unit,
2352 			    (void *)vd, vt_kbdevent, vd);
2353 			if (i >= 0) {
2354 				if (vd->vd_keyboard != -1) {
2355 					kbd = kbd_get_keyboard(vd->vd_keyboard);
2356 					vt_save_kbd_state(vd->vd_curwindow, kbd);
2357 					kbd_release(kbd, (void *)vd);
2358 				}
2359 				kbd = kbd_get_keyboard(i);
2360 				vd->vd_keyboard = i;
2361 
2362 				vt_update_kbd_mode(vd->vd_curwindow, kbd);
2363 				vt_update_kbd_state(vd->vd_curwindow, kbd);
2364 			} else {
2365 				error = EPERM;	/* XXX */
2366 			}
2367 		}
2368 		mtx_unlock(&Giant);
2369 		return (error);
2370 	case CONS_RELKBD: 		/* release the current keyboard */
2371 		mtx_lock(&Giant);
2372 		error = 0;
2373 		if (vd->vd_keyboard != -1) {
2374 			kbd = kbd_get_keyboard(vd->vd_keyboard);
2375 			if (kbd == NULL) {
2376 				mtx_unlock(&Giant);
2377 				return (EINVAL);
2378 			}
2379 			vt_save_kbd_state(vd->vd_curwindow, kbd);
2380 			error = kbd_release(kbd, (void *)vd);
2381 			if (error == 0) {
2382 				vd->vd_keyboard = -1;
2383 			}
2384 		}
2385 		mtx_unlock(&Giant);
2386 		return (error);
2387 	case VT_ACTIVATE: {
2388 		int win;
2389 		win = *(int *)data - 1;
2390 		DPRINTF(5, "%s%d: VT_ACTIVATE ttyv%d ", SC_DRIVER_NAME,
2391 		    VT_UNIT(vw), win);
2392 		if ((win >= VT_MAXWINDOWS) || (win < 0))
2393 			return (EINVAL);
2394 		return (vt_proc_window_switch(vd->vd_windows[win]));
2395 	}
2396 	case VT_GETACTIVE:
2397 		*(int *)data = vd->vd_curwindow->vw_number + 1;
2398 		return (0);
2399 	case VT_GETINDEX:
2400 		*(int *)data = vw->vw_number + 1;
2401 		return (0);
2402 	case VT_LOCKSWITCH:
2403 		/* TODO: Check current state, switching can be in progress. */
2404 		if ((*(int *)data) == 0x01)
2405 			vw->vw_flags |= VWF_VTYLOCK;
2406 		else if ((*(int *)data) == 0x02)
2407 			vw->vw_flags &= ~VWF_VTYLOCK;
2408 		else
2409 			return (EINVAL);
2410 		return (0);
2411 	case VT_OPENQRY:
2412 		VT_LOCK(vd);
2413 		for (i = 0; i < VT_MAXWINDOWS; i++) {
2414 			vw = vd->vd_windows[i];
2415 			if (vw == NULL)
2416 				continue;
2417 			if (!(vw->vw_flags & VWF_OPENED)) {
2418 				*(int *)data = vw->vw_number + 1;
2419 				VT_UNLOCK(vd);
2420 				return (0);
2421 			}
2422 		}
2423 		VT_UNLOCK(vd);
2424 		return (EINVAL);
2425 	case VT_WAITACTIVE: {
2426 		unsigned int idx;
2427 
2428 		error = 0;
2429 
2430 		idx = *(unsigned int *)data;
2431 		if (idx > VT_MAXWINDOWS)
2432 			return (EINVAL);
2433 		if (idx > 0)
2434 			vw = vd->vd_windows[idx - 1];
2435 
2436 		VT_LOCK(vd);
2437 		while (vd->vd_curwindow != vw && error == 0)
2438 			error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
2439 		VT_UNLOCK(vd);
2440 		return (error);
2441 	}
2442 	case VT_SETMODE: {    	/* set screen switcher mode */
2443 		struct vt_mode *mode;
2444 		struct proc *p1;
2445 
2446 		mode = (struct vt_mode *)data;
2447 		DPRINTF(5, "%s%d: VT_SETMODE ", SC_DRIVER_NAME, VT_UNIT(vw));
2448 		if (vw->vw_smode.mode == VT_PROCESS) {
2449 			p1 = pfind(vw->vw_pid);
2450 			if (vw->vw_proc == p1 && vw->vw_proc != td->td_proc) {
2451 				if (p1)
2452 					PROC_UNLOCK(p1);
2453 				DPRINTF(5, "error EPERM\n");
2454 				return (EPERM);
2455 			}
2456 			if (p1)
2457 				PROC_UNLOCK(p1);
2458 		}
2459 		if (mode->mode == VT_AUTO) {
2460 			vw->vw_smode.mode = VT_AUTO;
2461 			vw->vw_proc = NULL;
2462 			vw->vw_pid = 0;
2463 			DPRINTF(5, "VT_AUTO, ");
2464 			if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
2465 				cnavailable(vw->vw_terminal->consdev, TRUE);
2466 			/* were we in the middle of the vty switching process? */
2467 			if (finish_vt_rel(vw, TRUE, &s) == 0)
2468 				DPRINTF(5, "reset WAIT_REL, ");
2469 			if (finish_vt_acq(vw) == 0)
2470 				DPRINTF(5, "reset WAIT_ACQ, ");
2471 			return (0);
2472 		} else if (mode->mode == VT_PROCESS) {
2473 			if (!ISSIGVALID(mode->relsig) ||
2474 			    !ISSIGVALID(mode->acqsig) ||
2475 			    !ISSIGVALID(mode->frsig)) {
2476 				DPRINTF(5, "error EINVAL\n");
2477 				return (EINVAL);
2478 			}
2479 			DPRINTF(5, "VT_PROCESS %d, ", td->td_proc->p_pid);
2480 			bcopy(data, &vw->vw_smode, sizeof(struct vt_mode));
2481 			vw->vw_proc = td->td_proc;
2482 			vw->vw_pid = vw->vw_proc->p_pid;
2483 			if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
2484 				cnavailable(vw->vw_terminal->consdev, FALSE);
2485 		} else {
2486 			DPRINTF(5, "VT_SETMODE failed, unknown mode %d\n",
2487 			    mode->mode);
2488 			return (EINVAL);
2489 		}
2490 		DPRINTF(5, "\n");
2491 		return (0);
2492 	}
2493 	case VT_GETMODE:	/* get screen switcher mode */
2494 		bcopy(&vw->vw_smode, data, sizeof(struct vt_mode));
2495 		return (0);
2496 
2497 	case VT_RELDISP:	/* screen switcher ioctl */
2498 		/*
2499 		 * This must be the current vty which is in the VT_PROCESS
2500 		 * switching mode...
2501 		 */
2502 		if ((vw != vd->vd_curwindow) || (vw->vw_smode.mode !=
2503 		    VT_PROCESS)) {
2504 			return (EINVAL);
2505 		}
2506 		/* ...and this process is controlling it. */
2507 		if (vw->vw_proc != td->td_proc) {
2508 			return (EPERM);
2509 		}
2510 		error = EINVAL;
2511 		switch(*(int *)data) {
2512 		case VT_FALSE:	/* user refuses to release screen, abort */
2513 			if ((error = finish_vt_rel(vw, FALSE, &s)) == 0)
2514 				DPRINTF(5, "%s%d: VT_RELDISP: VT_FALSE\n",
2515 				    SC_DRIVER_NAME, VT_UNIT(vw));
2516 			break;
2517 		case VT_TRUE:	/* user has released screen, go on */
2518 			/* finish_vt_rel(..., TRUE, ...) should not be locked */
2519 			if (vw->vw_flags & VWF_SWWAIT_REL) {
2520 				if ((error = finish_vt_rel(vw, TRUE, &s)) == 0)
2521 					DPRINTF(5, "%s%d: VT_RELDISP: VT_TRUE\n",
2522 					    SC_DRIVER_NAME, VT_UNIT(vw));
2523 			} else {
2524 				error = EINVAL;
2525 			}
2526 			return (error);
2527 		case VT_ACKACQ:	/* acquire acknowledged, switch completed */
2528 			if ((error = finish_vt_acq(vw)) == 0)
2529 				DPRINTF(5, "%s%d: VT_RELDISP: VT_ACKACQ\n",
2530 				    SC_DRIVER_NAME, VT_UNIT(vw));
2531 			break;
2532 		default:
2533 			break;
2534 		}
2535 		return (error);
2536 	}
2537 
2538 	return (ENOIOCTL);
2539 }
2540 
2541 static struct vt_window *
2542 vt_allocate_window(struct vt_device *vd, unsigned int window)
2543 {
2544 	struct vt_window *vw;
2545 	struct terminal *tm;
2546 	term_pos_t size;
2547 	struct winsize wsz;
2548 
2549 	vw = malloc(sizeof *vw, M_VT, M_WAITOK|M_ZERO);
2550 	vw->vw_device = vd;
2551 	vw->vw_number = window;
2552 	vw->vw_kbdmode = K_XLATE;
2553 
2554 	if ((vd->vd_flags & VDF_TEXTMODE) == 0) {
2555 		vw->vw_font = vtfont_ref(&vt_font_default);
2556 		vt_compute_drawable_area(vw);
2557 	}
2558 
2559 	vt_termsize(vd, vw->vw_font, &size);
2560 	vt_winsize(vd, vw->vw_font, &wsz);
2561 	vtbuf_init(&vw->vw_buf, &size);
2562 
2563 	tm = vw->vw_terminal = terminal_alloc(&vt_termclass, vw);
2564 	terminal_set_winsize(tm, &wsz);
2565 	vd->vd_windows[window] = vw;
2566 	callout_init(&vw->vw_proc_dead_timer, 0);
2567 
2568 	return (vw);
2569 }
2570 
2571 void
2572 vt_upgrade(struct vt_device *vd)
2573 {
2574 	struct vt_window *vw;
2575 	unsigned int i;
2576 	int register_handlers;
2577 
2578 	if (!vty_enabled(VTY_VT))
2579 		return;
2580 	if (main_vd->vd_driver == NULL)
2581 		return;
2582 
2583 	for (i = 0; i < VT_MAXWINDOWS; i++) {
2584 		vw = vd->vd_windows[i];
2585 		if (vw == NULL) {
2586 			/* New window. */
2587 			vw = vt_allocate_window(vd, i);
2588 		}
2589 		if (!(vw->vw_flags & VWF_READY)) {
2590 			callout_init(&vw->vw_proc_dead_timer, 0);
2591 			terminal_maketty(vw->vw_terminal, "v%r", VT_UNIT(vw));
2592 			vw->vw_flags |= VWF_READY;
2593 			if (vw->vw_flags & VWF_CONSOLE) {
2594 				/* For existing console window. */
2595 				EVENTHANDLER_REGISTER(shutdown_pre_sync,
2596 				    vt_window_switch, vw, SHUTDOWN_PRI_DEFAULT);
2597 			}
2598 		}
2599 
2600 	}
2601 	VT_LOCK(vd);
2602 	if (vd->vd_curwindow == NULL)
2603 		vd->vd_curwindow = vd->vd_windows[VT_CONSWINDOW];
2604 
2605 	register_handlers = 0;
2606 	if (!(vd->vd_flags & VDF_ASYNC)) {
2607 		/* Attach keyboard. */
2608 		vt_allocate_keyboard(vd);
2609 
2610 		/* Init 25 Hz timer. */
2611 		callout_init_mtx(&vd->vd_timer, &vd->vd_lock, 0);
2612 
2613 		/*
2614 		 * Start timer when everything ready.
2615 		 * Note that the operations here are purposefully ordered.
2616 		 * We need to ensure vd_timer_armed is non-zero before we set
2617 		 * the VDF_ASYNC flag. That prevents this function from
2618 		 * racing with vt_resume_flush_timer() to update the
2619 		 * callout structure.
2620 		 */
2621 		atomic_add_acq_int(&vd->vd_timer_armed, 1);
2622 		vd->vd_flags |= VDF_ASYNC;
2623 		callout_reset(&vd->vd_timer, hz / VT_TIMERFREQ, vt_timer, vd);
2624 		register_handlers = 1;
2625 	}
2626 
2627 	VT_UNLOCK(vd);
2628 
2629 	/* Refill settings with new sizes. */
2630 	vt_resize(vd);
2631 
2632 	if (register_handlers) {
2633 		/* Register suspend/resume handlers. */
2634 		EVENTHANDLER_REGISTER(power_suspend_early, vt_suspend_handler,
2635 		    vd, EVENTHANDLER_PRI_ANY);
2636 		EVENTHANDLER_REGISTER(power_resume, vt_resume_handler, vd,
2637 		    EVENTHANDLER_PRI_ANY);
2638 	}
2639 }
2640 
2641 static void
2642 vt_resize(struct vt_device *vd)
2643 {
2644 	struct vt_window *vw;
2645 	int i;
2646 
2647 	for (i = 0; i < VT_MAXWINDOWS; i++) {
2648 		vw = vd->vd_windows[i];
2649 		VT_LOCK(vd);
2650 		/* Assign default font to window, if not textmode. */
2651 		if (!(vd->vd_flags & VDF_TEXTMODE) && vw->vw_font == NULL)
2652 			vw->vw_font = vtfont_ref(&vt_font_default);
2653 		VT_UNLOCK(vd);
2654 
2655 		/* Resize terminal windows */
2656 		while (vt_change_font(vw, vw->vw_font) == EBUSY) {
2657 			DPRINTF(100, "%s: vt_change_font() is busy, "
2658 			    "window %d\n", __func__, i);
2659 		}
2660 	}
2661 }
2662 
2663 static void
2664 vt_replace_backend(const struct vt_driver *drv, void *softc)
2665 {
2666 	struct vt_device *vd;
2667 
2668 	vd = main_vd;
2669 
2670 	if (vd->vd_flags & VDF_ASYNC) {
2671 		/* Stop vt_flush periodic task. */
2672 		VT_LOCK(vd);
2673 		vt_suspend_flush_timer(vd);
2674 		VT_UNLOCK(vd);
2675 		/*
2676 		 * Mute current terminal until we done. vt_change_font (called
2677 		 * from vt_resize) will unmute it.
2678 		 */
2679 		terminal_mute(vd->vd_curwindow->vw_terminal, 1);
2680 	}
2681 
2682 	/*
2683 	 * Reset VDF_TEXTMODE flag, driver who require that flag (vt_vga) will
2684 	 * set it.
2685 	 */
2686 	VT_LOCK(vd);
2687 	vd->vd_flags &= ~VDF_TEXTMODE;
2688 
2689 	if (drv != NULL) {
2690 		/*
2691 		 * We want to upgrade from the current driver to the
2692 		 * given driver.
2693 		 */
2694 
2695 		vd->vd_prev_driver = vd->vd_driver;
2696 		vd->vd_prev_softc = vd->vd_softc;
2697 		vd->vd_driver = drv;
2698 		vd->vd_softc = softc;
2699 
2700 		vd->vd_driver->vd_init(vd);
2701 	} else if (vd->vd_prev_driver != NULL && vd->vd_prev_softc != NULL) {
2702 		/*
2703 		 * No driver given: we want to downgrade to the previous
2704 		 * driver.
2705 		 */
2706 		const struct vt_driver *old_drv;
2707 		void *old_softc;
2708 
2709 		old_drv = vd->vd_driver;
2710 		old_softc = vd->vd_softc;
2711 
2712 		vd->vd_driver = vd->vd_prev_driver;
2713 		vd->vd_softc = vd->vd_prev_softc;
2714 		vd->vd_prev_driver = NULL;
2715 		vd->vd_prev_softc = NULL;
2716 
2717 		vd->vd_flags |= VDF_DOWNGRADE;
2718 
2719 		vd->vd_driver->vd_init(vd);
2720 
2721 		if (old_drv->vd_fini)
2722 			old_drv->vd_fini(vd, old_softc);
2723 
2724 		vd->vd_flags &= ~VDF_DOWNGRADE;
2725 	}
2726 
2727 	VT_UNLOCK(vd);
2728 
2729 	/* Update windows sizes and initialize last items. */
2730 	vt_upgrade(vd);
2731 
2732 #ifdef DEV_SPLASH
2733 	if (vd->vd_flags & VDF_SPLASH)
2734 		vtterm_splash(vd);
2735 #endif
2736 
2737 	if (vd->vd_flags & VDF_ASYNC) {
2738 		/* Allow to put chars now. */
2739 		terminal_mute(vd->vd_curwindow->vw_terminal, 0);
2740 		/* Rerun timer for screen updates. */
2741 		vt_resume_flush_timer(vd, 0);
2742 	}
2743 
2744 	/*
2745 	 * Register as console. If it already registered, cnadd() will ignore
2746 	 * it.
2747 	 */
2748 	termcn_cnregister(vd->vd_windows[VT_CONSWINDOW]->vw_terminal);
2749 }
2750 
2751 static void
2752 vt_suspend_handler(void *priv)
2753 {
2754 	struct vt_device *vd;
2755 
2756 	vd = priv;
2757 	if (vd->vd_driver != NULL && vd->vd_driver->vd_suspend != NULL)
2758 		vd->vd_driver->vd_suspend(vd);
2759 }
2760 
2761 static void
2762 vt_resume_handler(void *priv)
2763 {
2764 	struct vt_device *vd;
2765 
2766 	vd = priv;
2767 	if (vd->vd_driver != NULL && vd->vd_driver->vd_resume != NULL)
2768 		vd->vd_driver->vd_resume(vd);
2769 }
2770 
2771 void
2772 vt_allocate(const struct vt_driver *drv, void *softc)
2773 {
2774 
2775 	if (!vty_enabled(VTY_VT))
2776 		return;
2777 
2778 	if (main_vd->vd_driver == NULL) {
2779 		main_vd->vd_driver = drv;
2780 		printf("VT: initialize with new VT driver \"%s\".\n",
2781 		    drv->vd_name);
2782 	} else {
2783 		/*
2784 		 * Check if have rights to replace current driver. For example:
2785 		 * it is bad idea to replace KMS driver with generic VGA one.
2786 		 */
2787 		if (drv->vd_priority <= main_vd->vd_driver->vd_priority) {
2788 			printf("VT: Driver priority %d too low. Current %d\n ",
2789 			    drv->vd_priority, main_vd->vd_driver->vd_priority);
2790 			return;
2791 		}
2792 		printf("VT: Replacing driver \"%s\" with new \"%s\".\n",
2793 		    main_vd->vd_driver->vd_name, drv->vd_name);
2794 	}
2795 
2796 	vt_replace_backend(drv, softc);
2797 }
2798 
2799 void
2800 vt_deallocate(const struct vt_driver *drv, void *softc)
2801 {
2802 
2803 	if (!vty_enabled(VTY_VT))
2804 		return;
2805 
2806 	if (main_vd->vd_prev_driver == NULL ||
2807 	    main_vd->vd_driver != drv ||
2808 	    main_vd->vd_softc != softc)
2809 		return;
2810 
2811 	printf("VT: Switching back from \"%s\" to \"%s\".\n",
2812 	    main_vd->vd_driver->vd_name, main_vd->vd_prev_driver->vd_name);
2813 
2814 	vt_replace_backend(NULL, NULL);
2815 }
2816 
2817 void
2818 vt_suspend(struct vt_device *vd)
2819 {
2820 	int error;
2821 
2822 	if (vt_suspendswitch == 0)
2823 		return;
2824 	/* Save current window. */
2825 	vd->vd_savedwindow = vd->vd_curwindow;
2826 	/* Ask holding process to free window and switch to console window */
2827 	vt_proc_window_switch(vd->vd_windows[VT_CONSWINDOW]);
2828 
2829 	/* Wait for the window switch to complete. */
2830 	error = 0;
2831 	VT_LOCK(vd);
2832 	while (vd->vd_curwindow != vd->vd_windows[VT_CONSWINDOW] && error == 0)
2833 		error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
2834 	VT_UNLOCK(vd);
2835 }
2836 
2837 void
2838 vt_resume(struct vt_device *vd)
2839 {
2840 
2841 	if (vt_suspendswitch == 0)
2842 		return;
2843 	/* Switch back to saved window, if any */
2844 	vt_proc_window_switch(vd->vd_savedwindow);
2845 	vd->vd_savedwindow = NULL;
2846 }
2847