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