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