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