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