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