xref: /freebsd/sys/dev/vt/vt_core.c (revision 357378bbdedf24ce2b90e9bd831af4a9db3ec70a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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/param.h>
35 #include <sys/consio.h>
36 #include <sys/devctl.h>
37 #include <sys/eventhandler.h>
38 #include <sys/fbio.h>
39 #include <sys/font.h>
40 #include <sys/kbio.h>
41 #include <sys/kdb.h>
42 #include <sys/kernel.h>
43 #include <sys/linker.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/mutex.h>
47 #include <sys/splash.h>
48 #include <sys/power.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/random.h>
52 #include <sys/reboot.h>
53 #include <sys/sbuf.h>
54 #include <sys/systm.h>
55 #include <sys/terminal.h>
56 
57 #include <dev/kbd/kbdreg.h>
58 #include <dev/vt/vt.h>
59 
60 #if defined(__i386__) || defined(__amd64__)
61 #include <machine/psl.h>
62 #include <machine/frame.h>
63 #endif
64 
65 static int vtterm_cngrab_noswitch(struct vt_device *, struct vt_window *);
66 static int vtterm_cnungrab_noswitch(struct vt_device *, struct vt_window *);
67 
68 static tc_bell_t	vtterm_bell;
69 static tc_cursor_t	vtterm_cursor;
70 static tc_putchar_t	vtterm_putchar;
71 static tc_fill_t	vtterm_fill;
72 static tc_copy_t	vtterm_copy;
73 static tc_pre_input_t	vtterm_pre_input;
74 static tc_post_input_t	vtterm_post_input;
75 static tc_param_t	vtterm_param;
76 static tc_done_t	vtterm_done;
77 
78 static tc_cnprobe_t	vtterm_cnprobe;
79 static tc_cngetc_t	vtterm_cngetc;
80 
81 static tc_cngrab_t	vtterm_cngrab;
82 static tc_cnungrab_t	vtterm_cnungrab;
83 
84 static tc_opened_t	vtterm_opened;
85 static tc_ioctl_t	vtterm_ioctl;
86 static tc_mmap_t	vtterm_mmap;
87 
88 static const struct terminal_class vt_termclass = {
89 	.tc_bell	= vtterm_bell,
90 	.tc_cursor	= vtterm_cursor,
91 	.tc_putchar	= vtterm_putchar,
92 	.tc_fill	= vtterm_fill,
93 	.tc_copy	= vtterm_copy,
94 	.tc_pre_input	= vtterm_pre_input,
95 	.tc_post_input	= vtterm_post_input,
96 	.tc_param	= vtterm_param,
97 	.tc_done	= vtterm_done,
98 
99 	.tc_cnprobe	= vtterm_cnprobe,
100 	.tc_cngetc	= vtterm_cngetc,
101 
102 	.tc_cngrab	= vtterm_cngrab,
103 	.tc_cnungrab	= vtterm_cnungrab,
104 
105 	.tc_opened	= vtterm_opened,
106 	.tc_ioctl	= vtterm_ioctl,
107 	.tc_mmap	= vtterm_mmap,
108 };
109 
110 /*
111  * Use a constant timer of 25 Hz to redraw the screen.
112  *
113  * XXX: In theory we should only fire up the timer when there is really
114  * activity. Unfortunately we cannot always start timers. We really
115  * don't want to process kernel messages synchronously, because it
116  * really slows down the system.
117  */
118 #define	VT_TIMERFREQ	25
119 
120 /* Bell pitch/duration. */
121 #define	VT_BELLDURATION	(SBT_1S / 20)
122 #define	VT_BELLPITCH	(1193182 / 800) /* Approx 1491Hz */
123 
124 #define	VT_UNIT(vw)	((vw)->vw_device->vd_unit * VT_MAXWINDOWS + \
125 			(vw)->vw_number)
126 
127 static SYSCTL_NODE(_kern, OID_AUTO, vt, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
128     "vt(9) parameters");
129 static VT_SYSCTL_INT(enable_altgr, 1, "Enable AltGr key (Do not assume R.Alt as Alt)");
130 static VT_SYSCTL_INT(enable_bell, 0, "Enable bell");
131 static VT_SYSCTL_INT(debug, 0, "vt(9) debug level");
132 static VT_SYSCTL_INT(deadtimer, 15, "Time to wait busy process in VT_PROCESS mode");
133 static VT_SYSCTL_INT(suspendswitch, 1, "Switch to VT0 before suspend");
134 
135 /* Allow to disable some keyboard combinations. */
136 static VT_SYSCTL_INT(kbd_halt, 1, "Enable halt keyboard combination.  "
137     "See kbdmap(5) to configure.");
138 static VT_SYSCTL_INT(kbd_poweroff, 1, "Enable Power Off keyboard combination.  "
139     "See kbdmap(5) to configure.");
140 static VT_SYSCTL_INT(kbd_reboot, 1, "Enable reboot keyboard combination.  "
141     "See kbdmap(5) to configure (typically Ctrl-Alt-Delete).");
142 static VT_SYSCTL_INT(kbd_debug, 1, "Enable key combination to enter debugger.  "
143     "See kbdmap(5) to configure (typically Ctrl-Alt-Esc).");
144 static VT_SYSCTL_INT(kbd_panic, 0, "Enable request to panic.  "
145     "See kbdmap(5) to configure.");
146 
147 /* Used internally, not a tunable. */
148 int vt_draw_logo_cpus;
149 VT_SYSCTL_INT(splash_cpu, 0, "Show logo CPUs during boot");
150 VT_SYSCTL_INT(splash_ncpu, 0, "Override number of logos displayed "
151     "(0 = do not override)");
152 VT_SYSCTL_INT(splash_cpu_style, 2, "Draw logo style "
153     "(0 = Alternate beastie, 1 = Beastie, 2 = Orb)");
154 VT_SYSCTL_INT(splash_cpu_duration, 10, "Hide logos after (seconds)");
155 
156 static unsigned int vt_unit = 0;
157 static MALLOC_DEFINE(M_VT, "vt", "vt device");
158 struct vt_device *main_vd = &vt_consdev;
159 
160 /* Boot logo. */
161 extern unsigned int vt_logo_width;
162 extern unsigned int vt_logo_height;
163 extern unsigned int vt_logo_depth;
164 extern unsigned char vt_logo_image[];
165 #ifndef DEV_SPLASH
166 #define	vtterm_draw_cpu_logos(...)	do {} while (0)
167 const unsigned int vt_logo_sprite_height;
168 #endif
169 
170 /*
171  * Console font. vt_font_loader will be filled with font data passed
172  * by loader. If there is no font passed by boot loader, we use built in
173  * default.
174  */
175 extern struct vt_font vt_font_default;
176 static struct vt_font vt_font_loader;
177 static struct vt_font *vt_font_assigned = &vt_font_default;
178 
179 #ifndef SC_NO_CUTPASTE
180 extern struct vt_mouse_cursor vt_default_mouse_pointer;
181 #endif
182 
183 static int signal_vt_rel(struct vt_window *);
184 static int signal_vt_acq(struct vt_window *);
185 static int finish_vt_rel(struct vt_window *, int, int *);
186 static int finish_vt_acq(struct vt_window *);
187 static int vt_window_switch(struct vt_window *);
188 static int vt_late_window_switch(struct vt_window *);
189 static int vt_proc_alive(struct vt_window *);
190 static void vt_resize(struct vt_device *);
191 static void vt_update_static(void *);
192 #ifndef SC_NO_CUTPASTE
193 static void vt_mouse_paste(void);
194 #endif
195 static void vt_suspend_handler(void *priv);
196 static void vt_resume_handler(void *priv);
197 
198 SET_DECLARE(vt_drv_set, struct vt_driver);
199 
200 #define	_VTDEFH	MAX(100, PIXEL_HEIGHT(VT_FB_MAX_HEIGHT))
201 #define	_VTDEFW	MAX(200, PIXEL_WIDTH(VT_FB_MAX_WIDTH))
202 
203 static struct terminal	vt_consterm;
204 static struct vt_window	vt_conswindow;
205 static term_char_t vt_consdrawn[PIXEL_HEIGHT(VT_FB_MAX_HEIGHT) * PIXEL_WIDTH(VT_FB_MAX_WIDTH)];
206 static term_color_t vt_consdrawnfg[PIXEL_HEIGHT(VT_FB_MAX_HEIGHT) * PIXEL_WIDTH(VT_FB_MAX_WIDTH)];
207 static term_color_t vt_consdrawnbg[PIXEL_HEIGHT(VT_FB_MAX_HEIGHT) * PIXEL_WIDTH(VT_FB_MAX_WIDTH)];
208 static bool vt_cons_pos_to_flush[PIXEL_HEIGHT(VT_FB_MAX_HEIGHT) * PIXEL_WIDTH(VT_FB_MAX_WIDTH)];
209 struct vt_device	vt_consdev = {
210 	.vd_driver = NULL,
211 	.vd_softc = NULL,
212 	.vd_prev_driver = NULL,
213 	.vd_prev_softc = NULL,
214 	.vd_flags = VDF_INVALID,
215 	.vd_windows = { [VT_CONSWINDOW] =  &vt_conswindow, },
216 	.vd_curwindow = &vt_conswindow,
217 	.vd_kbstate = 0,
218 
219 #ifndef SC_NO_CUTPASTE
220 	.vd_pastebuf = {
221 		.vpb_buf = NULL,
222 		.vpb_bufsz = 0,
223 		.vpb_len = 0
224 	},
225 	.vd_mcursor = &vt_default_mouse_pointer,
226 	.vd_mcursor_fg = TC_WHITE,
227 	.vd_mcursor_bg = TC_BLACK,
228 #endif
229 
230 	.vd_drawn = vt_consdrawn,
231 	.vd_drawnfg = vt_consdrawnfg,
232 	.vd_drawnbg = vt_consdrawnbg,
233 
234 	.vd_pos_to_flush = vt_cons_pos_to_flush,
235 };
236 static term_char_t vt_constextbuf[(_VTDEFW) * (VBF_DEFAULT_HISTORY_SIZE)];
237 static term_char_t *vt_constextbufrows[VBF_DEFAULT_HISTORY_SIZE];
238 static struct vt_window	vt_conswindow = {
239 	.vw_number = VT_CONSWINDOW,
240 	.vw_flags = VWF_CONSOLE,
241 	.vw_buf = {
242 		.vb_buffer = &vt_constextbuf[0],
243 		.vb_rows = &vt_constextbufrows[0],
244 		.vb_history_size = VBF_DEFAULT_HISTORY_SIZE,
245 		.vb_curroffset = 0,
246 		.vb_roffset = 0,
247 		.vb_flags = VBF_STATIC,
248 		.vb_mark_start = {.tp_row = 0, .tp_col = 0,},
249 		.vb_mark_end = {.tp_row = 0, .tp_col = 0,},
250 		.vb_scr_size = {
251 			.tp_row = _VTDEFH,
252 			.tp_col = _VTDEFW,
253 		},
254 	},
255 	.vw_device = &vt_consdev,
256 	.vw_terminal = &vt_consterm,
257 	.vw_kbdmode = K_XLATE,
258 	.vw_grabbed = 0,
259 	.vw_bell_pitch = VT_BELLPITCH,
260 	.vw_bell_duration = VT_BELLDURATION,
261 };
262 
263 /* Add to set of consoles. */
264 TERMINAL_DECLARE_EARLY(vt_consterm, vt_termclass, &vt_conswindow);
265 
266 /*
267  * Right after kmem is done to allow early drivers to use locking and allocate
268  * memory.
269  */
270 SYSINIT(vt_update_static, SI_SUB_KMEM, SI_ORDER_ANY, vt_update_static,
271     &vt_consdev);
272 /* Delay until all devices attached, to not waste time. */
273 SYSINIT(vt_early_cons, SI_SUB_INT_CONFIG_HOOKS, SI_ORDER_ANY, vt_upgrade,
274     &vt_consdev);
275 
276 static bool inside_vt_flush = false;
277 static bool inside_vt_window_switch = false;
278 
279 /* Initialize locks/mem depended members. */
280 static void
281 vt_update_static(void *dummy)
282 {
283 
284 	if (!vty_enabled(VTY_VT))
285 		return;
286 	if (main_vd->vd_driver != NULL)
287 		printf("VT(%s): %s %ux%u\n", main_vd->vd_driver->vd_name,
288 		    (main_vd->vd_flags & VDF_TEXTMODE) ? "text" : "resolution",
289 		    main_vd->vd_width, main_vd->vd_height);
290 	else
291 		printf("VT: init without driver.\n");
292 
293 	mtx_init(&main_vd->vd_lock, "vtdev", NULL, MTX_DEF);
294 	mtx_init(&main_vd->vd_flush_lock, "vtdev flush", NULL, MTX_DEF);
295 	cv_init(&main_vd->vd_winswitch, "vtwswt");
296 }
297 
298 static void
299 vt_schedule_flush(struct vt_device *vd, int ms)
300 {
301 
302 	if (ms <= 0)
303 		/* Default to initial value. */
304 		ms = 1000 / VT_TIMERFREQ;
305 
306 	callout_schedule(&vd->vd_timer, hz / (1000 / ms));
307 }
308 
309 void
310 vt_resume_flush_timer(struct vt_window *vw, int ms)
311 {
312 	struct vt_device *vd = vw->vw_device;
313 
314 	if (vd->vd_curwindow != vw)
315 		return;
316 
317 	if (!(vd->vd_flags & VDF_ASYNC) ||
318 	    !atomic_cmpset_int(&vd->vd_timer_armed, 0, 1))
319 		return;
320 
321 	vt_schedule_flush(vd, ms);
322 }
323 
324 static void
325 vt_suspend_flush_timer(struct vt_device *vd)
326 {
327 	/*
328 	 * As long as this function is called locked, callout_stop()
329 	 * has the same effect like callout_drain() with regard to
330 	 * preventing the callback function from executing.
331 	 */
332 	VT_LOCK_ASSERT(vd, MA_OWNED);
333 
334 	if (!(vd->vd_flags & VDF_ASYNC) ||
335 	    !atomic_cmpset_int(&vd->vd_timer_armed, 1, 0))
336 		return;
337 
338 	callout_stop(&vd->vd_timer);
339 }
340 
341 static void
342 vt_switch_timer(void *arg, int pending)
343 {
344 
345 	(void)vt_late_window_switch((struct vt_window *)arg);
346 }
347 
348 static int
349 vt_save_kbd_mode(struct vt_window *vw, keyboard_t *kbd)
350 {
351 	int mode, ret;
352 
353 	mode = 0;
354 	ret = kbdd_ioctl(kbd, KDGKBMODE, (caddr_t)&mode);
355 	if (ret == ENOIOCTL)
356 		ret = ENODEV;
357 	if (ret != 0)
358 		return (ret);
359 
360 	vw->vw_kbdmode = mode;
361 
362 	return (0);
363 }
364 
365 static int
366 vt_update_kbd_mode(struct vt_window *vw, keyboard_t *kbd)
367 {
368 	int ret;
369 
370 	ret = kbdd_ioctl(kbd, KDSKBMODE, (caddr_t)&vw->vw_kbdmode);
371 	if (ret == ENOIOCTL)
372 		ret = ENODEV;
373 
374 	return (ret);
375 }
376 
377 static int
378 vt_save_kbd_state(struct vt_window *vw, keyboard_t *kbd)
379 {
380 	int state, ret;
381 
382 	state = 0;
383 	ret = kbdd_ioctl(kbd, KDGKBSTATE, (caddr_t)&state);
384 	if (ret == ENOIOCTL)
385 		ret = ENODEV;
386 	if (ret != 0)
387 		return (ret);
388 
389 	vw->vw_kbdstate &= ~LOCK_MASK;
390 	vw->vw_kbdstate |= state & LOCK_MASK;
391 
392 	return (0);
393 }
394 
395 static int
396 vt_update_kbd_state(struct vt_window *vw, keyboard_t *kbd)
397 {
398 	int state, ret;
399 
400 	state = vw->vw_kbdstate & LOCK_MASK;
401 	ret = kbdd_ioctl(kbd, KDSKBSTATE, (caddr_t)&state);
402 	if (ret == ENOIOCTL)
403 		ret = ENODEV;
404 
405 	return (ret);
406 }
407 
408 static int
409 vt_save_kbd_leds(struct vt_window *vw, keyboard_t *kbd)
410 {
411 	int leds, ret;
412 
413 	leds = 0;
414 	ret = kbdd_ioctl(kbd, KDGETLED, (caddr_t)&leds);
415 	if (ret == ENOIOCTL)
416 		ret = ENODEV;
417 	if (ret != 0)
418 		return (ret);
419 
420 	vw->vw_kbdstate &= ~LED_MASK;
421 	vw->vw_kbdstate |= leds & LED_MASK;
422 
423 	return (0);
424 }
425 
426 static int
427 vt_update_kbd_leds(struct vt_window *vw, keyboard_t *kbd)
428 {
429 	int leds, ret;
430 
431 	leds = vw->vw_kbdstate & LED_MASK;
432 	ret = kbdd_ioctl(kbd, KDSETLED, (caddr_t)&leds);
433 	if (ret == ENOIOCTL)
434 		ret = ENODEV;
435 
436 	return (ret);
437 }
438 
439 static int
440 vt_window_preswitch(struct vt_window *vw, struct vt_window *curvw)
441 {
442 
443 	DPRINTF(40, "%s\n", __func__);
444 	curvw->vw_switch_to = vw;
445 	/* Set timer to allow switch in case when process hang. */
446 	taskqueue_enqueue_timeout(taskqueue_thread, &vw->vw_timeout_task_dead, hz * vt_deadtimer);
447 	/* Notify process about vt switch attempt. */
448 	DPRINTF(30, "%s: Notify process.\n", __func__);
449 	signal_vt_rel(curvw);
450 
451 	return (0);
452 }
453 
454 static int
455 vt_window_postswitch(struct vt_window *vw)
456 {
457 
458 	signal_vt_acq(vw);
459 	return (0);
460 }
461 
462 /* vt_late_window_switch will do VT switching for regular case. */
463 static int
464 vt_late_window_switch(struct vt_window *vw)
465 {
466 	struct vt_window *curvw;
467 	int ret;
468 
469 	taskqueue_cancel_timeout(taskqueue_thread, &vw->vw_timeout_task_dead, NULL);
470 
471 	ret = vt_window_switch(vw);
472 	if (ret != 0) {
473 		/*
474 		 * If the switch hasn't happened, then return the VT
475 		 * to the current owner, if any.
476 		 */
477 		curvw = vw->vw_device->vd_curwindow;
478 		if (curvw->vw_smode.mode == VT_PROCESS)
479 			(void)vt_window_postswitch(curvw);
480 		return (ret);
481 	}
482 
483 	/* Notify owner process about terminal availability. */
484 	if (vw->vw_smode.mode == VT_PROCESS) {
485 		ret = vt_window_postswitch(vw);
486 	}
487 	return (ret);
488 }
489 
490 /* Switch window. */
491 static int
492 vt_proc_window_switch(struct vt_window *vw)
493 {
494 	struct vt_window *curvw;
495 	struct vt_device *vd;
496 	int ret;
497 
498 	/* Prevent switching to NULL */
499 	if (vw == NULL) {
500 		DPRINTF(30, "%s: Cannot switch: vw is NULL.", __func__);
501 		return (EINVAL);
502 	}
503 	vd = vw->vw_device;
504 	curvw = vd->vd_curwindow;
505 
506 	/* Check if virtual terminal is locked */
507 	if (curvw->vw_flags & VWF_VTYLOCK)
508 		return (EBUSY);
509 
510 	/* Check if switch already in progress */
511 	if (curvw->vw_flags & VWF_SWWAIT_REL) {
512 		/* Check if switching to same window */
513 		if (curvw->vw_switch_to == vw) {
514 			DPRINTF(30, "%s: Switch in progress to same vw.", __func__);
515 			return (0);	/* success */
516 		}
517 		DPRINTF(30, "%s: Switch in progress to different vw.", __func__);
518 		return (EBUSY);
519 	}
520 
521 	/* Avoid switching to already selected window */
522 	if (vw == curvw) {
523 		DPRINTF(30, "%s: Cannot switch: vw == curvw.", __func__);
524 		return (0);	/* success */
525 	}
526 
527 	/*
528 	 * Early check for an attempt to switch to a non-functional VT.
529 	 * The same check is done in vt_window_switch(), but it's better
530 	 * to fail as early as possible to avoid needless pre-switch
531 	 * actions.
532 	 */
533 	VT_LOCK(vd);
534 	if ((vw->vw_flags & (VWF_OPENED|VWF_CONSOLE)) == 0) {
535 		VT_UNLOCK(vd);
536 		return (EINVAL);
537 	}
538 	VT_UNLOCK(vd);
539 
540 	/* Ask current process permission to switch away. */
541 	if (curvw->vw_smode.mode == VT_PROCESS) {
542 		DPRINTF(30, "%s: VT_PROCESS ", __func__);
543 		if (vt_proc_alive(curvw) == FALSE) {
544 			DPRINTF(30, "Dead. Cleaning.");
545 			/* Dead */
546 		} else {
547 			DPRINTF(30, "%s: Signaling process.\n", __func__);
548 			/* Alive, try to ask him. */
549 			ret = vt_window_preswitch(vw, curvw);
550 			/* Wait for process answer or timeout. */
551 			return (ret);
552 		}
553 		DPRINTF(30, "\n");
554 	}
555 
556 	ret = vt_late_window_switch(vw);
557 	return (ret);
558 }
559 
560 /* Switch window ignoring process locking. */
561 static int
562 vt_window_switch(struct vt_window *vw)
563 {
564 	struct vt_device *vd = vw->vw_device;
565 	struct vt_window *curvw = vd->vd_curwindow;
566 	keyboard_t *kbd;
567 
568 	if (inside_vt_window_switch && KERNEL_PANICKED())
569 		return (0);
570 
571 	inside_vt_window_switch = true;
572 
573 	if (kdb_active) {
574 		/*
575 		 * When grabbing the console for the debugger, avoid
576 		 * locks as that can result in deadlock.  While this
577 		 * could use try locks, that wouldn't really make a
578 		 * difference as there are sufficient barriers in
579 		 * debugger entry/exit to be equivalent to
580 		 * successfully try-locking here.
581 		 */
582 		if (!(vw->vw_flags & (VWF_OPENED|VWF_CONSOLE))) {
583 			inside_vt_window_switch = false;
584 			return (EINVAL);
585 		}
586 
587 		vd->vd_curwindow = vw;
588 		vd->vd_flags |= VDF_INVALID;
589 		if (vd->vd_driver->vd_postswitch)
590 			vd->vd_driver->vd_postswitch(vd);
591 		inside_vt_window_switch = false;
592 		return (0);
593 	}
594 
595 	VT_LOCK(vd);
596 	if (curvw == vw) {
597 		/*
598 		 * Nothing to do, except ensure the driver has the opportunity to
599 		 * switch to console mode when panicking, making sure the panic
600 		 * is readable (even when a GUI was using ttyv0).
601 		 */
602 		if ((kdb_active || KERNEL_PANICKED()) &&
603 		    vd->vd_driver->vd_postswitch)
604 			vd->vd_driver->vd_postswitch(vd);
605 		inside_vt_window_switch = false;
606 		VT_UNLOCK(vd);
607 		return (0);
608 	}
609 	if (!(vw->vw_flags & (VWF_OPENED|VWF_CONSOLE))) {
610 		inside_vt_window_switch = false;
611 		VT_UNLOCK(vd);
612 		return (EINVAL);
613 	}
614 
615 	vt_suspend_flush_timer(vd);
616 
617 	vd->vd_curwindow = vw;
618 	vd->vd_flags |= VDF_INVALID;
619 	cv_broadcast(&vd->vd_winswitch);
620 	VT_UNLOCK(vd);
621 
622 	if (vd->vd_driver->vd_postswitch)
623 		vd->vd_driver->vd_postswitch(vd);
624 
625 	vt_resume_flush_timer(vw, 0);
626 
627 	/* Restore per-window keyboard mode. */
628 	mtx_lock(&Giant);
629 	if ((kbd = vd->vd_keyboard) != NULL) {
630 		if (curvw->vw_kbdmode == K_XLATE)
631 			vt_save_kbd_state(curvw, kbd);
632 
633 		vt_update_kbd_mode(vw, kbd);
634 		vt_update_kbd_state(vw, kbd);
635 	}
636 	mtx_unlock(&Giant);
637 	DPRINTF(10, "%s(ttyv%d) done\n", __func__, vw->vw_number);
638 
639 	inside_vt_window_switch = false;
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 void
1350 vt_flush_to_buffer(struct vt_device *vd,
1351     const struct vt_window *vw, const term_rect_t *area)
1352 {
1353 	unsigned int col, row;
1354 	term_char_t c;
1355 	term_color_t fg, bg;
1356 	size_t z;
1357 
1358 	for (row = area->tr_begin.tp_row; row < area->tr_end.tp_row; ++row) {
1359 		for (col = area->tr_begin.tp_col; col < area->tr_end.tp_col;
1360 		    ++col) {
1361 			z = row * PIXEL_WIDTH(VT_FB_MAX_WIDTH) + col;
1362 			if (z >= PIXEL_HEIGHT(VT_FB_MAX_HEIGHT) *
1363 			    PIXEL_WIDTH(VT_FB_MAX_WIDTH))
1364 				continue;
1365 
1366 			c = VTBUF_GET_FIELD(&vw->vw_buf, row, col);
1367 			vt_determine_colors(c,
1368 			    VTBUF_ISCURSOR(&vw->vw_buf, row, col), &fg, &bg);
1369 
1370 			if (vd->vd_drawn && (vd->vd_drawn[z] == c) &&
1371 			    vd->vd_drawnfg && (vd->vd_drawnfg[z] == fg) &&
1372 			    vd->vd_drawnbg && (vd->vd_drawnbg[z] == bg)) {
1373 				vd->vd_pos_to_flush[z] = false;
1374 				continue;
1375 			}
1376 
1377 			vd->vd_pos_to_flush[z] = true;
1378 
1379 			if (vd->vd_drawn)
1380 				vd->vd_drawn[z] = c;
1381 			if (vd->vd_drawnfg)
1382 				vd->vd_drawnfg[z] = fg;
1383 			if (vd->vd_drawnbg)
1384 				vd->vd_drawnbg[z] = bg;
1385 		}
1386 	}
1387 }
1388 
1389 static void
1390 vt_bitblt_buffer(struct vt_device *vd, const struct vt_window *vw,
1391     const term_rect_t *area)
1392 {
1393 	unsigned int col, row, x, y;
1394 	struct vt_font *vf;
1395 	term_char_t c;
1396 	term_color_t fg, bg;
1397 	const uint8_t *pattern;
1398 	size_t z;
1399 
1400 	vf = vw->vw_font;
1401 
1402 	for (row = area->tr_begin.tp_row; row < area->tr_end.tp_row; ++row) {
1403 		for (col = area->tr_begin.tp_col; col < area->tr_end.tp_col;
1404 		    ++col) {
1405 			x = col * vf->vf_width +
1406 			    vw->vw_draw_area.tr_begin.tp_col;
1407 			y = row * vf->vf_height +
1408 			    vw->vw_draw_area.tr_begin.tp_row;
1409 
1410 			z = row * PIXEL_WIDTH(VT_FB_MAX_WIDTH) + col;
1411 			if (z >= PIXEL_HEIGHT(VT_FB_MAX_HEIGHT) *
1412 			    PIXEL_WIDTH(VT_FB_MAX_WIDTH))
1413 				continue;
1414 			if (!vd->vd_pos_to_flush[z])
1415 				continue;
1416 
1417 			c = vd->vd_drawn[z];
1418 			fg = vd->vd_drawnfg[z];
1419 			bg = vd->vd_drawnbg[z];
1420 
1421 			pattern = vtfont_lookup(vf, c);
1422 			vd->vd_driver->vd_bitblt_bmp(vd, vw,
1423 			    pattern, NULL, vf->vf_width, vf->vf_height,
1424 			    x, y, fg, bg);
1425 		}
1426 	}
1427 
1428 #ifndef SC_NO_CUTPASTE
1429 	if (!vd->vd_mshown)
1430 		return;
1431 
1432 	term_rect_t drawn_area;
1433 
1434 	drawn_area.tr_begin.tp_col = area->tr_begin.tp_col * vf->vf_width;
1435 	drawn_area.tr_begin.tp_row = area->tr_begin.tp_row * vf->vf_height;
1436 	drawn_area.tr_end.tp_col = area->tr_end.tp_col * vf->vf_width;
1437 	drawn_area.tr_end.tp_row = area->tr_end.tp_row * vf->vf_height;
1438 
1439 	if (vt_is_cursor_in_area(vd, &drawn_area)) {
1440 		vd->vd_driver->vd_bitblt_bmp(vd, vw,
1441 		    vd->vd_mcursor->map, vd->vd_mcursor->mask,
1442 		    vd->vd_mcursor->width, vd->vd_mcursor->height,
1443 		    vd->vd_mx_drawn + vw->vw_draw_area.tr_begin.tp_col,
1444 		    vd->vd_my_drawn + vw->vw_draw_area.tr_begin.tp_row,
1445 		    vd->vd_mcursor_fg, vd->vd_mcursor_bg);
1446 	}
1447 #endif
1448 }
1449 
1450 static void
1451 vt_draw_decorations(struct vt_device *vd)
1452 {
1453 	struct vt_window *vw;
1454 	const teken_attr_t *a;
1455 
1456 	vw = vd->vd_curwindow;
1457 
1458 	a = teken_get_curattr(&vw->vw_terminal->tm_emulator);
1459 	vt_set_border(vd, &vw->vw_draw_area, a->ta_bgcolor);
1460 
1461 	if (vt_draw_logo_cpus)
1462 		vtterm_draw_cpu_logos(vd);
1463 }
1464 
1465 static int
1466 vt_flush(struct vt_device *vd)
1467 {
1468 	struct vt_window *vw;
1469 	struct vt_font *vf;
1470 	term_rect_t tarea;
1471 #ifndef SC_NO_CUTPASTE
1472 	int cursor_was_shown, cursor_moved;
1473 #endif
1474 	bool needs_refresh;
1475 
1476 	if (inside_vt_flush && KERNEL_PANICKED())
1477 		return (0);
1478 
1479 	vw = vd->vd_curwindow;
1480 	if (vw == NULL)
1481 		return (0);
1482 
1483 	if (vd->vd_flags & VDF_SPLASH || vw->vw_flags & VWF_BUSY)
1484 		return (0);
1485 
1486 	vf = vw->vw_font;
1487 	if (((vd->vd_flags & VDF_TEXTMODE) == 0) && (vf == NULL))
1488 		return (0);
1489 
1490 	VT_FLUSH_LOCK(vd);
1491 
1492 	vtbuf_lock(&vw->vw_buf);
1493 	inside_vt_flush = true;
1494 
1495 #ifndef SC_NO_CUTPASTE
1496 	cursor_was_shown = vd->vd_mshown;
1497 	cursor_moved = (vd->vd_mx != vd->vd_mx_drawn ||
1498 	    vd->vd_my != vd->vd_my_drawn);
1499 
1500 	/* Check if the cursor should be displayed or not. */
1501 	if ((vd->vd_flags & VDF_MOUSECURSOR) && /* Mouse support enabled. */
1502 	    !(vw->vw_flags & VWF_MOUSE_HIDE) && /* Cursor displayed.      */
1503 	    !kdb_active && !KERNEL_PANICKED()) {  /* DDB inactive.          */
1504 		vd->vd_mshown = 1;
1505 	} else {
1506 		vd->vd_mshown = 0;
1507 	}
1508 
1509 	/*
1510 	 * If the cursor changed display state or moved, we must mark
1511 	 * the old position as dirty, so that it's erased.
1512 	 */
1513 	if (cursor_was_shown != vd->vd_mshown ||
1514 	    (vd->vd_mshown && cursor_moved))
1515 		vt_mark_mouse_position_as_dirty(vd, true);
1516 
1517 	/*
1518          * Save position of the mouse cursor. It's used by backends to
1519          * know where to draw the cursor and during the next refresh to
1520          * erase the previous position.
1521 	 */
1522 	vd->vd_mx_drawn = vd->vd_mx;
1523 	vd->vd_my_drawn = vd->vd_my;
1524 
1525 	/*
1526 	 * If the cursor is displayed and has moved since last refresh,
1527 	 * mark the new position as dirty.
1528 	 */
1529 	if (vd->vd_mshown && cursor_moved)
1530 		vt_mark_mouse_position_as_dirty(vd, true);
1531 #endif
1532 
1533 	vtbuf_undirty(&vw->vw_buf, &tarea);
1534 
1535 	/* Force a full redraw when the screen contents might be invalid. */
1536 	needs_refresh = false;
1537 	if (vd->vd_flags & (VDF_INVALID | VDF_SUSPENDED)) {
1538 		needs_refresh = true;
1539 		vd->vd_flags &= ~VDF_INVALID;
1540 
1541 		vt_termrect(vd, vf, &tarea);
1542 		if (vd->vd_driver->vd_invalidate_text)
1543 			vd->vd_driver->vd_invalidate_text(vd, &tarea);
1544 	}
1545 
1546 	if (tarea.tr_begin.tp_col < tarea.tr_end.tp_col) {
1547 		if (vd->vd_driver->vd_bitblt_after_vtbuf_unlock) {
1548 			/*
1549 			 * When `vd_bitblt_after_vtbuf_unlock` is set to true,
1550 			 * we first remember the characters to redraw. They are
1551 			 * already copied to the `vd_drawn` arrays.
1552 			 *
1553 			 * We then unlock vt_buf and proceed with the actual
1554 			 * drawing using the backend driver.
1555 			 */
1556 			vt_flush_to_buffer(vd, vw, &tarea);
1557 			vtbuf_unlock(&vw->vw_buf);
1558 			vt_bitblt_buffer(vd, vw, &tarea);
1559 
1560 			if (needs_refresh)
1561 				vt_draw_decorations(vd);
1562 
1563 			/*
1564 			 * We can reset `inside_vt_flush` after unlocking vtbuf
1565 			 * here because we also hold vt_flush_lock in this code
1566 			 * path.
1567 			 */
1568 			inside_vt_flush = false;
1569 		} else {
1570 			/*
1571 			 * When `vd_bitblt_after_vtbuf_unlock` is false, we use
1572 			 * the backend's `vd_bitblt_text` callback directly.
1573 			 */
1574 			vd->vd_driver->vd_bitblt_text(vd, vw, &tarea);
1575 
1576 			if (needs_refresh)
1577 				vt_draw_decorations(vd);
1578 
1579 			inside_vt_flush = false;
1580 			vtbuf_unlock(&vw->vw_buf);
1581 		}
1582 
1583 		VT_FLUSH_UNLOCK(vd);
1584 
1585 		return (1);
1586 	}
1587 
1588 	inside_vt_flush = false;
1589 	vtbuf_unlock(&vw->vw_buf);
1590 
1591 	VT_FLUSH_UNLOCK(vd);
1592 
1593 	return (0);
1594 }
1595 
1596 static void
1597 vt_timer(void *arg)
1598 {
1599 	struct vt_device *vd;
1600 	int changed;
1601 
1602 	vd = arg;
1603 	/* Update screen if required. */
1604 	changed = vt_flush(vd);
1605 
1606 	/* Schedule for next update. */
1607 	if (changed)
1608 		vt_schedule_flush(vd, 0);
1609 	else
1610 		vd->vd_timer_armed = 0;
1611 }
1612 
1613 static void
1614 vtterm_pre_input(struct terminal *tm)
1615 {
1616 	struct vt_window *vw = tm->tm_softc;
1617 
1618 	if (inside_vt_flush && KERNEL_PANICKED())
1619 		return;
1620 
1621 	vtbuf_lock(&vw->vw_buf);
1622 }
1623 
1624 static void
1625 vtterm_post_input(struct terminal *tm)
1626 {
1627 	struct vt_window *vw = tm->tm_softc;
1628 
1629 	if (inside_vt_flush && KERNEL_PANICKED())
1630 		return;
1631 
1632 	vtbuf_unlock(&vw->vw_buf);
1633 	vt_resume_flush_timer(vw, 0);
1634 }
1635 
1636 static void
1637 vtterm_done(struct terminal *tm)
1638 {
1639 	struct vt_window *vw = tm->tm_softc;
1640 	struct vt_device *vd = vw->vw_device;
1641 
1642 	if (kdb_active || KERNEL_PANICKED()) {
1643 		/* Switch to the debugger. */
1644 		if (vd->vd_curwindow != vw) {
1645 			vd->vd_curwindow = vw;
1646 			vd->vd_flags |= VDF_INVALID;
1647 			if (vd->vd_driver->vd_postswitch)
1648 				vd->vd_driver->vd_postswitch(vd);
1649 		}
1650 		vd->vd_flags &= ~VDF_SPLASH;
1651 		vt_flush(vd);
1652 	} else if (!(vd->vd_flags & VDF_ASYNC)) {
1653 		vt_flush(vd);
1654 	}
1655 }
1656 
1657 #ifdef DEV_SPLASH
1658 static void
1659 vtterm_splash(struct vt_device *vd)
1660 {
1661 	caddr_t kmdp;
1662 	struct splash_info *si;
1663 	uintptr_t image;
1664 	vt_axis_t top, left;
1665 
1666 	kmdp = preload_search_by_type("elf kernel");
1667 	if (kmdp == NULL)
1668 		kmdp = preload_search_by_type("elf64 kernel");
1669 	si = MD_FETCH(kmdp, MODINFOMD_SPLASH, struct splash_info *);
1670 	if (!(vd->vd_flags & VDF_TEXTMODE) && (boothowto & RB_MUTE)) {
1671 		if (si == NULL) {
1672 			top = (vd->vd_height - vt_logo_height) / 2;
1673 			left = (vd->vd_width - vt_logo_width) / 2;
1674 			vd->vd_driver->vd_bitblt_bmp(vd, vd->vd_curwindow,
1675 			    vt_logo_image, NULL, vt_logo_width, vt_logo_height,
1676 			    left, top, TC_WHITE, TC_BLACK);
1677 		} else {
1678 			if (si->si_depth != 4)
1679 				return;
1680 			printf("SPLASH: width: %d height: %d depth: %d\n", si->si_width, si->si_height, si->si_depth);
1681 			image = (uintptr_t)si + sizeof(struct splash_info);
1682 			image = roundup2(image, 8);
1683 			top = (vd->vd_height - si->si_height) / 2;
1684 			left = (vd->vd_width - si->si_width) / 2;
1685 			vd->vd_driver->vd_bitblt_argb(vd, vd->vd_curwindow,
1686 			    (unsigned char *)image, si->si_width, si->si_height,
1687 			    left, top);
1688 		}
1689 		vd->vd_flags |= VDF_SPLASH;
1690 	}
1691 }
1692 #endif
1693 
1694 static struct vt_font *
1695 parse_font_info_static(struct font_info *fi)
1696 {
1697 	struct vt_font *vfp;
1698 	uintptr_t ptr;
1699 	uint32_t checksum;
1700 
1701 	if (fi == NULL)
1702 		return (NULL);
1703 
1704 	ptr = (uintptr_t)fi;
1705 	/*
1706 	 * Compute and verify checksum. The total sum of all the fields
1707 	 * must be 0.
1708 	 */
1709 	checksum = fi->fi_width;
1710 	checksum += fi->fi_height;
1711 	checksum += fi->fi_bitmap_size;
1712 	for (unsigned i = 0; i < VFNT_MAPS; i++)
1713 		checksum += fi->fi_map_count[i];
1714 
1715 	if (checksum + fi->fi_checksum != 0)
1716 		return (NULL);
1717 
1718 	ptr += sizeof(struct font_info);
1719 	ptr = roundup2(ptr, 8);
1720 
1721 	vfp = &vt_font_loader;
1722 	vfp->vf_height = fi->fi_height;
1723 	vfp->vf_width = fi->fi_width;
1724 	/* This is default font, set refcount 1 to disable removal. */
1725 	vfp->vf_refcount = 1;
1726 	for (unsigned i = 0; i < VFNT_MAPS; i++) {
1727 		if (fi->fi_map_count[i] == 0)
1728 			continue;
1729 		vfp->vf_map_count[i] = fi->fi_map_count[i];
1730 		vfp->vf_map[i] = (vfnt_map_t *)ptr;
1731 		ptr += (fi->fi_map_count[i] * sizeof(vfnt_map_t));
1732 		ptr = roundup2(ptr, 8);
1733 	}
1734 	vfp->vf_bytes = (uint8_t *)ptr;
1735 	return (vfp);
1736 }
1737 
1738 /*
1739  * Set up default font with allocated data structures.
1740  * However, we can not set refcount here, because it is already set and
1741  * incremented in vtterm_cnprobe() to avoid being released by font load from
1742  * userland.
1743  */
1744 static struct vt_font *
1745 parse_font_info(struct font_info *fi)
1746 {
1747 	struct vt_font *vfp;
1748 	uintptr_t ptr;
1749 	uint32_t checksum;
1750 	size_t size;
1751 
1752 	if (fi == NULL)
1753 		return (NULL);
1754 
1755 	ptr = (uintptr_t)fi;
1756 	/*
1757 	 * Compute and verify checksum. The total sum of all the fields
1758 	 * must be 0.
1759 	 */
1760 	checksum = fi->fi_width;
1761 	checksum += fi->fi_height;
1762 	checksum += fi->fi_bitmap_size;
1763 	for (unsigned i = 0; i < VFNT_MAPS; i++)
1764 		checksum += fi->fi_map_count[i];
1765 
1766 	if (checksum + fi->fi_checksum != 0)
1767 		return (NULL);
1768 
1769 	ptr += sizeof(struct font_info);
1770 	ptr = roundup2(ptr, 8);
1771 
1772 	vfp = &vt_font_loader;
1773 	vfp->vf_height = fi->fi_height;
1774 	vfp->vf_width = fi->fi_width;
1775 	for (unsigned i = 0; i < VFNT_MAPS; i++) {
1776 		if (fi->fi_map_count[i] == 0)
1777 			continue;
1778 		vfp->vf_map_count[i] = fi->fi_map_count[i];
1779 		size = fi->fi_map_count[i] * sizeof(vfnt_map_t);
1780 		vfp->vf_map[i] = malloc(size, M_VT, M_WAITOK | M_ZERO);
1781 		bcopy((vfnt_map_t *)ptr, vfp->vf_map[i], size);
1782 		ptr += size;
1783 		ptr = roundup2(ptr, 8);
1784 	}
1785 	vfp->vf_bytes = malloc(fi->fi_bitmap_size, M_VT, M_WAITOK | M_ZERO);
1786 	bcopy((uint8_t *)ptr, vfp->vf_bytes, fi->fi_bitmap_size);
1787 	return (vfp);
1788 }
1789 
1790 static void
1791 vt_init_font(void *arg)
1792 {
1793 	caddr_t kmdp;
1794 	struct font_info *fi;
1795 	struct vt_font *font;
1796 
1797 	kmdp = preload_search_by_type("elf kernel");
1798 	if (kmdp == NULL)
1799 		kmdp = preload_search_by_type("elf64 kernel");
1800 	fi = MD_FETCH(kmdp, MODINFOMD_FONT, struct font_info *);
1801 
1802 	font = parse_font_info(fi);
1803 	if (font != NULL)
1804 		vt_font_assigned = font;
1805 }
1806 
1807 SYSINIT(vt_init_font, SI_SUB_KMEM, SI_ORDER_ANY, vt_init_font, &vt_consdev);
1808 
1809 static void
1810 vt_init_font_static(void)
1811 {
1812 	caddr_t kmdp;
1813 	struct font_info *fi;
1814 	struct vt_font *font;
1815 
1816 	kmdp = preload_search_by_type("elf kernel");
1817 	if (kmdp == NULL)
1818 		kmdp = preload_search_by_type("elf64 kernel");
1819 	fi = MD_FETCH(kmdp, MODINFOMD_FONT, struct font_info *);
1820 
1821 	font = parse_font_info_static(fi);
1822 	if (font != NULL)
1823 		vt_font_assigned = font;
1824 }
1825 
1826 static void
1827 vtterm_cnprobe(struct terminal *tm, struct consdev *cp)
1828 {
1829 	struct vt_driver *vtd, **vtdlist, *vtdbest = NULL;
1830 	struct vt_window *vw = tm->tm_softc;
1831 	struct vt_device *vd = vw->vw_device;
1832 	struct winsize wsz;
1833 	const term_attr_t *a;
1834 
1835 	if (!vty_enabled(VTY_VT))
1836 		return;
1837 
1838 	if (vd->vd_flags & VDF_INITIALIZED)
1839 		/* Initialization already done. */
1840 		return;
1841 
1842 	SET_FOREACH(vtdlist, vt_drv_set) {
1843 		vtd = *vtdlist;
1844 		if (vtd->vd_probe == NULL)
1845 			continue;
1846 		if (vtd->vd_probe(vd) == CN_DEAD)
1847 			continue;
1848 		if ((vtdbest == NULL) ||
1849 		    (vtd->vd_priority > vtdbest->vd_priority))
1850 			vtdbest = vtd;
1851 	}
1852 	if (vtdbest == NULL) {
1853 		cp->cn_pri = CN_DEAD;
1854 		vd->vd_flags |= VDF_DEAD;
1855 	} else {
1856 		vd->vd_driver = vtdbest;
1857 		cp->cn_pri = vd->vd_driver->vd_init(vd);
1858 	}
1859 
1860 	/* Check if driver's vt_init return CN_DEAD. */
1861 	if (cp->cn_pri == CN_DEAD) {
1862 		vd->vd_flags |= VDF_DEAD;
1863 	}
1864 
1865 	/* Initialize any early-boot keyboard drivers */
1866 	kbd_configure(KB_CONF_PROBE_ONLY);
1867 
1868 	vd->vd_unit = atomic_fetchadd_int(&vt_unit, 1);
1869 	vd->vd_windows[VT_CONSWINDOW] = vw;
1870 	sprintf(cp->cn_name, "ttyv%r", VT_UNIT(vw));
1871 
1872 	vt_init_font_static();
1873 
1874 	/* Attach default font if not in TEXTMODE. */
1875 	if ((vd->vd_flags & VDF_TEXTMODE) == 0) {
1876 		vw->vw_font = vtfont_ref(vt_font_assigned);
1877 		vt_compute_drawable_area(vw);
1878 	}
1879 
1880 	/*
1881 	 * The original screen size was faked (_VTDEFW x _VTDEFH). Now
1882 	 * that we have the real viewable size, fix it in the static
1883 	 * buffer.
1884 	 */
1885 	if (vd->vd_width != 0 && vd->vd_height != 0)
1886 		vt_termsize(vd, vw->vw_font, &vw->vw_buf.vb_scr_size);
1887 
1888 	/* We need to access terminal attributes from vtbuf */
1889 	vw->vw_buf.vb_terminal = tm;
1890 	vtbuf_init_early(&vw->vw_buf);
1891 	vt_winsize(vd, vw->vw_font, &wsz);
1892 	a = teken_get_curattr(&tm->tm_emulator);
1893 	terminal_set_winsize_blank(tm, &wsz, 1, a);
1894 
1895 	if (vtdbest != NULL) {
1896 #ifdef DEV_SPLASH
1897 		if (!vt_splash_cpu)
1898 			vtterm_splash(vd);
1899 #endif
1900 		vd->vd_flags |= VDF_INITIALIZED;
1901 	}
1902 }
1903 
1904 static int
1905 vtterm_cngetc(struct terminal *tm)
1906 {
1907 	struct vt_window *vw = tm->tm_softc;
1908 	struct vt_device *vd = vw->vw_device;
1909 	keyboard_t *kbd;
1910 	u_int c;
1911 
1912 	if (vw->vw_kbdsq && *vw->vw_kbdsq)
1913 		return (*vw->vw_kbdsq++);
1914 
1915 	/* Make sure the splash screen is not there. */
1916 	if (vd->vd_flags & VDF_SPLASH) {
1917 		/* Remove splash */
1918 		vd->vd_flags &= ~VDF_SPLASH;
1919 		/* Mark screen as invalid to force update */
1920 		vd->vd_flags |= VDF_INVALID;
1921 		vt_flush(vd);
1922 	}
1923 
1924 	/* Stripped down keyboard handler. */
1925 	if ((kbd = vd->vd_keyboard) == NULL)
1926 		return (-1);
1927 
1928 	/* Force keyboard input mode to K_XLATE */
1929 	vw->vw_kbdmode = K_XLATE;
1930 	vt_update_kbd_mode(vw, kbd);
1931 
1932 	/* Switch the keyboard to polling to make it work here. */
1933 	kbdd_poll(kbd, TRUE);
1934 	c = kbdd_read_char(kbd, 0);
1935 	kbdd_poll(kbd, FALSE);
1936 	if (c & RELKEY)
1937 		return (-1);
1938 
1939 	if (vw->vw_flags & VWF_SCROLL) {
1940 		vt_scrollmode_kbdevent(vw, c, 1/* Console mode */);
1941 		vt_flush(vd);
1942 		return (-1);
1943 	}
1944 
1945 	/* Stripped down handling of vt_kbdevent(), without locking, etc. */
1946 	if (c & SPCLKEY) {
1947 		switch (c) {
1948 		case SPCLKEY | SLK:
1949 			vt_save_kbd_state(vw, kbd);
1950 			if (vw->vw_kbdstate & SLKED) {
1951 				/* Turn scrolling on. */
1952 				vw->vw_flags |= VWF_SCROLL;
1953 				VTBUF_SLCK_ENABLE(&vw->vw_buf);
1954 			} else {
1955 				/* Turn scrolling off. */
1956 				vt_scroll(vw, 0, VHS_END);
1957 				vw->vw_flags &= ~VWF_SCROLL;
1958 				VTBUF_SLCK_DISABLE(&vw->vw_buf);
1959 			}
1960 			break;
1961 		/* XXX: KDB can handle history. */
1962 		case SPCLKEY | FKEY | F(50): /* Arrow up. */
1963 			vw->vw_kbdsq = "\x1b[A";
1964 			break;
1965 		case SPCLKEY | FKEY | F(58): /* Arrow down. */
1966 			vw->vw_kbdsq = "\x1b[B";
1967 			break;
1968 		case SPCLKEY | FKEY | F(55): /* Arrow right. */
1969 			vw->vw_kbdsq = "\x1b[C";
1970 			break;
1971 		case SPCLKEY | FKEY | F(53): /* Arrow left. */
1972 			vw->vw_kbdsq = "\x1b[D";
1973 			break;
1974 		}
1975 
1976 		/* Force refresh to make scrollback work. */
1977 		vt_flush(vd);
1978 	} else if (KEYFLAGS(c) == 0) {
1979 		return (KEYCHAR(c));
1980 	}
1981 
1982 	if (vw->vw_kbdsq && *vw->vw_kbdsq)
1983 		return (*vw->vw_kbdsq++);
1984 
1985 	return (-1);
1986 }
1987 
1988 /*
1989  * These two do most of what we want to do in vtterm_cnungrab, but without
1990  * actually switching windows.  This is necessary for, e.g.,
1991  * vt_allocate_keyboard() to get the current keyboard into the state it needs to
1992  * be in without damaging the device's window state.
1993  *
1994  * Both return the current grab count, though it's only used in vtterm_cnungrab.
1995  */
1996 static int
1997 vtterm_cngrab_noswitch(struct vt_device *vd, struct vt_window *vw)
1998 {
1999 	keyboard_t *kbd;
2000 
2001 	if (vw->vw_grabbed++ > 0)
2002 		return (vw->vw_grabbed);
2003 
2004 	if ((kbd = vd->vd_keyboard) == NULL)
2005 		return (1);
2006 
2007 	/*
2008 	 * Make sure the keyboard is accessible even when the kbd device
2009 	 * driver is disabled.
2010 	 */
2011 	kbdd_enable(kbd);
2012 
2013 	/* We shall always use the keyboard in the XLATE mode here. */
2014 	vw->vw_prev_kbdmode = vw->vw_kbdmode;
2015 	vw->vw_kbdmode = K_XLATE;
2016 	vt_update_kbd_mode(vw, kbd);
2017 
2018 	kbdd_poll(kbd, TRUE);
2019 	return (1);
2020 }
2021 
2022 static int
2023 vtterm_cnungrab_noswitch(struct vt_device *vd, struct vt_window *vw)
2024 {
2025 	keyboard_t *kbd;
2026 
2027 	if (--vw->vw_grabbed > 0)
2028 		return (vw->vw_grabbed);
2029 
2030 	if ((kbd = vd->vd_keyboard) == NULL)
2031 		return (0);
2032 
2033 	kbdd_poll(kbd, FALSE);
2034 
2035 	vw->vw_kbdmode = vw->vw_prev_kbdmode;
2036 	vt_update_kbd_mode(vw, kbd);
2037 	kbdd_disable(kbd);
2038 	return (0);
2039 }
2040 
2041 static void
2042 vtterm_cngrab(struct terminal *tm)
2043 {
2044 	struct vt_device *vd;
2045 	struct vt_window *vw;
2046 
2047 	vw = tm->tm_softc;
2048 	vd = vw->vw_device;
2049 
2050 	/* To be restored after we ungrab. */
2051 	if (vd->vd_grabwindow == NULL)
2052 		vd->vd_grabwindow = vd->vd_curwindow;
2053 
2054 	if (!cold)
2055 		vt_window_switch(vw);
2056 
2057 	vtterm_cngrab_noswitch(vd, vw);
2058 }
2059 
2060 static void
2061 vtterm_cnungrab(struct terminal *tm)
2062 {
2063 	struct vt_device *vd;
2064 	struct vt_window *vw, *grabwindow;
2065 
2066 	vw = tm->tm_softc;
2067 	vd = vw->vw_device;
2068 
2069 	MPASS(vd->vd_grabwindow != NULL);
2070 	if (vtterm_cnungrab_noswitch(vd, vw) != 0)
2071 		return;
2072 
2073 	/*
2074 	 * We set `vd_grabwindow` to NULL before calling vt_window_switch()
2075 	 * because it allows the underlying vt(4) backend to distinguish a
2076 	 * "grab" from an "ungrab" of the console.
2077 	 *
2078 	 * This is used by `vt_drmfb` in drm-kmod to call either
2079 	 * fb_debug_enter() or fb_debug_leave() appropriately.
2080 	 */
2081 	grabwindow = vd->vd_grabwindow;
2082 	vd->vd_grabwindow = NULL;
2083 
2084 	if (!cold)
2085 		vt_window_switch(grabwindow);
2086 }
2087 
2088 static void
2089 vtterm_opened(struct terminal *tm, int opened)
2090 {
2091 	struct vt_window *vw = tm->tm_softc;
2092 	struct vt_device *vd = vw->vw_device;
2093 
2094 	VT_LOCK(vd);
2095 	vd->vd_flags &= ~VDF_SPLASH;
2096 	if (opened)
2097 		vw->vw_flags |= VWF_OPENED;
2098 	else {
2099 		vw->vw_flags &= ~VWF_OPENED;
2100 		/* TODO: finish ACQ/REL */
2101 	}
2102 	VT_UNLOCK(vd);
2103 }
2104 
2105 static int
2106 vt_change_font(struct vt_window *vw, struct vt_font *vf)
2107 {
2108 	struct vt_device *vd = vw->vw_device;
2109 	struct terminal *tm = vw->vw_terminal;
2110 	term_pos_t size;
2111 	struct winsize wsz;
2112 
2113 	/*
2114 	 * Changing fonts.
2115 	 *
2116 	 * Changing fonts is a little tricky.  We must prevent
2117 	 * simultaneous access to the device, so we must stop
2118 	 * the display timer and the terminal from accessing.
2119 	 * We need to switch fonts and grow our screen buffer.
2120 	 *
2121 	 * XXX: Right now the code uses terminal_mute() to
2122 	 * prevent data from reaching the console driver while
2123 	 * resizing the screen buffer.  This isn't elegant...
2124 	 */
2125 
2126 	VT_LOCK(vd);
2127 	if (vw->vw_flags & VWF_BUSY) {
2128 		/* Another process is changing the font. */
2129 		VT_UNLOCK(vd);
2130 		return (EBUSY);
2131 	}
2132 	vw->vw_flags |= VWF_BUSY;
2133 	VT_UNLOCK(vd);
2134 
2135 	vt_termsize(vd, vf, &size);
2136 	vt_winsize(vd, vf, &wsz);
2137 
2138 	/* Grow the screen buffer and terminal. */
2139 	terminal_mute(tm, 1);
2140 	vtbuf_grow(&vw->vw_buf, &size, vw->vw_buf.vb_history_size);
2141 	terminal_set_winsize_blank(tm, &wsz, 0, NULL);
2142 	terminal_set_cursor(tm, &vw->vw_buf.vb_cursor);
2143 	terminal_mute(tm, 0);
2144 
2145 	/* Actually apply the font to the current window. */
2146 	VT_LOCK(vd);
2147 	if (vw->vw_font != vf && vw->vw_font != NULL && vf != NULL) {
2148 		/*
2149 		 * In case vt_change_font called to update size we don't need
2150 		 * to update font link.
2151 		 */
2152 		vtfont_unref(vw->vw_font);
2153 		vw->vw_font = vtfont_ref(vf);
2154 	}
2155 
2156 	/*
2157 	 * Compute the drawable area and move the mouse cursor inside
2158 	 * it, in case the new area is smaller than the previous one.
2159 	 */
2160 	vt_compute_drawable_area(vw);
2161 	vd->vd_mx = min(vd->vd_mx,
2162 	    vw->vw_draw_area.tr_end.tp_col -
2163 	    vw->vw_draw_area.tr_begin.tp_col - 1);
2164 	vd->vd_my = min(vd->vd_my,
2165 	    vw->vw_draw_area.tr_end.tp_row -
2166 	    vw->vw_draw_area.tr_begin.tp_row - 1);
2167 
2168 	/* Force a full redraw the next timer tick. */
2169 	if (vd->vd_curwindow == vw) {
2170 		vd->vd_flags |= VDF_INVALID;
2171 		vt_resume_flush_timer(vw, 0);
2172 	}
2173 	vw->vw_flags &= ~VWF_BUSY;
2174 	VT_UNLOCK(vd);
2175 	return (0);
2176 }
2177 
2178 static int
2179 vt_proc_alive(struct vt_window *vw)
2180 {
2181 	struct proc *p;
2182 
2183 	if (vw->vw_smode.mode != VT_PROCESS)
2184 		return (FALSE);
2185 
2186 	if (vw->vw_proc) {
2187 		if ((p = pfind(vw->vw_pid)) != NULL)
2188 			PROC_UNLOCK(p);
2189 		if (vw->vw_proc == p)
2190 			return (TRUE);
2191 		vw->vw_proc = NULL;
2192 		vw->vw_smode.mode = VT_AUTO;
2193 		DPRINTF(1, "vt controlling process %d died\n", vw->vw_pid);
2194 		vw->vw_pid = 0;
2195 	}
2196 	return (FALSE);
2197 }
2198 
2199 static int
2200 signal_vt_rel(struct vt_window *vw)
2201 {
2202 
2203 	if (vw->vw_smode.mode != VT_PROCESS)
2204 		return (FALSE);
2205 	if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
2206 		vw->vw_proc = NULL;
2207 		vw->vw_pid = 0;
2208 		return (TRUE);
2209 	}
2210 	vw->vw_flags |= VWF_SWWAIT_REL;
2211 	PROC_LOCK(vw->vw_proc);
2212 	kern_psignal(vw->vw_proc, vw->vw_smode.relsig);
2213 	PROC_UNLOCK(vw->vw_proc);
2214 	DPRINTF(1, "sending relsig to %d\n", vw->vw_pid);
2215 	return (TRUE);
2216 }
2217 
2218 static int
2219 signal_vt_acq(struct vt_window *vw)
2220 {
2221 
2222 	if (vw->vw_smode.mode != VT_PROCESS)
2223 		return (FALSE);
2224 	if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
2225 		cnavailable(vw->vw_terminal->consdev, FALSE);
2226 	if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
2227 		vw->vw_proc = NULL;
2228 		vw->vw_pid = 0;
2229 		return (TRUE);
2230 	}
2231 	vw->vw_flags |= VWF_SWWAIT_ACQ;
2232 	PROC_LOCK(vw->vw_proc);
2233 	kern_psignal(vw->vw_proc, vw->vw_smode.acqsig);
2234 	PROC_UNLOCK(vw->vw_proc);
2235 	DPRINTF(1, "sending acqsig to %d\n", vw->vw_pid);
2236 	return (TRUE);
2237 }
2238 
2239 static int
2240 finish_vt_rel(struct vt_window *vw, int release, int *s)
2241 {
2242 
2243 	if (vw->vw_flags & VWF_SWWAIT_REL) {
2244 		vw->vw_flags &= ~VWF_SWWAIT_REL;
2245 		if (release) {
2246 			taskqueue_drain_timeout(taskqueue_thread, &vw->vw_timeout_task_dead);
2247 			(void)vt_late_window_switch(vw->vw_switch_to);
2248 		}
2249 		return (0);
2250 	}
2251 	return (EINVAL);
2252 }
2253 
2254 static int
2255 finish_vt_acq(struct vt_window *vw)
2256 {
2257 
2258 	if (vw->vw_flags & VWF_SWWAIT_ACQ) {
2259 		vw->vw_flags &= ~VWF_SWWAIT_ACQ;
2260 		return (0);
2261 	}
2262 	return (EINVAL);
2263 }
2264 
2265 #ifndef SC_NO_CUTPASTE
2266 static void
2267 vt_mouse_terminput_button(struct vt_device *vd, int button)
2268 {
2269 	struct vt_window *vw;
2270 	struct vt_font *vf;
2271 	char mouseb[6] = "\x1B[M";
2272 	int i, x, y;
2273 
2274 	vw = vd->vd_curwindow;
2275 	vf = vw->vw_font;
2276 
2277 	/* Translate to char position. */
2278 	x = vd->vd_mx / vf->vf_width;
2279 	y = vd->vd_my / vf->vf_height;
2280 	/* Avoid overflow. */
2281 	x = MIN(x, 255 - '!');
2282 	y = MIN(y, 255 - '!');
2283 
2284 	mouseb[3] = ' ' + button;
2285 	mouseb[4] = '!' + x;
2286 	mouseb[5] = '!' + y;
2287 
2288 	for (i = 0; i < sizeof(mouseb); i++)
2289 		terminal_input_char(vw->vw_terminal, mouseb[i]);
2290 }
2291 
2292 static void
2293 vt_mouse_terminput(struct vt_device *vd, int type, int x, int y, int event,
2294     int cnt)
2295 {
2296 
2297 	switch (type) {
2298 	case MOUSE_BUTTON_EVENT:
2299 		if (cnt > 0) {
2300 			/* Mouse button pressed. */
2301 			if (event & MOUSE_BUTTON1DOWN)
2302 				vt_mouse_terminput_button(vd, 0);
2303 			if (event & MOUSE_BUTTON2DOWN)
2304 				vt_mouse_terminput_button(vd, 1);
2305 			if (event & MOUSE_BUTTON3DOWN)
2306 				vt_mouse_terminput_button(vd, 2);
2307 		} else {
2308 			/* Mouse button released. */
2309 			vt_mouse_terminput_button(vd, 3);
2310 		}
2311 		break;
2312 #ifdef notyet
2313 	case MOUSE_MOTION_EVENT:
2314 		if (mouse->u.data.z < 0) {
2315 			/* Scroll up. */
2316 			sc_mouse_input_button(vd, 64);
2317 		} else if (mouse->u.data.z > 0) {
2318 			/* Scroll down. */
2319 			sc_mouse_input_button(vd, 65);
2320 		}
2321 		break;
2322 #endif
2323 	}
2324 }
2325 
2326 static void
2327 vt_mouse_paste(void)
2328 {
2329 	term_char_t *buf;
2330 	int i, len;
2331 
2332 	len = VD_PASTEBUFLEN(main_vd);
2333 	buf = VD_PASTEBUF(main_vd);
2334 	len /= sizeof(term_char_t);
2335 	for (i = 0; i < len; i++) {
2336 		if (TCHAR_CHARACTER(buf[i]) == '\0')
2337 			continue;
2338 		terminal_input_char(main_vd->vd_curwindow->vw_terminal,
2339 		    buf[i]);
2340 	}
2341 }
2342 
2343 void
2344 vt_mouse_event(int type, int x, int y, int event, int cnt, int mlevel)
2345 {
2346 	struct vt_device *vd;
2347 	struct vt_window *vw;
2348 	struct vt_font *vf;
2349 	term_pos_t size;
2350 	int len, mark;
2351 
2352 	vd = main_vd;
2353 	vw = vd->vd_curwindow;
2354 	vf = vw->vw_font;
2355 
2356 	if (vw->vw_flags & (VWF_MOUSE_HIDE | VWF_GRAPHICS))
2357 		/*
2358 		 * Either the mouse is disabled, or the window is in
2359 		 * "graphics mode". The graphics mode is usually set by
2360 		 * an X server, using the KDSETMODE ioctl.
2361 		 */
2362 		return;
2363 
2364 	if (vf == NULL)	/* Text mode. */
2365 		return;
2366 
2367 	/*
2368 	 * TODO: add flag about pointer position changed, to not redraw chars
2369 	 * under mouse pointer when nothing changed.
2370 	 */
2371 
2372 	if (vw->vw_mouse_level > 0)
2373 		vt_mouse_terminput(vd, type, x, y, event, cnt);
2374 
2375 	switch (type) {
2376 	case MOUSE_ACTION:
2377 	case MOUSE_MOTION_EVENT:
2378 		/* Movement */
2379 		x += vd->vd_mx;
2380 		y += vd->vd_my;
2381 
2382 		vt_termsize(vd, vf, &size);
2383 
2384 		/* Apply limits. */
2385 		x = MAX(x, 0);
2386 		y = MAX(y, 0);
2387 		x = MIN(x, (size.tp_col * vf->vf_width) - 1);
2388 		y = MIN(y, (size.tp_row * vf->vf_height) - 1);
2389 
2390 		vd->vd_mx = x;
2391 		vd->vd_my = y;
2392 		if (vd->vd_mstate & (MOUSE_BUTTON1DOWN | VT_MOUSE_EXTENDBUTTON))
2393 			vtbuf_set_mark(&vw->vw_buf, VTB_MARK_MOVE,
2394 			    vd->vd_mx / vf->vf_width,
2395 			    vd->vd_my / vf->vf_height);
2396 
2397 		vt_resume_flush_timer(vw, 0);
2398 		return; /* Done */
2399 	case MOUSE_BUTTON_EVENT:
2400 		/* Buttons */
2401 		break;
2402 	default:
2403 		return; /* Done */
2404 	}
2405 
2406 	switch (event) {
2407 	case MOUSE_BUTTON1DOWN:
2408 		switch (cnt % 4) {
2409 		case 0:	/* up */
2410 			mark = VTB_MARK_END;
2411 			break;
2412 		case 1: /* single click: start cut operation */
2413 			mark = VTB_MARK_START;
2414 			break;
2415 		case 2:	/* double click: cut a word */
2416 			mark = VTB_MARK_WORD;
2417 			break;
2418 		default:	/* triple click: cut a line */
2419 			mark = VTB_MARK_ROW;
2420 			break;
2421 		}
2422 		break;
2423 	case VT_MOUSE_PASTEBUTTON:
2424 		switch (cnt) {
2425 		case 0:	/* up */
2426 			break;
2427 		default:
2428 			vt_mouse_paste();
2429 			/* clear paste buffer selection after paste */
2430 			vtbuf_set_mark(&vw->vw_buf, VTB_MARK_START,
2431 			    vd->vd_mx / vf->vf_width,
2432 			    vd->vd_my / vf->vf_height);
2433 			break;
2434 		}
2435 		return; /* Done */
2436 	case VT_MOUSE_EXTENDBUTTON:
2437 		switch (cnt) {
2438 		case 0:	/* up */
2439 			if (!(vd->vd_mstate & MOUSE_BUTTON1DOWN))
2440 				mark = VTB_MARK_EXTEND;
2441 			else
2442 				mark = VTB_MARK_NONE;
2443 			break;
2444 		default:
2445 			mark = VTB_MARK_EXTEND;
2446 			break;
2447 		}
2448 		break;
2449 	default:
2450 		return; /* Done */
2451 	}
2452 
2453 	/* Save buttons state. */
2454 	if (cnt > 0)
2455 		vd->vd_mstate |= event;
2456 	else
2457 		vd->vd_mstate &= ~event;
2458 
2459 	if (vtbuf_set_mark(&vw->vw_buf, mark, vd->vd_mx / vf->vf_width,
2460 	    vd->vd_my / vf->vf_height) == 1) {
2461 		/*
2462 		 * We have something marked to copy, so update pointer to
2463 		 * window with selection.
2464 		 */
2465 		vt_resume_flush_timer(vw, 0);
2466 
2467 		switch (mark) {
2468 		case VTB_MARK_END:
2469 		case VTB_MARK_WORD:
2470 		case VTB_MARK_ROW:
2471 		case VTB_MARK_EXTEND:
2472 			break;
2473 		default:
2474 			/* Other types of mark do not require to copy data. */
2475 			return;
2476 		}
2477 
2478 		/* Get current selection size in bytes. */
2479 		len = vtbuf_get_marked_len(&vw->vw_buf);
2480 		if (len <= 0)
2481 			return;
2482 
2483 		/* Reallocate buffer only if old one is too small. */
2484 		if (len > VD_PASTEBUFSZ(vd)) {
2485 			VD_PASTEBUF(vd) = realloc(VD_PASTEBUF(vd), len, M_VT,
2486 			    M_WAITOK | M_ZERO);
2487 			/* Update buffer size. */
2488 			VD_PASTEBUFSZ(vd) = len;
2489 		}
2490 		/* Request copy/paste buffer data, no more than `len' */
2491 		vtbuf_extract_marked(&vw->vw_buf, VD_PASTEBUF(vd), len, mark);
2492 
2493 		VD_PASTEBUFLEN(vd) = len;
2494 
2495 		/* XXX VD_PASTEBUF(vd) have to be freed on shutdown/unload. */
2496 	}
2497 }
2498 
2499 void
2500 vt_mouse_state(int show)
2501 {
2502 	struct vt_device *vd;
2503 	struct vt_window *vw;
2504 
2505 	vd = main_vd;
2506 	vw = vd->vd_curwindow;
2507 
2508 	switch (show) {
2509 	case VT_MOUSE_HIDE:
2510 		vw->vw_flags |= VWF_MOUSE_HIDE;
2511 		break;
2512 	case VT_MOUSE_SHOW:
2513 		vw->vw_flags &= ~VWF_MOUSE_HIDE;
2514 		break;
2515 	}
2516 
2517 	/* Mark mouse position as dirty. */
2518 	vt_mark_mouse_position_as_dirty(vd, false);
2519 	vt_resume_flush_timer(vw, 0);
2520 }
2521 #endif
2522 
2523 static int
2524 vtterm_mmap(struct terminal *tm, vm_ooffset_t offset, vm_paddr_t * paddr,
2525     int nprot, vm_memattr_t *memattr)
2526 {
2527 	struct vt_window *vw = tm->tm_softc;
2528 	struct vt_device *vd = vw->vw_device;
2529 
2530 	if (vd->vd_driver->vd_fb_mmap)
2531 		return (vd->vd_driver->vd_fb_mmap(vd, offset, paddr, nprot,
2532 		    memattr));
2533 
2534 	return (ENXIO);
2535 }
2536 
2537 static int
2538 vtterm_ioctl(struct terminal *tm, u_long cmd, caddr_t data,
2539     struct thread *td)
2540 {
2541 	struct vt_window *vw = tm->tm_softc;
2542 	struct vt_device *vd = vw->vw_device;
2543 	keyboard_t *kbd;
2544 	int error, i, s;
2545 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
2546     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
2547 	int ival;
2548 
2549 	switch (cmd) {
2550 	case _IO('v', 4):
2551 		cmd = VT_RELDISP;
2552 		break;
2553 	case _IO('v', 5):
2554 		cmd = VT_ACTIVATE;
2555 		break;
2556 	case _IO('v', 6):
2557 		cmd = VT_WAITACTIVE;
2558 		break;
2559 	case _IO('K', 20):
2560 		cmd = KDSKBSTATE;
2561 		break;
2562 	case _IO('K', 67):
2563 		cmd = KDSETRAD;
2564 		break;
2565 	case _IO('K', 7):
2566 		cmd = KDSKBMODE;
2567 		break;
2568 	case _IO('K', 8):
2569 		cmd = KDMKTONE;
2570 		break;
2571 	case _IO('K', 10):
2572 		cmd = KDSETMODE;
2573 		break;
2574 	case _IO('K', 13):
2575 		cmd = KDSBORDER;
2576 		break;
2577 	case _IO('K', 63):
2578 		cmd = KIOCSOUND;
2579 		break;
2580 	case _IO('K', 66):
2581 		cmd = KDSETLED;
2582 		break;
2583 	case _IO('c', 104):
2584 		cmd = CONS_SETWINORG;
2585 		break;
2586 	case _IO('c', 110):
2587 		cmd = CONS_SETKBD;
2588 		break;
2589 	default:
2590 		goto skip_thunk;
2591 	}
2592 	ival = IOCPARM_IVAL(data);
2593 	data = (caddr_t)&ival;
2594 skip_thunk:
2595 #endif
2596 
2597 	switch (cmd) {
2598 	case KDSETRAD:		/* set keyboard repeat & delay rates (old) */
2599 		if (*(int *)data & ~0x7f)
2600 			return (EINVAL);
2601 		/* FALLTHROUGH */
2602 	case GIO_KEYMAP:
2603 	case PIO_KEYMAP:
2604 	case GIO_DEADKEYMAP:
2605 	case PIO_DEADKEYMAP:
2606 #ifdef COMPAT_FREEBSD13
2607 	case OGIO_DEADKEYMAP:
2608 	case OPIO_DEADKEYMAP:
2609 #endif /* COMPAT_FREEBSD13 */
2610 	case GETFKEY:
2611 	case SETFKEY:
2612 	case KDGKBINFO:
2613 	case KDGKBTYPE:
2614 	case KDGETREPEAT:	/* get keyboard repeat & delay rates */
2615 	case KDSETREPEAT:	/* set keyboard repeat & delay rates (new) */
2616 	case KBADDKBD:		/* add keyboard to mux */
2617 	case KBRELKBD: {	/* release keyboard from mux */
2618 		error = 0;
2619 
2620 		mtx_lock(&Giant);
2621 		if ((kbd = vd->vd_keyboard) != NULL)
2622 			error = kbdd_ioctl(kbd, cmd, data);
2623 		mtx_unlock(&Giant);
2624 		if (error == ENOIOCTL) {
2625 			if (cmd == KDGKBTYPE) {
2626 				/* always return something? XXX */
2627 				*(int *)data = 0;
2628 			} else {
2629 				return (ENODEV);
2630 			}
2631 		}
2632 		return (error);
2633 	}
2634 	case KDGKBSTATE: {	/* get keyboard state (locks) */
2635 		error = 0;
2636 
2637 		if (vw == vd->vd_curwindow) {
2638 			mtx_lock(&Giant);
2639 			if ((kbd = vd->vd_keyboard) != NULL)
2640 				error = vt_save_kbd_state(vw, kbd);
2641 			mtx_unlock(&Giant);
2642 
2643 			if (error != 0)
2644 				return (error);
2645 		}
2646 
2647 		*(int *)data = vw->vw_kbdstate & LOCK_MASK;
2648 
2649 		return (error);
2650 	}
2651 	case KDSKBSTATE: {	/* set keyboard state (locks) */
2652 		int state;
2653 
2654 		state = *(int *)data;
2655 		if (state & ~LOCK_MASK)
2656 			return (EINVAL);
2657 
2658 		vw->vw_kbdstate &= ~LOCK_MASK;
2659 		vw->vw_kbdstate |= state;
2660 
2661 		error = 0;
2662 		if (vw == vd->vd_curwindow) {
2663 			mtx_lock(&Giant);
2664 			if ((kbd = vd->vd_keyboard) != NULL)
2665 				error = vt_update_kbd_state(vw, kbd);
2666 			mtx_unlock(&Giant);
2667 		}
2668 
2669 		return (error);
2670 	}
2671 	case KDGETLED: {	/* get keyboard LED status */
2672 		error = 0;
2673 
2674 		if (vw == vd->vd_curwindow) {
2675 			mtx_lock(&Giant);
2676 			if ((kbd = vd->vd_keyboard) != NULL)
2677 				error = vt_save_kbd_leds(vw, kbd);
2678 			mtx_unlock(&Giant);
2679 
2680 			if (error != 0)
2681 				return (error);
2682 		}
2683 
2684 		*(int *)data = vw->vw_kbdstate & LED_MASK;
2685 
2686 		return (error);
2687 	}
2688 	case KDSETLED: {	/* set keyboard LED status */
2689 		int leds;
2690 
2691 		leds = *(int *)data;
2692 		if (leds & ~LED_MASK)
2693 			return (EINVAL);
2694 
2695 		vw->vw_kbdstate &= ~LED_MASK;
2696 		vw->vw_kbdstate |= leds;
2697 
2698 		error = 0;
2699 		if (vw == vd->vd_curwindow) {
2700 			mtx_lock(&Giant);
2701 			if ((kbd = vd->vd_keyboard) != NULL)
2702 				error = vt_update_kbd_leds(vw, kbd);
2703 			mtx_unlock(&Giant);
2704 		}
2705 
2706 		return (error);
2707 	}
2708 	case KDGETMODE:
2709 		*(int *)data = (vw->vw_flags & VWF_GRAPHICS) ?
2710 		    KD_GRAPHICS : KD_TEXT;
2711 		return (0);
2712 	case KDGKBMODE: {
2713 		error = 0;
2714 
2715 		if (vw == vd->vd_curwindow) {
2716 			mtx_lock(&Giant);
2717 			if ((kbd = vd->vd_keyboard) != NULL)
2718 				error = vt_save_kbd_mode(vw, kbd);
2719 			mtx_unlock(&Giant);
2720 
2721 			if (error != 0)
2722 				return (error);
2723 		}
2724 
2725 		*(int *)data = vw->vw_kbdmode;
2726 
2727 		return (error);
2728 	}
2729 	case KDSKBMODE: {
2730 		int mode;
2731 
2732 		mode = *(int *)data;
2733 		switch (mode) {
2734 		case K_XLATE:
2735 		case K_RAW:
2736 		case K_CODE:
2737 			vw->vw_kbdmode = mode;
2738 
2739 			error = 0;
2740 			if (vw == vd->vd_curwindow) {
2741 				mtx_lock(&Giant);
2742 				if ((kbd = vd->vd_keyboard) != NULL)
2743 					error = vt_update_kbd_mode(vw, kbd);
2744 				mtx_unlock(&Giant);
2745 			}
2746 
2747 			return (error);
2748 		default:
2749 			return (EINVAL);
2750 		}
2751 	}
2752 	case FBIOGTYPE:
2753 	case FBIO_GETWINORG:	/* get frame buffer window origin */
2754 	case FBIO_GETDISPSTART:	/* get display start address */
2755 	case FBIO_GETLINEWIDTH:	/* get scan line width in bytes */
2756 	case FBIO_BLANK:	/* blank display */
2757 	case FBIO_GETRGBOFFS:	/* get RGB offsets */
2758 		if (vd->vd_driver->vd_fb_ioctl)
2759 			return (vd->vd_driver->vd_fb_ioctl(vd, cmd, data, td));
2760 		break;
2761 	case CONS_BLANKTIME:
2762 		/* XXX */
2763 		return (0);
2764 	case CONS_HISTORY:
2765 		if (*(int *)data < 0)
2766 			return EINVAL;
2767 		if (*(int *)data != vw->vw_buf.vb_history_size)
2768 			vtbuf_sethistory_size(&vw->vw_buf, *(int *)data);
2769 		return (0);
2770 	case CONS_CLRHIST:
2771 		vtbuf_clearhistory(&vw->vw_buf);
2772 		/*
2773 		 * Invalidate the entire visible window; it is not guaranteed
2774 		 * that this operation will be immediately followed by a scroll
2775 		 * event, so it would otherwise be possible for prior artifacts
2776 		 * to remain visible.
2777 		 */
2778 		VT_LOCK(vd);
2779 		if (vw == vd->vd_curwindow) {
2780 			vd->vd_flags |= VDF_INVALID;
2781 			vt_resume_flush_timer(vw, 0);
2782 		}
2783 		VT_UNLOCK(vd);
2784 		return (0);
2785 	case CONS_GET:
2786 		/* XXX */
2787 		*(int *)data = M_CG640x480;
2788 		return (0);
2789 	case CONS_BELLTYPE:	/* set bell type sound */
2790 		if ((*(int *)data) & CONS_QUIET_BELL)
2791 			vd->vd_flags |= VDF_QUIET_BELL;
2792 		else
2793 			vd->vd_flags &= ~VDF_QUIET_BELL;
2794 		return (0);
2795 	case CONS_GETINFO: {
2796 		vid_info_t *vi = (vid_info_t *)data;
2797 		if (vi->size != sizeof(struct vid_info))
2798 			return (EINVAL);
2799 
2800 		if (vw == vd->vd_curwindow) {
2801 			mtx_lock(&Giant);
2802 			if ((kbd = vd->vd_keyboard) != NULL)
2803 				vt_save_kbd_state(vw, kbd);
2804 			mtx_unlock(&Giant);
2805 		}
2806 
2807 		vi->m_num = vd->vd_curwindow->vw_number + 1;
2808 		vi->mk_keylock = vw->vw_kbdstate & LOCK_MASK;
2809 		/* XXX: other fields! */
2810 		return (0);
2811 	}
2812 	case CONS_GETVERS:
2813 		*(int *)data = 0x200;
2814 		return (0);
2815 	case CONS_MODEINFO:
2816 		/* XXX */
2817 		return (0);
2818 	case CONS_MOUSECTL: {
2819 		mouse_info_t *mouse = (mouse_info_t*)data;
2820 
2821 		/*
2822 		 * All the commands except MOUSE_SHOW nd MOUSE_HIDE
2823 		 * should not be applied to individual TTYs, but only to
2824 		 * consolectl.
2825 		 */
2826 		switch (mouse->operation) {
2827 		case MOUSE_HIDE:
2828 			if (vd->vd_flags & VDF_MOUSECURSOR) {
2829 				vd->vd_flags &= ~VDF_MOUSECURSOR;
2830 #ifndef SC_NO_CUTPASTE
2831 				vt_mouse_state(VT_MOUSE_HIDE);
2832 #endif
2833 			}
2834 			return (0);
2835 		case MOUSE_SHOW:
2836 			if (!(vd->vd_flags & VDF_MOUSECURSOR)) {
2837 				vd->vd_flags |= VDF_MOUSECURSOR;
2838 				vd->vd_mx = vd->vd_width / 2;
2839 				vd->vd_my = vd->vd_height / 2;
2840 #ifndef SC_NO_CUTPASTE
2841 				vt_mouse_state(VT_MOUSE_SHOW);
2842 #endif
2843 			}
2844 			return (0);
2845 		default:
2846 			return (EINVAL);
2847 		}
2848 	}
2849 	case PIO_VFONT: {
2850 		struct vt_font *vf;
2851 
2852 		if (vd->vd_flags & VDF_TEXTMODE)
2853 			return (ENOTSUP);
2854 
2855 		error = vtfont_load((void *)data, &vf);
2856 		if (error != 0)
2857 			return (error);
2858 
2859 		error = vt_change_font(vw, vf);
2860 		vtfont_unref(vf);
2861 		return (error);
2862 	}
2863 	case PIO_VFONT_DEFAULT: {
2864 		/* Reset to default font. */
2865 		error = vt_change_font(vw, vt_font_assigned);
2866 		return (error);
2867 	}
2868 	case GIO_SCRNMAP: {
2869 		scrmap_t *sm = (scrmap_t *)data;
2870 
2871 		/* We don't have screen maps, so return a handcrafted one. */
2872 		for (i = 0; i < 256; i++)
2873 			sm->scrmap[i] = i;
2874 		return (0);
2875 	}
2876 	case KDSETMODE:
2877 		/*
2878 		 * FIXME: This implementation is incomplete compared to
2879 		 * syscons.
2880 		 */
2881 		switch (*(int *)data) {
2882 		case KD_TEXT:
2883 		case KD_TEXT1:
2884 		case KD_PIXEL:
2885 			vw->vw_flags &= ~VWF_GRAPHICS;
2886 			break;
2887 		case KD_GRAPHICS:
2888 			vw->vw_flags |= VWF_GRAPHICS;
2889 			break;
2890 		}
2891 		return (0);
2892 	case KDENABIO:		/* allow io operations */
2893 		error = priv_check(td, PRIV_IO);
2894 		if (error != 0)
2895 			return (error);
2896 		error = securelevel_gt(td->td_ucred, 0);
2897 		if (error != 0)
2898 			return (error);
2899 #if defined(__i386__)
2900 		td->td_frame->tf_eflags |= PSL_IOPL;
2901 #elif defined(__amd64__)
2902 		td->td_frame->tf_rflags |= PSL_IOPL;
2903 #endif
2904 		return (0);
2905 	case KDDISABIO:		/* disallow io operations (default) */
2906 #if defined(__i386__)
2907 		td->td_frame->tf_eflags &= ~PSL_IOPL;
2908 #elif defined(__amd64__)
2909 		td->td_frame->tf_rflags &= ~PSL_IOPL;
2910 #endif
2911 		return (0);
2912 	case KDMKTONE:		/* sound the bell */
2913 		vtterm_beep(tm, *(u_int *)data);
2914 		return (0);
2915 	case KIOCSOUND:		/* make tone (*data) hz */
2916 		/* TODO */
2917 		return (0);
2918 	case CONS_SETKBD:	/* set the new keyboard */
2919 		mtx_lock(&Giant);
2920 		error = 0;
2921 		if (vd->vd_keyboard == NULL ||
2922 		    vd->vd_keyboard->kb_index != *(int *)data) {
2923 			kbd = kbd_get_keyboard(*(int *)data);
2924 			if (kbd == NULL) {
2925 				mtx_unlock(&Giant);
2926 				return (EINVAL);
2927 			}
2928 			i = kbd_allocate(kbd->kb_name, kbd->kb_unit,
2929 			    (void *)vd, vt_kbdevent, vd);
2930 			if (i >= 0) {
2931 				if ((kbd = vd->vd_keyboard) != NULL) {
2932 					vt_save_kbd_state(vd->vd_curwindow, kbd);
2933 					kbd_release(kbd, (void *)vd);
2934 				}
2935 				kbd = vd->vd_keyboard = kbd_get_keyboard(i);
2936 
2937 				vt_update_kbd_mode(vd->vd_curwindow, kbd);
2938 				vt_update_kbd_state(vd->vd_curwindow, kbd);
2939 			} else {
2940 				error = EPERM;	/* XXX */
2941 			}
2942 		}
2943 		mtx_unlock(&Giant);
2944 		return (error);
2945 	case CONS_RELKBD:	/* release the current keyboard */
2946 		mtx_lock(&Giant);
2947 		error = 0;
2948 		if ((kbd = vd->vd_keyboard) != NULL) {
2949 			vt_save_kbd_state(vd->vd_curwindow, kbd);
2950 			error = kbd_release(kbd, (void *)vd);
2951 			if (error == 0) {
2952 				vd->vd_keyboard = NULL;
2953 			}
2954 		}
2955 		mtx_unlock(&Giant);
2956 		return (error);
2957 	case VT_ACTIVATE: {
2958 		int win;
2959 		win = *(int *)data - 1;
2960 		DPRINTF(5, "%s%d: VT_ACTIVATE ttyv%d ", SC_DRIVER_NAME,
2961 		    VT_UNIT(vw), win);
2962 		if ((win >= VT_MAXWINDOWS) || (win < 0))
2963 			return (EINVAL);
2964 		return (vt_proc_window_switch(vd->vd_windows[win]));
2965 	}
2966 	case VT_GETACTIVE:
2967 		*(int *)data = vd->vd_curwindow->vw_number + 1;
2968 		return (0);
2969 	case VT_GETINDEX:
2970 		*(int *)data = vw->vw_number + 1;
2971 		return (0);
2972 	case VT_LOCKSWITCH:
2973 		/* TODO: Check current state, switching can be in progress. */
2974 		if ((*(int *)data) == 0x01)
2975 			vw->vw_flags |= VWF_VTYLOCK;
2976 		else if ((*(int *)data) == 0x02)
2977 			vw->vw_flags &= ~VWF_VTYLOCK;
2978 		else
2979 			return (EINVAL);
2980 		return (0);
2981 	case VT_OPENQRY:
2982 		VT_LOCK(vd);
2983 		for (i = 0; i < VT_MAXWINDOWS; i++) {
2984 			vw = vd->vd_windows[i];
2985 			if (vw == NULL)
2986 				continue;
2987 			if (!(vw->vw_flags & VWF_OPENED)) {
2988 				*(int *)data = vw->vw_number + 1;
2989 				VT_UNLOCK(vd);
2990 				return (0);
2991 			}
2992 		}
2993 		VT_UNLOCK(vd);
2994 		return (EINVAL);
2995 	case VT_WAITACTIVE: {
2996 		unsigned int idx;
2997 
2998 		error = 0;
2999 
3000 		idx = *(unsigned int *)data;
3001 		if (idx > VT_MAXWINDOWS)
3002 			return (EINVAL);
3003 		if (idx > 0)
3004 			vw = vd->vd_windows[idx - 1];
3005 
3006 		VT_LOCK(vd);
3007 		while (vd->vd_curwindow != vw && error == 0)
3008 			error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
3009 		VT_UNLOCK(vd);
3010 		return (error);
3011 	}
3012 	case VT_SETMODE: {	/* set screen switcher mode */
3013 		struct vt_mode *mode;
3014 		struct proc *p1;
3015 
3016 		mode = (struct vt_mode *)data;
3017 		DPRINTF(5, "%s%d: VT_SETMODE ", SC_DRIVER_NAME, VT_UNIT(vw));
3018 		if (vw->vw_smode.mode == VT_PROCESS) {
3019 			p1 = pfind(vw->vw_pid);
3020 			if (vw->vw_proc == p1 && vw->vw_proc != td->td_proc) {
3021 				if (p1)
3022 					PROC_UNLOCK(p1);
3023 				DPRINTF(5, "error EPERM\n");
3024 				return (EPERM);
3025 			}
3026 			if (p1)
3027 				PROC_UNLOCK(p1);
3028 		}
3029 		if (mode->mode == VT_AUTO) {
3030 			vw->vw_smode.mode = VT_AUTO;
3031 			vw->vw_proc = NULL;
3032 			vw->vw_pid = 0;
3033 			DPRINTF(5, "VT_AUTO, ");
3034 			if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
3035 				cnavailable(vw->vw_terminal->consdev, TRUE);
3036 			/* were we in the middle of the vty switching process? */
3037 			if (finish_vt_rel(vw, TRUE, &s) == 0)
3038 				DPRINTF(5, "reset WAIT_REL, ");
3039 			if (finish_vt_acq(vw) == 0)
3040 				DPRINTF(5, "reset WAIT_ACQ, ");
3041 			return (0);
3042 		} else if (mode->mode == VT_PROCESS) {
3043 			if (!ISSIGVALID(mode->relsig) ||
3044 			    !ISSIGVALID(mode->acqsig) ||
3045 			    !ISSIGVALID(mode->frsig)) {
3046 				DPRINTF(5, "error EINVAL\n");
3047 				return (EINVAL);
3048 			}
3049 			DPRINTF(5, "VT_PROCESS %d, ", td->td_proc->p_pid);
3050 			bcopy(data, &vw->vw_smode, sizeof(struct vt_mode));
3051 			vw->vw_proc = td->td_proc;
3052 			vw->vw_pid = vw->vw_proc->p_pid;
3053 			if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
3054 				cnavailable(vw->vw_terminal->consdev, FALSE);
3055 		} else {
3056 			DPRINTF(5, "VT_SETMODE failed, unknown mode %d\n",
3057 			    mode->mode);
3058 			return (EINVAL);
3059 		}
3060 		DPRINTF(5, "\n");
3061 		return (0);
3062 	}
3063 	case VT_GETMODE:	/* get screen switcher mode */
3064 		bcopy(&vw->vw_smode, data, sizeof(struct vt_mode));
3065 		return (0);
3066 
3067 	case VT_RELDISP:	/* screen switcher ioctl */
3068 		/*
3069 		 * This must be the current vty which is in the VT_PROCESS
3070 		 * switching mode...
3071 		 */
3072 		if ((vw != vd->vd_curwindow) || (vw->vw_smode.mode !=
3073 		    VT_PROCESS)) {
3074 			return (EINVAL);
3075 		}
3076 		/* ...and this process is controlling it. */
3077 		if (vw->vw_proc != td->td_proc) {
3078 			return (EPERM);
3079 		}
3080 		error = EINVAL;
3081 		switch(*(int *)data) {
3082 		case VT_FALSE:	/* user refuses to release screen, abort */
3083 			if ((error = finish_vt_rel(vw, FALSE, &s)) == 0)
3084 				DPRINTF(5, "%s%d: VT_RELDISP: VT_FALSE\n",
3085 				    SC_DRIVER_NAME, VT_UNIT(vw));
3086 			break;
3087 		case VT_TRUE:	/* user has released screen, go on */
3088 			/* finish_vt_rel(..., TRUE, ...) should not be locked */
3089 			if (vw->vw_flags & VWF_SWWAIT_REL) {
3090 				if ((error = finish_vt_rel(vw, TRUE, &s)) == 0)
3091 					DPRINTF(5, "%s%d: VT_RELDISP: VT_TRUE\n",
3092 					    SC_DRIVER_NAME, VT_UNIT(vw));
3093 			} else {
3094 				error = EINVAL;
3095 			}
3096 			return (error);
3097 		case VT_ACKACQ:	/* acquire acknowledged, switch completed */
3098 			if ((error = finish_vt_acq(vw)) == 0)
3099 				DPRINTF(5, "%s%d: VT_RELDISP: VT_ACKACQ\n",
3100 				    SC_DRIVER_NAME, VT_UNIT(vw));
3101 			break;
3102 		default:
3103 			break;
3104 		}
3105 		return (error);
3106 	}
3107 
3108 	return (ENOIOCTL);
3109 }
3110 
3111 static struct vt_window *
3112 vt_allocate_window(struct vt_device *vd, unsigned int window)
3113 {
3114 	struct vt_window *vw;
3115 	struct terminal *tm;
3116 	term_pos_t size;
3117 	struct winsize wsz;
3118 
3119 	vw = malloc(sizeof *vw, M_VT, M_WAITOK|M_ZERO);
3120 	vw->vw_device = vd;
3121 	vw->vw_number = window;
3122 	vw->vw_kbdmode = K_XLATE;
3123 
3124 	if ((vd->vd_flags & VDF_TEXTMODE) == 0) {
3125 		vw->vw_font = vtfont_ref(vt_font_assigned);
3126 		vt_compute_drawable_area(vw);
3127 	}
3128 
3129 	vt_termsize(vd, vw->vw_font, &size);
3130 	vt_winsize(vd, vw->vw_font, &wsz);
3131 	tm = vw->vw_terminal = terminal_alloc(&vt_termclass, vw);
3132 	vw->vw_buf.vb_terminal = tm;	/* must be set before vtbuf_init() */
3133 	vtbuf_init(&vw->vw_buf, &size);
3134 
3135 	terminal_set_winsize(tm, &wsz);
3136 	vd->vd_windows[window] = vw;
3137 	TIMEOUT_TASK_INIT(taskqueue_thread, &vw->vw_timeout_task_dead, 0, &vt_switch_timer, vw);
3138 
3139 	return (vw);
3140 }
3141 
3142 void
3143 vt_upgrade(struct vt_device *vd)
3144 {
3145 	struct vt_window *vw;
3146 	unsigned int i;
3147 	int register_handlers;
3148 
3149 	if (!vty_enabled(VTY_VT))
3150 		return;
3151 	if (main_vd->vd_driver == NULL)
3152 		return;
3153 
3154 	for (i = 0; i < VT_MAXWINDOWS; i++) {
3155 		vw = vd->vd_windows[i];
3156 		if (vw == NULL) {
3157 			/* New window. */
3158 			vw = vt_allocate_window(vd, i);
3159 		}
3160 		if (!(vw->vw_flags & VWF_READY)) {
3161 			TIMEOUT_TASK_INIT(taskqueue_thread, &vw->vw_timeout_task_dead, 0, &vt_switch_timer, vw);
3162 			terminal_maketty(vw->vw_terminal, "v%r", VT_UNIT(vw));
3163 			vw->vw_flags |= VWF_READY;
3164 			if (vw->vw_flags & VWF_CONSOLE) {
3165 				/* For existing console window. */
3166 				EVENTHANDLER_REGISTER(shutdown_pre_sync,
3167 				    vt_window_switch, vw, SHUTDOWN_PRI_DEFAULT);
3168 			}
3169 		}
3170 	}
3171 	VT_LOCK(vd);
3172 	if (vd->vd_curwindow == NULL)
3173 		vd->vd_curwindow = vd->vd_windows[VT_CONSWINDOW];
3174 
3175 	register_handlers = 0;
3176 	if (!(vd->vd_flags & VDF_ASYNC)) {
3177 		/* Attach keyboard. */
3178 		vt_allocate_keyboard(vd);
3179 
3180 		/* Init 25 Hz timer. */
3181 		callout_init_mtx(&vd->vd_timer, &vd->vd_lock, 0);
3182 
3183 		/*
3184 		 * Start timer when everything ready.
3185 		 * Note that the operations here are purposefully ordered.
3186 		 * We need to ensure vd_timer_armed is non-zero before we set
3187 		 * the VDF_ASYNC flag. That prevents this function from
3188 		 * racing with vt_resume_flush_timer() to update the
3189 		 * callout structure.
3190 		 */
3191 		atomic_add_acq_int(&vd->vd_timer_armed, 1);
3192 		vd->vd_flags |= VDF_ASYNC;
3193 		callout_reset(&vd->vd_timer, hz / VT_TIMERFREQ, vt_timer, vd);
3194 		register_handlers = 1;
3195 	}
3196 
3197 	VT_UNLOCK(vd);
3198 
3199 	/* Refill settings with new sizes. */
3200 	vt_resize(vd);
3201 
3202 	if (register_handlers) {
3203 		/* Register suspend/resume handlers. */
3204 		EVENTHANDLER_REGISTER(power_suspend_early, vt_suspend_handler,
3205 		    vd, EVENTHANDLER_PRI_ANY);
3206 		EVENTHANDLER_REGISTER(power_resume, vt_resume_handler, vd,
3207 		    EVENTHANDLER_PRI_ANY);
3208 	}
3209 }
3210 
3211 static void
3212 vt_resize(struct vt_device *vd)
3213 {
3214 	struct vt_window *vw;
3215 	int i;
3216 
3217 	for (i = 0; i < VT_MAXWINDOWS; i++) {
3218 		vw = vd->vd_windows[i];
3219 		VT_LOCK(vd);
3220 		/* Assign default font to window, if not textmode. */
3221 		if (!(vd->vd_flags & VDF_TEXTMODE) && vw->vw_font == NULL)
3222 			vw->vw_font = vtfont_ref(vt_font_assigned);
3223 		VT_UNLOCK(vd);
3224 
3225 		/* Resize terminal windows */
3226 		while (vt_change_font(vw, vw->vw_font) == EBUSY) {
3227 			DPRINTF(100, "%s: vt_change_font() is busy, "
3228 			    "window %d\n", __func__, i);
3229 		}
3230 	}
3231 }
3232 
3233 static void
3234 vt_replace_backend(const struct vt_driver *drv, void *softc)
3235 {
3236 	struct vt_device *vd;
3237 
3238 	vd = main_vd;
3239 
3240 	if (vd->vd_flags & VDF_ASYNC) {
3241 		/* Stop vt_flush periodic task. */
3242 		VT_LOCK(vd);
3243 		vt_suspend_flush_timer(vd);
3244 		VT_UNLOCK(vd);
3245 		/*
3246 		 * Mute current terminal until we done. vt_change_font (called
3247 		 * from vt_resize) will unmute it.
3248 		 */
3249 		terminal_mute(vd->vd_curwindow->vw_terminal, 1);
3250 	}
3251 
3252 	/*
3253 	 * Reset VDF_TEXTMODE flag, driver who require that flag (vt_vga) will
3254 	 * set it.
3255 	 */
3256 	VT_LOCK(vd);
3257 	vd->vd_flags &= ~VDF_TEXTMODE;
3258 
3259 	if (drv != NULL) {
3260 		/*
3261 		 * We want to upgrade from the current driver to the
3262 		 * given driver.
3263 		 */
3264 
3265 		vd->vd_prev_driver = vd->vd_driver;
3266 		vd->vd_prev_softc = vd->vd_softc;
3267 		vd->vd_driver = drv;
3268 		vd->vd_softc = softc;
3269 
3270 		vd->vd_driver->vd_init(vd);
3271 	} else if (vd->vd_prev_driver != NULL && vd->vd_prev_softc != NULL) {
3272 		/*
3273 		 * No driver given: we want to downgrade to the previous
3274 		 * driver.
3275 		 */
3276 		const struct vt_driver *old_drv;
3277 		void *old_softc;
3278 
3279 		old_drv = vd->vd_driver;
3280 		old_softc = vd->vd_softc;
3281 
3282 		vd->vd_driver = vd->vd_prev_driver;
3283 		vd->vd_softc = vd->vd_prev_softc;
3284 		vd->vd_prev_driver = NULL;
3285 		vd->vd_prev_softc = NULL;
3286 
3287 		vd->vd_flags |= VDF_DOWNGRADE;
3288 
3289 		vd->vd_driver->vd_init(vd);
3290 
3291 		if (old_drv->vd_fini)
3292 			old_drv->vd_fini(vd, old_softc);
3293 
3294 		vd->vd_flags &= ~VDF_DOWNGRADE;
3295 	}
3296 
3297 	VT_UNLOCK(vd);
3298 
3299 	/* Update windows sizes and initialize last items. */
3300 	vt_upgrade(vd);
3301 
3302 	/*
3303 	 * Give a chance to the new backend to run the post-switch code, for
3304 	 * instance to refresh the screen.
3305 	 */
3306 	if (vd->vd_driver->vd_postswitch)
3307 		vd->vd_driver->vd_postswitch(vd);
3308 
3309 #ifdef DEV_SPLASH
3310 	if (vd->vd_flags & VDF_SPLASH)
3311 		vtterm_splash(vd);
3312 #endif
3313 
3314 	if (vd->vd_flags & VDF_ASYNC) {
3315 		/* Allow to put chars now. */
3316 		terminal_mute(vd->vd_curwindow->vw_terminal, 0);
3317 		/* Rerun timer for screen updates. */
3318 		vt_resume_flush_timer(vd->vd_curwindow, 0);
3319 	}
3320 
3321 	/*
3322 	 * Register as console. If it already registered, cnadd() will ignore
3323 	 * it.
3324 	 */
3325 	termcn_cnregister(vd->vd_windows[VT_CONSWINDOW]->vw_terminal);
3326 }
3327 
3328 static void
3329 vt_suspend_handler(void *priv)
3330 {
3331 	struct vt_device *vd;
3332 
3333 	vd = priv;
3334 	vd->vd_flags |= VDF_SUSPENDED;
3335 	if (vd->vd_driver != NULL && vd->vd_driver->vd_suspend != NULL)
3336 		vd->vd_driver->vd_suspend(vd);
3337 }
3338 
3339 static void
3340 vt_resume_handler(void *priv)
3341 {
3342 	struct vt_device *vd;
3343 
3344 	vd = priv;
3345 	if (vd->vd_driver != NULL && vd->vd_driver->vd_resume != NULL)
3346 		vd->vd_driver->vd_resume(vd);
3347 	vd->vd_flags &= ~VDF_SUSPENDED;
3348 }
3349 
3350 int
3351 vt_allocate(const struct vt_driver *drv, void *softc)
3352 {
3353 
3354 	if (!vty_enabled(VTY_VT))
3355 		return (EINVAL);
3356 
3357 	if (main_vd->vd_driver == NULL) {
3358 		main_vd->vd_driver = drv;
3359 		printf("VT: initialize with new VT driver \"%s\".\n",
3360 		    drv->vd_name);
3361 	} else {
3362 		/*
3363 		 * Check if have rights to replace current driver. For example:
3364 		 * it is bad idea to replace KMS driver with generic VGA one.
3365 		 */
3366 		if (drv->vd_priority <= main_vd->vd_driver->vd_priority) {
3367 			printf("VT: Driver priority %d too low. Current %d\n ",
3368 			    drv->vd_priority, main_vd->vd_driver->vd_priority);
3369 			return (EEXIST);
3370 		}
3371 		printf("VT: Replacing driver \"%s\" with new \"%s\".\n",
3372 		    main_vd->vd_driver->vd_name, drv->vd_name);
3373 	}
3374 
3375 	vt_replace_backend(drv, softc);
3376 
3377 	return (0);
3378 }
3379 
3380 int
3381 vt_deallocate(const struct vt_driver *drv, void *softc)
3382 {
3383 
3384 	if (!vty_enabled(VTY_VT))
3385 		return (EINVAL);
3386 
3387 	if (main_vd->vd_prev_driver == NULL ||
3388 	    main_vd->vd_driver != drv ||
3389 	    main_vd->vd_softc != softc)
3390 		return (EPERM);
3391 
3392 	printf("VT: Switching back from \"%s\" to \"%s\".\n",
3393 	    main_vd->vd_driver->vd_name, main_vd->vd_prev_driver->vd_name);
3394 
3395 	vt_replace_backend(NULL, NULL);
3396 
3397 	return (0);
3398 }
3399 
3400 void
3401 vt_suspend(struct vt_device *vd)
3402 {
3403 	int error;
3404 
3405 	if (vt_suspendswitch == 0)
3406 		return;
3407 	/* Save current window. */
3408 	vd->vd_savedwindow = vd->vd_curwindow;
3409 	/* Ask holding process to free window and switch to console window */
3410 	vt_proc_window_switch(vd->vd_windows[VT_CONSWINDOW]);
3411 
3412 	/* Wait for the window switch to complete. */
3413 	error = 0;
3414 	VT_LOCK(vd);
3415 	while (vd->vd_curwindow != vd->vd_windows[VT_CONSWINDOW] && error == 0)
3416 		error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
3417 	VT_UNLOCK(vd);
3418 }
3419 
3420 void
3421 vt_resume(struct vt_device *vd)
3422 {
3423 
3424 	if (vt_suspendswitch == 0)
3425 		return;
3426 	/* Switch back to saved window, if any */
3427 	vt_proc_window_switch(vd->vd_savedwindow);
3428 	vd->vd_savedwindow = NULL;
3429 }
3430