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