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