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