xref: /freebsd/sys/dev/vt/vt_core.c (revision a2f733abcff64628b7771a47089628b7327a88bd)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009, 2013 The FreeBSD Foundation
5  *
6  * This software was developed by Ed Schouten under sponsorship from the
7  * FreeBSD Foundation.
8  *
9  * Portions of this software were developed by Oleksandr Rybalko
10  * under sponsorship from the FreeBSD Foundation.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 #include <sys/param.h>
36 #include <sys/consio.h>
37 #include <sys/devctl.h>
38 #include <sys/eventhandler.h>
39 #include <sys/fbio.h>
40 #include <sys/font.h>
41 #include <sys/kbio.h>
42 #include <sys/kdb.h>
43 #include <sys/kernel.h>
44 #include <sys/linker.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mutex.h>
48 #include <sys/power.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/random.h>
52 #include <sys/reboot.h>
53 #include <sys/sbuf.h>
54 #include <sys/systm.h>
55 #include <sys/terminal.h>
56 
57 #include <dev/kbd/kbdreg.h>
58 #include <dev/vt/vt.h>
59 
60 #if defined(__i386__) || defined(__amd64__)
61 #include <machine/psl.h>
62 #include <machine/frame.h>
63 #endif
64 
65 static int vtterm_cngrab_noswitch(struct vt_device *, struct vt_window *);
66 static int vtterm_cnungrab_noswitch(struct vt_device *, struct vt_window *);
67 
68 static tc_bell_t	vtterm_bell;
69 static tc_cursor_t	vtterm_cursor;
70 static tc_putchar_t	vtterm_putchar;
71 static tc_fill_t	vtterm_fill;
72 static tc_copy_t	vtterm_copy;
73 static tc_pre_input_t	vtterm_pre_input;
74 static tc_post_input_t	vtterm_post_input;
75 static tc_param_t	vtterm_param;
76 static tc_done_t	vtterm_done;
77 
78 static tc_cnprobe_t	vtterm_cnprobe;
79 static tc_cngetc_t	vtterm_cngetc;
80 
81 static tc_cngrab_t	vtterm_cngrab;
82 static tc_cnungrab_t	vtterm_cnungrab;
83 
84 static tc_opened_t	vtterm_opened;
85 static tc_ioctl_t	vtterm_ioctl;
86 static tc_mmap_t	vtterm_mmap;
87 
88 static const struct terminal_class vt_termclass = {
89 	.tc_bell	= vtterm_bell,
90 	.tc_cursor	= vtterm_cursor,
91 	.tc_putchar	= vtterm_putchar,
92 	.tc_fill	= vtterm_fill,
93 	.tc_copy	= vtterm_copy,
94 	.tc_pre_input	= vtterm_pre_input,
95 	.tc_post_input	= vtterm_post_input,
96 	.tc_param	= vtterm_param,
97 	.tc_done	= vtterm_done,
98 
99 	.tc_cnprobe	= vtterm_cnprobe,
100 	.tc_cngetc	= vtterm_cngetc,
101 
102 	.tc_cngrab	= vtterm_cngrab,
103 	.tc_cnungrab	= vtterm_cnungrab,
104 
105 	.tc_opened	= vtterm_opened,
106 	.tc_ioctl	= vtterm_ioctl,
107 	.tc_mmap	= vtterm_mmap,
108 };
109 
110 /*
111  * Use a constant timer of 25 Hz to redraw the screen.
112  *
113  * XXX: In theory we should only fire up the timer when there is really
114  * activity. Unfortunately we cannot always start timers. We really
115  * don't want to process kernel messages synchronously, because it
116  * really slows down the system.
117  */
118 #define	VT_TIMERFREQ	25
119 
120 /* Bell pitch/duration. */
121 #define	VT_BELLDURATION	(SBT_1S / 20)
122 #define	VT_BELLPITCH	(1193182 / 800) /* Approx 1491Hz */
123 
124 #define	VT_UNIT(vw)	((vw)->vw_device->vd_unit * VT_MAXWINDOWS + \
125 			(vw)->vw_number)
126 
127 static SYSCTL_NODE(_kern, OID_AUTO, vt, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
128     "vt(9) parameters");
129 static VT_SYSCTL_INT(enable_altgr, 1, "Enable AltGr key (Do not assume R.Alt as Alt)");
130 static VT_SYSCTL_INT(enable_bell, 0, "Enable bell");
131 static VT_SYSCTL_INT(debug, 0, "vt(9) debug level");
132 static VT_SYSCTL_INT(deadtimer, 15, "Time to wait busy process in VT_PROCESS mode");
133 static VT_SYSCTL_INT(suspendswitch, 1, "Switch to VT0 before suspend");
134 
135 /* Allow to disable some keyboard combinations. */
136 static VT_SYSCTL_INT(kbd_halt, 1, "Enable halt keyboard combination.  "
137     "See kbdmap(5) to configure.");
138 static VT_SYSCTL_INT(kbd_poweroff, 1, "Enable Power Off keyboard combination.  "
139     "See kbdmap(5) to configure.");
140 static VT_SYSCTL_INT(kbd_reboot, 1, "Enable reboot keyboard combination.  "
141     "See kbdmap(5) to configure (typically Ctrl-Alt-Delete).");
142 static VT_SYSCTL_INT(kbd_debug, 1, "Enable key combination to enter debugger.  "
143     "See kbdmap(5) to configure (typically Ctrl-Alt-Esc).");
144 static VT_SYSCTL_INT(kbd_panic, 0, "Enable request to panic.  "
145     "See kbdmap(5) to configure.");
146 
147 /* Used internally, not a tunable. */
148 int vt_draw_logo_cpus;
149 VT_SYSCTL_INT(splash_cpu, 0, "Show logo CPUs during boot");
150 VT_SYSCTL_INT(splash_ncpu, 0, "Override number of logos displayed "
151     "(0 = do not override)");
152 VT_SYSCTL_INT(splash_cpu_style, 2, "Draw logo style "
153     "(0 = Alternate beastie, 1 = Beastie, 2 = Orb)");
154 VT_SYSCTL_INT(splash_cpu_duration, 10, "Hide logos after (seconds)");
155 
156 static unsigned int vt_unit = 0;
157 static MALLOC_DEFINE(M_VT, "vt", "vt device");
158 struct vt_device *main_vd = &vt_consdev;
159 
160 /* Boot logo. */
161 extern unsigned int vt_logo_width;
162 extern unsigned int vt_logo_height;
163 extern unsigned int vt_logo_depth;
164 extern unsigned char vt_logo_image[];
165 #ifndef DEV_SPLASH
166 #define	vtterm_draw_cpu_logos(...)	do {} while (0)
167 const unsigned int vt_logo_sprite_height;
168 #endif
169 
170 /*
171  * Console font. vt_font_loader will be filled with font data passed
172  * by loader. If there is no font passed by boot loader, we use built in
173  * default.
174  */
175 extern struct vt_font vt_font_default;
176 static struct vt_font vt_font_loader;
177 static struct vt_font *vt_font_assigned = &vt_font_default;
178 
179 #ifndef SC_NO_CUTPASTE
180 extern struct vt_mouse_cursor vt_default_mouse_pointer;
181 #endif
182 
183 static int signal_vt_rel(struct vt_window *);
184 static int signal_vt_acq(struct vt_window *);
185 static int finish_vt_rel(struct vt_window *, int, int *);
186 static int finish_vt_acq(struct vt_window *);
187 static int vt_window_switch(struct vt_window *);
188 static int vt_late_window_switch(struct vt_window *);
189 static int vt_proc_alive(struct vt_window *);
190 static void vt_resize(struct vt_device *);
191 static void vt_update_static(void *);
192 #ifndef SC_NO_CUTPASTE
193 static void vt_mouse_paste(void);
194 #endif
195 static void vt_suspend_handler(void *priv);
196 static void vt_resume_handler(void *priv);
197 
198 SET_DECLARE(vt_drv_set, struct vt_driver);
199 
200 #define	_VTDEFH	MAX(100, PIXEL_HEIGHT(VT_FB_MAX_HEIGHT))
201 #define	_VTDEFW	MAX(200, PIXEL_WIDTH(VT_FB_MAX_WIDTH))
202 
203 static struct terminal	vt_consterm;
204 static struct vt_window	vt_conswindow;
205 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 	vt_axis_t top, left;
1662 
1663 	/* Display a nice boot splash. */
1664 	if (!(vd->vd_flags & VDF_TEXTMODE) && (boothowto & RB_MUTE)) {
1665 		top = (vd->vd_height - vt_logo_height) / 2;
1666 		left = (vd->vd_width - vt_logo_width) / 2;
1667 		switch (vt_logo_depth) {
1668 		case 1:
1669 			/* XXX: Unhardcode colors! */
1670 			vd->vd_driver->vd_bitblt_bmp(vd, vd->vd_curwindow,
1671 			    vt_logo_image, NULL, vt_logo_width, vt_logo_height,
1672 			    left, top, TC_WHITE, TC_BLACK);
1673 		}
1674 		vd->vd_flags |= VDF_SPLASH;
1675 	}
1676 }
1677 #endif
1678 
1679 static struct vt_font *
1680 parse_font_info_static(struct font_info *fi)
1681 {
1682 	struct vt_font *vfp;
1683 	uintptr_t ptr;
1684 	uint32_t checksum;
1685 
1686 	if (fi == NULL)
1687 		return (NULL);
1688 
1689 	ptr = (uintptr_t)fi;
1690 	/*
1691 	 * Compute and verify checksum. The total sum of all the fields
1692 	 * must be 0.
1693 	 */
1694 	checksum = fi->fi_width;
1695 	checksum += fi->fi_height;
1696 	checksum += fi->fi_bitmap_size;
1697 	for (unsigned i = 0; i < VFNT_MAPS; i++)
1698 		checksum += fi->fi_map_count[i];
1699 
1700 	if (checksum + fi->fi_checksum != 0)
1701 		return (NULL);
1702 
1703 	ptr += sizeof(struct font_info);
1704 	ptr = roundup2(ptr, 8);
1705 
1706 	vfp = &vt_font_loader;
1707 	vfp->vf_height = fi->fi_height;
1708 	vfp->vf_width = fi->fi_width;
1709 	/* This is default font, set refcount 1 to disable removal. */
1710 	vfp->vf_refcount = 1;
1711 	for (unsigned i = 0; i < VFNT_MAPS; i++) {
1712 		if (fi->fi_map_count[i] == 0)
1713 			continue;
1714 		vfp->vf_map_count[i] = fi->fi_map_count[i];
1715 		vfp->vf_map[i] = (vfnt_map_t *)ptr;
1716 		ptr += (fi->fi_map_count[i] * sizeof(vfnt_map_t));
1717 		ptr = roundup2(ptr, 8);
1718 	}
1719 	vfp->vf_bytes = (uint8_t *)ptr;
1720 	return (vfp);
1721 }
1722 
1723 /*
1724  * Set up default font with allocated data structures.
1725  * However, we can not set refcount here, because it is already set and
1726  * incremented in vtterm_cnprobe() to avoid being released by font load from
1727  * userland.
1728  */
1729 static struct vt_font *
1730 parse_font_info(struct font_info *fi)
1731 {
1732 	struct vt_font *vfp;
1733 	uintptr_t ptr;
1734 	uint32_t checksum;
1735 	size_t size;
1736 
1737 	if (fi == NULL)
1738 		return (NULL);
1739 
1740 	ptr = (uintptr_t)fi;
1741 	/*
1742 	 * Compute and verify checksum. The total sum of all the fields
1743 	 * must be 0.
1744 	 */
1745 	checksum = fi->fi_width;
1746 	checksum += fi->fi_height;
1747 	checksum += fi->fi_bitmap_size;
1748 	for (unsigned i = 0; i < VFNT_MAPS; i++)
1749 		checksum += fi->fi_map_count[i];
1750 
1751 	if (checksum + fi->fi_checksum != 0)
1752 		return (NULL);
1753 
1754 	ptr += sizeof(struct font_info);
1755 	ptr = roundup2(ptr, 8);
1756 
1757 	vfp = &vt_font_loader;
1758 	vfp->vf_height = fi->fi_height;
1759 	vfp->vf_width = fi->fi_width;
1760 	for (unsigned i = 0; i < VFNT_MAPS; i++) {
1761 		if (fi->fi_map_count[i] == 0)
1762 			continue;
1763 		vfp->vf_map_count[i] = fi->fi_map_count[i];
1764 		size = fi->fi_map_count[i] * sizeof(vfnt_map_t);
1765 		vfp->vf_map[i] = malloc(size, M_VT, M_WAITOK | M_ZERO);
1766 		bcopy((vfnt_map_t *)ptr, vfp->vf_map[i], size);
1767 		ptr += size;
1768 		ptr = roundup2(ptr, 8);
1769 	}
1770 	vfp->vf_bytes = malloc(fi->fi_bitmap_size, M_VT, M_WAITOK | M_ZERO);
1771 	bcopy((uint8_t *)ptr, vfp->vf_bytes, fi->fi_bitmap_size);
1772 	return (vfp);
1773 }
1774 
1775 static void
1776 vt_init_font(void *arg)
1777 {
1778 	caddr_t kmdp;
1779 	struct font_info *fi;
1780 	struct vt_font *font;
1781 
1782 	kmdp = preload_search_by_type("elf kernel");
1783 	if (kmdp == NULL)
1784 		kmdp = preload_search_by_type("elf64 kernel");
1785 	fi = MD_FETCH(kmdp, MODINFOMD_FONT, struct font_info *);
1786 
1787 	font = parse_font_info(fi);
1788 	if (font != NULL)
1789 		vt_font_assigned = font;
1790 }
1791 
1792 SYSINIT(vt_init_font, SI_SUB_KMEM, SI_ORDER_ANY, vt_init_font, &vt_consdev);
1793 
1794 static void
1795 vt_init_font_static(void)
1796 {
1797 	caddr_t kmdp;
1798 	struct font_info *fi;
1799 	struct vt_font *font;
1800 
1801 	kmdp = preload_search_by_type("elf kernel");
1802 	if (kmdp == NULL)
1803 		kmdp = preload_search_by_type("elf64 kernel");
1804 	fi = MD_FETCH(kmdp, MODINFOMD_FONT, struct font_info *);
1805 
1806 	font = parse_font_info_static(fi);
1807 	if (font != NULL)
1808 		vt_font_assigned = font;
1809 }
1810 
1811 static void
1812 vtterm_cnprobe(struct terminal *tm, struct consdev *cp)
1813 {
1814 	struct vt_driver *vtd, **vtdlist, *vtdbest = NULL;
1815 	struct vt_window *vw = tm->tm_softc;
1816 	struct vt_device *vd = vw->vw_device;
1817 	struct winsize wsz;
1818 	const term_attr_t *a;
1819 
1820 	if (!vty_enabled(VTY_VT))
1821 		return;
1822 
1823 	if (vd->vd_flags & VDF_INITIALIZED)
1824 		/* Initialization already done. */
1825 		return;
1826 
1827 	SET_FOREACH(vtdlist, vt_drv_set) {
1828 		vtd = *vtdlist;
1829 		if (vtd->vd_probe == NULL)
1830 			continue;
1831 		if (vtd->vd_probe(vd) == CN_DEAD)
1832 			continue;
1833 		if ((vtdbest == NULL) ||
1834 		    (vtd->vd_priority > vtdbest->vd_priority))
1835 			vtdbest = vtd;
1836 	}
1837 	if (vtdbest == NULL) {
1838 		cp->cn_pri = CN_DEAD;
1839 		vd->vd_flags |= VDF_DEAD;
1840 	} else {
1841 		vd->vd_driver = vtdbest;
1842 		cp->cn_pri = vd->vd_driver->vd_init(vd);
1843 	}
1844 
1845 	/* Check if driver's vt_init return CN_DEAD. */
1846 	if (cp->cn_pri == CN_DEAD) {
1847 		vd->vd_flags |= VDF_DEAD;
1848 	}
1849 
1850 	/* Initialize any early-boot keyboard drivers */
1851 	kbd_configure(KB_CONF_PROBE_ONLY);
1852 
1853 	vd->vd_unit = atomic_fetchadd_int(&vt_unit, 1);
1854 	vd->vd_windows[VT_CONSWINDOW] = vw;
1855 	sprintf(cp->cn_name, "ttyv%r", VT_UNIT(vw));
1856 
1857 	vt_init_font_static();
1858 
1859 	/* Attach default font if not in TEXTMODE. */
1860 	if ((vd->vd_flags & VDF_TEXTMODE) == 0) {
1861 		vw->vw_font = vtfont_ref(vt_font_assigned);
1862 		vt_compute_drawable_area(vw);
1863 	}
1864 
1865 	/*
1866 	 * The original screen size was faked (_VTDEFW x _VTDEFH). Now
1867 	 * that we have the real viewable size, fix it in the static
1868 	 * buffer.
1869 	 */
1870 	if (vd->vd_width != 0 && vd->vd_height != 0)
1871 		vt_termsize(vd, vw->vw_font, &vw->vw_buf.vb_scr_size);
1872 
1873 	/* We need to access terminal attributes from vtbuf */
1874 	vw->vw_buf.vb_terminal = tm;
1875 	vtbuf_init_early(&vw->vw_buf);
1876 	vt_winsize(vd, vw->vw_font, &wsz);
1877 	a = teken_get_curattr(&tm->tm_emulator);
1878 	terminal_set_winsize_blank(tm, &wsz, 1, a);
1879 
1880 	if (vtdbest != NULL) {
1881 #ifdef DEV_SPLASH
1882 		if (!vt_splash_cpu)
1883 			vtterm_splash(vd);
1884 #endif
1885 		vd->vd_flags |= VDF_INITIALIZED;
1886 	}
1887 }
1888 
1889 static int
1890 vtterm_cngetc(struct terminal *tm)
1891 {
1892 	struct vt_window *vw = tm->tm_softc;
1893 	struct vt_device *vd = vw->vw_device;
1894 	keyboard_t *kbd;
1895 	u_int c;
1896 
1897 	if (vw->vw_kbdsq && *vw->vw_kbdsq)
1898 		return (*vw->vw_kbdsq++);
1899 
1900 	/* Make sure the splash screen is not there. */
1901 	if (vd->vd_flags & VDF_SPLASH) {
1902 		/* Remove splash */
1903 		vd->vd_flags &= ~VDF_SPLASH;
1904 		/* Mark screen as invalid to force update */
1905 		vd->vd_flags |= VDF_INVALID;
1906 		vt_flush(vd);
1907 	}
1908 
1909 	/* Stripped down keyboard handler. */
1910 	if ((kbd = vd->vd_keyboard) == NULL)
1911 		return (-1);
1912 
1913 	/* Force keyboard input mode to K_XLATE */
1914 	vw->vw_kbdmode = K_XLATE;
1915 	vt_update_kbd_mode(vw, kbd);
1916 
1917 	/* Switch the keyboard to polling to make it work here. */
1918 	kbdd_poll(kbd, TRUE);
1919 	c = kbdd_read_char(kbd, 0);
1920 	kbdd_poll(kbd, FALSE);
1921 	if (c & RELKEY)
1922 		return (-1);
1923 
1924 	if (vw->vw_flags & VWF_SCROLL) {
1925 		vt_scrollmode_kbdevent(vw, c, 1/* Console mode */);
1926 		vt_flush(vd);
1927 		return (-1);
1928 	}
1929 
1930 	/* Stripped down handling of vt_kbdevent(), without locking, etc. */
1931 	if (c & SPCLKEY) {
1932 		switch (c) {
1933 		case SPCLKEY | SLK:
1934 			vt_save_kbd_state(vw, kbd);
1935 			if (vw->vw_kbdstate & SLKED) {
1936 				/* Turn scrolling on. */
1937 				vw->vw_flags |= VWF_SCROLL;
1938 				VTBUF_SLCK_ENABLE(&vw->vw_buf);
1939 			} else {
1940 				/* Turn scrolling off. */
1941 				vt_scroll(vw, 0, VHS_END);
1942 				vw->vw_flags &= ~VWF_SCROLL;
1943 				VTBUF_SLCK_DISABLE(&vw->vw_buf);
1944 			}
1945 			break;
1946 		/* XXX: KDB can handle history. */
1947 		case SPCLKEY | FKEY | F(50): /* Arrow up. */
1948 			vw->vw_kbdsq = "\x1b[A";
1949 			break;
1950 		case SPCLKEY | FKEY | F(58): /* Arrow down. */
1951 			vw->vw_kbdsq = "\x1b[B";
1952 			break;
1953 		case SPCLKEY | FKEY | F(55): /* Arrow right. */
1954 			vw->vw_kbdsq = "\x1b[C";
1955 			break;
1956 		case SPCLKEY | FKEY | F(53): /* Arrow left. */
1957 			vw->vw_kbdsq = "\x1b[D";
1958 			break;
1959 		}
1960 
1961 		/* Force refresh to make scrollback work. */
1962 		vt_flush(vd);
1963 	} else if (KEYFLAGS(c) == 0) {
1964 		return (KEYCHAR(c));
1965 	}
1966 
1967 	if (vw->vw_kbdsq && *vw->vw_kbdsq)
1968 		return (*vw->vw_kbdsq++);
1969 
1970 	return (-1);
1971 }
1972 
1973 /*
1974  * These two do most of what we want to do in vtterm_cnungrab, but without
1975  * actually switching windows.  This is necessary for, e.g.,
1976  * vt_allocate_keyboard() to get the current keyboard into the state it needs to
1977  * be in without damaging the device's window state.
1978  *
1979  * Both return the current grab count, though it's only used in vtterm_cnungrab.
1980  */
1981 static int
1982 vtterm_cngrab_noswitch(struct vt_device *vd, struct vt_window *vw)
1983 {
1984 	keyboard_t *kbd;
1985 
1986 	if (vw->vw_grabbed++ > 0)
1987 		return (vw->vw_grabbed);
1988 
1989 	if ((kbd = vd->vd_keyboard) == NULL)
1990 		return (1);
1991 
1992 	/*
1993 	 * Make sure the keyboard is accessible even when the kbd device
1994 	 * driver is disabled.
1995 	 */
1996 	kbdd_enable(kbd);
1997 
1998 	/* We shall always use the keyboard in the XLATE mode here. */
1999 	vw->vw_prev_kbdmode = vw->vw_kbdmode;
2000 	vw->vw_kbdmode = K_XLATE;
2001 	vt_update_kbd_mode(vw, kbd);
2002 
2003 	kbdd_poll(kbd, TRUE);
2004 	return (1);
2005 }
2006 
2007 static int
2008 vtterm_cnungrab_noswitch(struct vt_device *vd, struct vt_window *vw)
2009 {
2010 	keyboard_t *kbd;
2011 
2012 	if (--vw->vw_grabbed > 0)
2013 		return (vw->vw_grabbed);
2014 
2015 	if ((kbd = vd->vd_keyboard) == NULL)
2016 		return (0);
2017 
2018 	kbdd_poll(kbd, FALSE);
2019 
2020 	vw->vw_kbdmode = vw->vw_prev_kbdmode;
2021 	vt_update_kbd_mode(vw, kbd);
2022 	kbdd_disable(kbd);
2023 	return (0);
2024 }
2025 
2026 static void
2027 vtterm_cngrab(struct terminal *tm)
2028 {
2029 	struct vt_device *vd;
2030 	struct vt_window *vw;
2031 
2032 	vw = tm->tm_softc;
2033 	vd = vw->vw_device;
2034 
2035 	/* To be restored after we ungrab. */
2036 	if (vd->vd_grabwindow == NULL)
2037 		vd->vd_grabwindow = vd->vd_curwindow;
2038 
2039 	if (!cold)
2040 		vt_window_switch(vw);
2041 
2042 	vtterm_cngrab_noswitch(vd, vw);
2043 }
2044 
2045 static void
2046 vtterm_cnungrab(struct terminal *tm)
2047 {
2048 	struct vt_device *vd;
2049 	struct vt_window *vw, *grabwindow;
2050 
2051 	vw = tm->tm_softc;
2052 	vd = vw->vw_device;
2053 
2054 	MPASS(vd->vd_grabwindow != NULL);
2055 	if (vtterm_cnungrab_noswitch(vd, vw) != 0)
2056 		return;
2057 
2058 	/*
2059 	 * We set `vd_grabwindow` to NULL before calling vt_window_switch()
2060 	 * because it allows the underlying vt(4) backend to distinguish a
2061 	 * "grab" from an "ungrab" of the console.
2062 	 *
2063 	 * This is used by `vt_drmfb` in drm-kmod to call either
2064 	 * fb_debug_enter() or fb_debug_leave() appropriately.
2065 	 */
2066 	grabwindow = vd->vd_grabwindow;
2067 	vd->vd_grabwindow = NULL;
2068 
2069 	if (!cold)
2070 		vt_window_switch(grabwindow);
2071 }
2072 
2073 static void
2074 vtterm_opened(struct terminal *tm, int opened)
2075 {
2076 	struct vt_window *vw = tm->tm_softc;
2077 	struct vt_device *vd = vw->vw_device;
2078 
2079 	VT_LOCK(vd);
2080 	vd->vd_flags &= ~VDF_SPLASH;
2081 	if (opened)
2082 		vw->vw_flags |= VWF_OPENED;
2083 	else {
2084 		vw->vw_flags &= ~VWF_OPENED;
2085 		/* TODO: finish ACQ/REL */
2086 	}
2087 	VT_UNLOCK(vd);
2088 }
2089 
2090 static int
2091 vt_change_font(struct vt_window *vw, struct vt_font *vf)
2092 {
2093 	struct vt_device *vd = vw->vw_device;
2094 	struct terminal *tm = vw->vw_terminal;
2095 	term_pos_t size;
2096 	struct winsize wsz;
2097 
2098 	/*
2099 	 * Changing fonts.
2100 	 *
2101 	 * Changing fonts is a little tricky.  We must prevent
2102 	 * simultaneous access to the device, so we must stop
2103 	 * the display timer and the terminal from accessing.
2104 	 * We need to switch fonts and grow our screen buffer.
2105 	 *
2106 	 * XXX: Right now the code uses terminal_mute() to
2107 	 * prevent data from reaching the console driver while
2108 	 * resizing the screen buffer.  This isn't elegant...
2109 	 */
2110 
2111 	VT_LOCK(vd);
2112 	if (vw->vw_flags & VWF_BUSY) {
2113 		/* Another process is changing the font. */
2114 		VT_UNLOCK(vd);
2115 		return (EBUSY);
2116 	}
2117 	vw->vw_flags |= VWF_BUSY;
2118 	VT_UNLOCK(vd);
2119 
2120 	vt_termsize(vd, vf, &size);
2121 	vt_winsize(vd, vf, &wsz);
2122 
2123 	/* Grow the screen buffer and terminal. */
2124 	terminal_mute(tm, 1);
2125 	vtbuf_grow(&vw->vw_buf, &size, vw->vw_buf.vb_history_size);
2126 	terminal_set_winsize_blank(tm, &wsz, 0, NULL);
2127 	terminal_set_cursor(tm, &vw->vw_buf.vb_cursor);
2128 	terminal_mute(tm, 0);
2129 
2130 	/* Actually apply the font to the current window. */
2131 	VT_LOCK(vd);
2132 	if (vw->vw_font != vf && vw->vw_font != NULL && vf != NULL) {
2133 		/*
2134 		 * In case vt_change_font called to update size we don't need
2135 		 * to update font link.
2136 		 */
2137 		vtfont_unref(vw->vw_font);
2138 		vw->vw_font = vtfont_ref(vf);
2139 	}
2140 
2141 	/*
2142 	 * Compute the drawable area and move the mouse cursor inside
2143 	 * it, in case the new area is smaller than the previous one.
2144 	 */
2145 	vt_compute_drawable_area(vw);
2146 	vd->vd_mx = min(vd->vd_mx,
2147 	    vw->vw_draw_area.tr_end.tp_col -
2148 	    vw->vw_draw_area.tr_begin.tp_col - 1);
2149 	vd->vd_my = min(vd->vd_my,
2150 	    vw->vw_draw_area.tr_end.tp_row -
2151 	    vw->vw_draw_area.tr_begin.tp_row - 1);
2152 
2153 	/* Force a full redraw the next timer tick. */
2154 	if (vd->vd_curwindow == vw) {
2155 		vd->vd_flags |= VDF_INVALID;
2156 		vt_resume_flush_timer(vw, 0);
2157 	}
2158 	vw->vw_flags &= ~VWF_BUSY;
2159 	VT_UNLOCK(vd);
2160 	return (0);
2161 }
2162 
2163 static int
2164 vt_proc_alive(struct vt_window *vw)
2165 {
2166 	struct proc *p;
2167 
2168 	if (vw->vw_smode.mode != VT_PROCESS)
2169 		return (FALSE);
2170 
2171 	if (vw->vw_proc) {
2172 		if ((p = pfind(vw->vw_pid)) != NULL)
2173 			PROC_UNLOCK(p);
2174 		if (vw->vw_proc == p)
2175 			return (TRUE);
2176 		vw->vw_proc = NULL;
2177 		vw->vw_smode.mode = VT_AUTO;
2178 		DPRINTF(1, "vt controlling process %d died\n", vw->vw_pid);
2179 		vw->vw_pid = 0;
2180 	}
2181 	return (FALSE);
2182 }
2183 
2184 static int
2185 signal_vt_rel(struct vt_window *vw)
2186 {
2187 
2188 	if (vw->vw_smode.mode != VT_PROCESS)
2189 		return (FALSE);
2190 	if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
2191 		vw->vw_proc = NULL;
2192 		vw->vw_pid = 0;
2193 		return (TRUE);
2194 	}
2195 	vw->vw_flags |= VWF_SWWAIT_REL;
2196 	PROC_LOCK(vw->vw_proc);
2197 	kern_psignal(vw->vw_proc, vw->vw_smode.relsig);
2198 	PROC_UNLOCK(vw->vw_proc);
2199 	DPRINTF(1, "sending relsig to %d\n", vw->vw_pid);
2200 	return (TRUE);
2201 }
2202 
2203 static int
2204 signal_vt_acq(struct vt_window *vw)
2205 {
2206 
2207 	if (vw->vw_smode.mode != VT_PROCESS)
2208 		return (FALSE);
2209 	if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
2210 		cnavailable(vw->vw_terminal->consdev, FALSE);
2211 	if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
2212 		vw->vw_proc = NULL;
2213 		vw->vw_pid = 0;
2214 		return (TRUE);
2215 	}
2216 	vw->vw_flags |= VWF_SWWAIT_ACQ;
2217 	PROC_LOCK(vw->vw_proc);
2218 	kern_psignal(vw->vw_proc, vw->vw_smode.acqsig);
2219 	PROC_UNLOCK(vw->vw_proc);
2220 	DPRINTF(1, "sending acqsig to %d\n", vw->vw_pid);
2221 	return (TRUE);
2222 }
2223 
2224 static int
2225 finish_vt_rel(struct vt_window *vw, int release, int *s)
2226 {
2227 
2228 	if (vw->vw_flags & VWF_SWWAIT_REL) {
2229 		vw->vw_flags &= ~VWF_SWWAIT_REL;
2230 		if (release) {
2231 			taskqueue_drain_timeout(taskqueue_thread, &vw->vw_timeout_task_dead);
2232 			(void)vt_late_window_switch(vw->vw_switch_to);
2233 		}
2234 		return (0);
2235 	}
2236 	return (EINVAL);
2237 }
2238 
2239 static int
2240 finish_vt_acq(struct vt_window *vw)
2241 {
2242 
2243 	if (vw->vw_flags & VWF_SWWAIT_ACQ) {
2244 		vw->vw_flags &= ~VWF_SWWAIT_ACQ;
2245 		return (0);
2246 	}
2247 	return (EINVAL);
2248 }
2249 
2250 #ifndef SC_NO_CUTPASTE
2251 static void
2252 vt_mouse_terminput_button(struct vt_device *vd, int button)
2253 {
2254 	struct vt_window *vw;
2255 	struct vt_font *vf;
2256 	char mouseb[6] = "\x1B[M";
2257 	int i, x, y;
2258 
2259 	vw = vd->vd_curwindow;
2260 	vf = vw->vw_font;
2261 
2262 	/* Translate to char position. */
2263 	x = vd->vd_mx / vf->vf_width;
2264 	y = vd->vd_my / vf->vf_height;
2265 	/* Avoid overflow. */
2266 	x = MIN(x, 255 - '!');
2267 	y = MIN(y, 255 - '!');
2268 
2269 	mouseb[3] = ' ' + button;
2270 	mouseb[4] = '!' + x;
2271 	mouseb[5] = '!' + y;
2272 
2273 	for (i = 0; i < sizeof(mouseb); i++)
2274 		terminal_input_char(vw->vw_terminal, mouseb[i]);
2275 }
2276 
2277 static void
2278 vt_mouse_terminput(struct vt_device *vd, int type, int x, int y, int event,
2279     int cnt)
2280 {
2281 
2282 	switch (type) {
2283 	case MOUSE_BUTTON_EVENT:
2284 		if (cnt > 0) {
2285 			/* Mouse button pressed. */
2286 			if (event & MOUSE_BUTTON1DOWN)
2287 				vt_mouse_terminput_button(vd, 0);
2288 			if (event & MOUSE_BUTTON2DOWN)
2289 				vt_mouse_terminput_button(vd, 1);
2290 			if (event & MOUSE_BUTTON3DOWN)
2291 				vt_mouse_terminput_button(vd, 2);
2292 		} else {
2293 			/* Mouse button released. */
2294 			vt_mouse_terminput_button(vd, 3);
2295 		}
2296 		break;
2297 #ifdef notyet
2298 	case MOUSE_MOTION_EVENT:
2299 		if (mouse->u.data.z < 0) {
2300 			/* Scroll up. */
2301 			sc_mouse_input_button(vd, 64);
2302 		} else if (mouse->u.data.z > 0) {
2303 			/* Scroll down. */
2304 			sc_mouse_input_button(vd, 65);
2305 		}
2306 		break;
2307 #endif
2308 	}
2309 }
2310 
2311 static void
2312 vt_mouse_paste(void)
2313 {
2314 	term_char_t *buf;
2315 	int i, len;
2316 
2317 	len = VD_PASTEBUFLEN(main_vd);
2318 	buf = VD_PASTEBUF(main_vd);
2319 	len /= sizeof(term_char_t);
2320 	for (i = 0; i < len; i++) {
2321 		if (TCHAR_CHARACTER(buf[i]) == '\0')
2322 			continue;
2323 		terminal_input_char(main_vd->vd_curwindow->vw_terminal,
2324 		    buf[i]);
2325 	}
2326 }
2327 
2328 void
2329 vt_mouse_event(int type, int x, int y, int event, int cnt, int mlevel)
2330 {
2331 	struct vt_device *vd;
2332 	struct vt_window *vw;
2333 	struct vt_font *vf;
2334 	term_pos_t size;
2335 	int len, mark;
2336 
2337 	vd = main_vd;
2338 	vw = vd->vd_curwindow;
2339 	vf = vw->vw_font;
2340 
2341 	if (vw->vw_flags & (VWF_MOUSE_HIDE | VWF_GRAPHICS))
2342 		/*
2343 		 * Either the mouse is disabled, or the window is in
2344 		 * "graphics mode". The graphics mode is usually set by
2345 		 * an X server, using the KDSETMODE ioctl.
2346 		 */
2347 		return;
2348 
2349 	if (vf == NULL)	/* Text mode. */
2350 		return;
2351 
2352 	/*
2353 	 * TODO: add flag about pointer position changed, to not redraw chars
2354 	 * under mouse pointer when nothing changed.
2355 	 */
2356 
2357 	if (vw->vw_mouse_level > 0)
2358 		vt_mouse_terminput(vd, type, x, y, event, cnt);
2359 
2360 	switch (type) {
2361 	case MOUSE_ACTION:
2362 	case MOUSE_MOTION_EVENT:
2363 		/* Movement */
2364 		x += vd->vd_mx;
2365 		y += vd->vd_my;
2366 
2367 		vt_termsize(vd, vf, &size);
2368 
2369 		/* Apply limits. */
2370 		x = MAX(x, 0);
2371 		y = MAX(y, 0);
2372 		x = MIN(x, (size.tp_col * vf->vf_width) - 1);
2373 		y = MIN(y, (size.tp_row * vf->vf_height) - 1);
2374 
2375 		vd->vd_mx = x;
2376 		vd->vd_my = y;
2377 		if (vd->vd_mstate & (MOUSE_BUTTON1DOWN | VT_MOUSE_EXTENDBUTTON))
2378 			vtbuf_set_mark(&vw->vw_buf, VTB_MARK_MOVE,
2379 			    vd->vd_mx / vf->vf_width,
2380 			    vd->vd_my / vf->vf_height);
2381 
2382 		vt_resume_flush_timer(vw, 0);
2383 		return; /* Done */
2384 	case MOUSE_BUTTON_EVENT:
2385 		/* Buttons */
2386 		break;
2387 	default:
2388 		return; /* Done */
2389 	}
2390 
2391 	switch (event) {
2392 	case MOUSE_BUTTON1DOWN:
2393 		switch (cnt % 4) {
2394 		case 0:	/* up */
2395 			mark = VTB_MARK_END;
2396 			break;
2397 		case 1: /* single click: start cut operation */
2398 			mark = VTB_MARK_START;
2399 			break;
2400 		case 2:	/* double click: cut a word */
2401 			mark = VTB_MARK_WORD;
2402 			break;
2403 		default:	/* triple click: cut a line */
2404 			mark = VTB_MARK_ROW;
2405 			break;
2406 		}
2407 		break;
2408 	case VT_MOUSE_PASTEBUTTON:
2409 		switch (cnt) {
2410 		case 0:	/* up */
2411 			break;
2412 		default:
2413 			vt_mouse_paste();
2414 			/* clear paste buffer selection after paste */
2415 			vtbuf_set_mark(&vw->vw_buf, VTB_MARK_START,
2416 			    vd->vd_mx / vf->vf_width,
2417 			    vd->vd_my / vf->vf_height);
2418 			break;
2419 		}
2420 		return; /* Done */
2421 	case VT_MOUSE_EXTENDBUTTON:
2422 		switch (cnt) {
2423 		case 0:	/* up */
2424 			if (!(vd->vd_mstate & MOUSE_BUTTON1DOWN))
2425 				mark = VTB_MARK_EXTEND;
2426 			else
2427 				mark = VTB_MARK_NONE;
2428 			break;
2429 		default:
2430 			mark = VTB_MARK_EXTEND;
2431 			break;
2432 		}
2433 		break;
2434 	default:
2435 		return; /* Done */
2436 	}
2437 
2438 	/* Save buttons state. */
2439 	if (cnt > 0)
2440 		vd->vd_mstate |= event;
2441 	else
2442 		vd->vd_mstate &= ~event;
2443 
2444 	if (vtbuf_set_mark(&vw->vw_buf, mark, vd->vd_mx / vf->vf_width,
2445 	    vd->vd_my / vf->vf_height) == 1) {
2446 		/*
2447 		 * We have something marked to copy, so update pointer to
2448 		 * window with selection.
2449 		 */
2450 		vt_resume_flush_timer(vw, 0);
2451 
2452 		switch (mark) {
2453 		case VTB_MARK_END:
2454 		case VTB_MARK_WORD:
2455 		case VTB_MARK_ROW:
2456 		case VTB_MARK_EXTEND:
2457 			break;
2458 		default:
2459 			/* Other types of mark do not require to copy data. */
2460 			return;
2461 		}
2462 
2463 		/* Get current selection size in bytes. */
2464 		len = vtbuf_get_marked_len(&vw->vw_buf);
2465 		if (len <= 0)
2466 			return;
2467 
2468 		/* Reallocate buffer only if old one is too small. */
2469 		if (len > VD_PASTEBUFSZ(vd)) {
2470 			VD_PASTEBUF(vd) = realloc(VD_PASTEBUF(vd), len, M_VT,
2471 			    M_WAITOK | M_ZERO);
2472 			/* Update buffer size. */
2473 			VD_PASTEBUFSZ(vd) = len;
2474 		}
2475 		/* Request copy/paste buffer data, no more than `len' */
2476 		vtbuf_extract_marked(&vw->vw_buf, VD_PASTEBUF(vd), len, mark);
2477 
2478 		VD_PASTEBUFLEN(vd) = len;
2479 
2480 		/* XXX VD_PASTEBUF(vd) have to be freed on shutdown/unload. */
2481 	}
2482 }
2483 
2484 void
2485 vt_mouse_state(int show)
2486 {
2487 	struct vt_device *vd;
2488 	struct vt_window *vw;
2489 
2490 	vd = main_vd;
2491 	vw = vd->vd_curwindow;
2492 
2493 	switch (show) {
2494 	case VT_MOUSE_HIDE:
2495 		vw->vw_flags |= VWF_MOUSE_HIDE;
2496 		break;
2497 	case VT_MOUSE_SHOW:
2498 		vw->vw_flags &= ~VWF_MOUSE_HIDE;
2499 		break;
2500 	}
2501 
2502 	/* Mark mouse position as dirty. */
2503 	vt_mark_mouse_position_as_dirty(vd, false);
2504 	vt_resume_flush_timer(vw, 0);
2505 }
2506 #endif
2507 
2508 static int
2509 vtterm_mmap(struct terminal *tm, vm_ooffset_t offset, vm_paddr_t * paddr,
2510     int nprot, vm_memattr_t *memattr)
2511 {
2512 	struct vt_window *vw = tm->tm_softc;
2513 	struct vt_device *vd = vw->vw_device;
2514 
2515 	if (vd->vd_driver->vd_fb_mmap)
2516 		return (vd->vd_driver->vd_fb_mmap(vd, offset, paddr, nprot,
2517 		    memattr));
2518 
2519 	return (ENXIO);
2520 }
2521 
2522 static int
2523 vtterm_ioctl(struct terminal *tm, u_long cmd, caddr_t data,
2524     struct thread *td)
2525 {
2526 	struct vt_window *vw = tm->tm_softc;
2527 	struct vt_device *vd = vw->vw_device;
2528 	keyboard_t *kbd;
2529 	int error, i, s;
2530 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
2531     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
2532 	int ival;
2533 
2534 	switch (cmd) {
2535 	case _IO('v', 4):
2536 		cmd = VT_RELDISP;
2537 		break;
2538 	case _IO('v', 5):
2539 		cmd = VT_ACTIVATE;
2540 		break;
2541 	case _IO('v', 6):
2542 		cmd = VT_WAITACTIVE;
2543 		break;
2544 	case _IO('K', 20):
2545 		cmd = KDSKBSTATE;
2546 		break;
2547 	case _IO('K', 67):
2548 		cmd = KDSETRAD;
2549 		break;
2550 	case _IO('K', 7):
2551 		cmd = KDSKBMODE;
2552 		break;
2553 	case _IO('K', 8):
2554 		cmd = KDMKTONE;
2555 		break;
2556 	case _IO('K', 10):
2557 		cmd = KDSETMODE;
2558 		break;
2559 	case _IO('K', 13):
2560 		cmd = KDSBORDER;
2561 		break;
2562 	case _IO('K', 63):
2563 		cmd = KIOCSOUND;
2564 		break;
2565 	case _IO('K', 66):
2566 		cmd = KDSETLED;
2567 		break;
2568 	case _IO('c', 104):
2569 		cmd = CONS_SETWINORG;
2570 		break;
2571 	case _IO('c', 110):
2572 		cmd = CONS_SETKBD;
2573 		break;
2574 	default:
2575 		goto skip_thunk;
2576 	}
2577 	ival = IOCPARM_IVAL(data);
2578 	data = (caddr_t)&ival;
2579 skip_thunk:
2580 #endif
2581 
2582 	switch (cmd) {
2583 	case KDSETRAD:		/* set keyboard repeat & delay rates (old) */
2584 		if (*(int *)data & ~0x7f)
2585 			return (EINVAL);
2586 		/* FALLTHROUGH */
2587 	case GIO_KEYMAP:
2588 	case PIO_KEYMAP:
2589 	case GIO_DEADKEYMAP:
2590 	case PIO_DEADKEYMAP:
2591 #ifdef COMPAT_FREEBSD13
2592 	case OGIO_DEADKEYMAP:
2593 	case OPIO_DEADKEYMAP:
2594 #endif /* COMPAT_FREEBSD13 */
2595 	case GETFKEY:
2596 	case SETFKEY:
2597 	case KDGKBINFO:
2598 	case KDGKBTYPE:
2599 	case KDGETREPEAT:	/* get keyboard repeat & delay rates */
2600 	case KDSETREPEAT:	/* set keyboard repeat & delay rates (new) */
2601 	case KBADDKBD:		/* add keyboard to mux */
2602 	case KBRELKBD: {	/* release keyboard from mux */
2603 		error = 0;
2604 
2605 		mtx_lock(&Giant);
2606 		if ((kbd = vd->vd_keyboard) != NULL)
2607 			error = kbdd_ioctl(kbd, cmd, data);
2608 		mtx_unlock(&Giant);
2609 		if (error == ENOIOCTL) {
2610 			if (cmd == KDGKBTYPE) {
2611 				/* always return something? XXX */
2612 				*(int *)data = 0;
2613 			} else {
2614 				return (ENODEV);
2615 			}
2616 		}
2617 		return (error);
2618 	}
2619 	case KDGKBSTATE: {	/* get keyboard state (locks) */
2620 		error = 0;
2621 
2622 		if (vw == vd->vd_curwindow) {
2623 			mtx_lock(&Giant);
2624 			if ((kbd = vd->vd_keyboard) != NULL)
2625 				error = vt_save_kbd_state(vw, kbd);
2626 			mtx_unlock(&Giant);
2627 
2628 			if (error != 0)
2629 				return (error);
2630 		}
2631 
2632 		*(int *)data = vw->vw_kbdstate & LOCK_MASK;
2633 
2634 		return (error);
2635 	}
2636 	case KDSKBSTATE: {	/* set keyboard state (locks) */
2637 		int state;
2638 
2639 		state = *(int *)data;
2640 		if (state & ~LOCK_MASK)
2641 			return (EINVAL);
2642 
2643 		vw->vw_kbdstate &= ~LOCK_MASK;
2644 		vw->vw_kbdstate |= state;
2645 
2646 		error = 0;
2647 		if (vw == vd->vd_curwindow) {
2648 			mtx_lock(&Giant);
2649 			if ((kbd = vd->vd_keyboard) != NULL)
2650 				error = vt_update_kbd_state(vw, kbd);
2651 			mtx_unlock(&Giant);
2652 		}
2653 
2654 		return (error);
2655 	}
2656 	case KDGETLED: {	/* get keyboard LED status */
2657 		error = 0;
2658 
2659 		if (vw == vd->vd_curwindow) {
2660 			mtx_lock(&Giant);
2661 			if ((kbd = vd->vd_keyboard) != NULL)
2662 				error = vt_save_kbd_leds(vw, kbd);
2663 			mtx_unlock(&Giant);
2664 
2665 			if (error != 0)
2666 				return (error);
2667 		}
2668 
2669 		*(int *)data = vw->vw_kbdstate & LED_MASK;
2670 
2671 		return (error);
2672 	}
2673 	case KDSETLED: {	/* set keyboard LED status */
2674 		int leds;
2675 
2676 		leds = *(int *)data;
2677 		if (leds & ~LED_MASK)
2678 			return (EINVAL);
2679 
2680 		vw->vw_kbdstate &= ~LED_MASK;
2681 		vw->vw_kbdstate |= leds;
2682 
2683 		error = 0;
2684 		if (vw == vd->vd_curwindow) {
2685 			mtx_lock(&Giant);
2686 			if ((kbd = vd->vd_keyboard) != NULL)
2687 				error = vt_update_kbd_leds(vw, kbd);
2688 			mtx_unlock(&Giant);
2689 		}
2690 
2691 		return (error);
2692 	}
2693 	case KDGETMODE:
2694 		*(int *)data = (vw->vw_flags & VWF_GRAPHICS) ?
2695 		    KD_GRAPHICS : KD_TEXT;
2696 		return (0);
2697 	case KDGKBMODE: {
2698 		error = 0;
2699 
2700 		if (vw == vd->vd_curwindow) {
2701 			mtx_lock(&Giant);
2702 			if ((kbd = vd->vd_keyboard) != NULL)
2703 				error = vt_save_kbd_mode(vw, kbd);
2704 			mtx_unlock(&Giant);
2705 
2706 			if (error != 0)
2707 				return (error);
2708 		}
2709 
2710 		*(int *)data = vw->vw_kbdmode;
2711 
2712 		return (error);
2713 	}
2714 	case KDSKBMODE: {
2715 		int mode;
2716 
2717 		mode = *(int *)data;
2718 		switch (mode) {
2719 		case K_XLATE:
2720 		case K_RAW:
2721 		case K_CODE:
2722 			vw->vw_kbdmode = mode;
2723 
2724 			error = 0;
2725 			if (vw == vd->vd_curwindow) {
2726 				mtx_lock(&Giant);
2727 				if ((kbd = vd->vd_keyboard) != NULL)
2728 					error = vt_update_kbd_mode(vw, kbd);
2729 				mtx_unlock(&Giant);
2730 			}
2731 
2732 			return (error);
2733 		default:
2734 			return (EINVAL);
2735 		}
2736 	}
2737 	case FBIOGTYPE:
2738 	case FBIO_GETWINORG:	/* get frame buffer window origin */
2739 	case FBIO_GETDISPSTART:	/* get display start address */
2740 	case FBIO_GETLINEWIDTH:	/* get scan line width in bytes */
2741 	case FBIO_BLANK:	/* blank display */
2742 	case FBIO_GETRGBOFFS:	/* get RGB offsets */
2743 		if (vd->vd_driver->vd_fb_ioctl)
2744 			return (vd->vd_driver->vd_fb_ioctl(vd, cmd, data, td));
2745 		break;
2746 	case CONS_BLANKTIME:
2747 		/* XXX */
2748 		return (0);
2749 	case CONS_HISTORY:
2750 		if (*(int *)data < 0)
2751 			return EINVAL;
2752 		if (*(int *)data != vw->vw_buf.vb_history_size)
2753 			vtbuf_sethistory_size(&vw->vw_buf, *(int *)data);
2754 		return (0);
2755 	case CONS_CLRHIST:
2756 		vtbuf_clearhistory(&vw->vw_buf);
2757 		/*
2758 		 * Invalidate the entire visible window; it is not guaranteed
2759 		 * that this operation will be immediately followed by a scroll
2760 		 * event, so it would otherwise be possible for prior artifacts
2761 		 * to remain visible.
2762 		 */
2763 		VT_LOCK(vd);
2764 		if (vw == vd->vd_curwindow) {
2765 			vd->vd_flags |= VDF_INVALID;
2766 			vt_resume_flush_timer(vw, 0);
2767 		}
2768 		VT_UNLOCK(vd);
2769 		return (0);
2770 	case CONS_GET:
2771 		/* XXX */
2772 		*(int *)data = M_CG640x480;
2773 		return (0);
2774 	case CONS_BELLTYPE:	/* set bell type sound */
2775 		if ((*(int *)data) & CONS_QUIET_BELL)
2776 			vd->vd_flags |= VDF_QUIET_BELL;
2777 		else
2778 			vd->vd_flags &= ~VDF_QUIET_BELL;
2779 		return (0);
2780 	case CONS_GETINFO: {
2781 		vid_info_t *vi = (vid_info_t *)data;
2782 		if (vi->size != sizeof(struct vid_info))
2783 			return (EINVAL);
2784 
2785 		if (vw == vd->vd_curwindow) {
2786 			mtx_lock(&Giant);
2787 			if ((kbd = vd->vd_keyboard) != NULL)
2788 				vt_save_kbd_state(vw, kbd);
2789 			mtx_unlock(&Giant);
2790 		}
2791 
2792 		vi->m_num = vd->vd_curwindow->vw_number + 1;
2793 		vi->mk_keylock = vw->vw_kbdstate & LOCK_MASK;
2794 		/* XXX: other fields! */
2795 		return (0);
2796 	}
2797 	case CONS_GETVERS:
2798 		*(int *)data = 0x200;
2799 		return (0);
2800 	case CONS_MODEINFO:
2801 		/* XXX */
2802 		return (0);
2803 	case CONS_MOUSECTL: {
2804 		mouse_info_t *mouse = (mouse_info_t*)data;
2805 
2806 		/*
2807 		 * All the commands except MOUSE_SHOW nd MOUSE_HIDE
2808 		 * should not be applied to individual TTYs, but only to
2809 		 * consolectl.
2810 		 */
2811 		switch (mouse->operation) {
2812 		case MOUSE_HIDE:
2813 			if (vd->vd_flags & VDF_MOUSECURSOR) {
2814 				vd->vd_flags &= ~VDF_MOUSECURSOR;
2815 #ifndef SC_NO_CUTPASTE
2816 				vt_mouse_state(VT_MOUSE_HIDE);
2817 #endif
2818 			}
2819 			return (0);
2820 		case MOUSE_SHOW:
2821 			if (!(vd->vd_flags & VDF_MOUSECURSOR)) {
2822 				vd->vd_flags |= VDF_MOUSECURSOR;
2823 				vd->vd_mx = vd->vd_width / 2;
2824 				vd->vd_my = vd->vd_height / 2;
2825 #ifndef SC_NO_CUTPASTE
2826 				vt_mouse_state(VT_MOUSE_SHOW);
2827 #endif
2828 			}
2829 			return (0);
2830 		default:
2831 			return (EINVAL);
2832 		}
2833 	}
2834 	case PIO_VFONT: {
2835 		struct vt_font *vf;
2836 
2837 		if (vd->vd_flags & VDF_TEXTMODE)
2838 			return (ENOTSUP);
2839 
2840 		error = vtfont_load((void *)data, &vf);
2841 		if (error != 0)
2842 			return (error);
2843 
2844 		error = vt_change_font(vw, vf);
2845 		vtfont_unref(vf);
2846 		return (error);
2847 	}
2848 	case PIO_VFONT_DEFAULT: {
2849 		/* Reset to default font. */
2850 		error = vt_change_font(vw, vt_font_assigned);
2851 		return (error);
2852 	}
2853 	case GIO_SCRNMAP: {
2854 		scrmap_t *sm = (scrmap_t *)data;
2855 
2856 		/* We don't have screen maps, so return a handcrafted one. */
2857 		for (i = 0; i < 256; i++)
2858 			sm->scrmap[i] = i;
2859 		return (0);
2860 	}
2861 	case KDSETMODE:
2862 		/*
2863 		 * FIXME: This implementation is incomplete compared to
2864 		 * syscons.
2865 		 */
2866 		switch (*(int *)data) {
2867 		case KD_TEXT:
2868 		case KD_TEXT1:
2869 		case KD_PIXEL:
2870 			vw->vw_flags &= ~VWF_GRAPHICS;
2871 			break;
2872 		case KD_GRAPHICS:
2873 			vw->vw_flags |= VWF_GRAPHICS;
2874 			break;
2875 		}
2876 		return (0);
2877 	case KDENABIO:		/* allow io operations */
2878 		error = priv_check(td, PRIV_IO);
2879 		if (error != 0)
2880 			return (error);
2881 		error = securelevel_gt(td->td_ucred, 0);
2882 		if (error != 0)
2883 			return (error);
2884 #if defined(__i386__)
2885 		td->td_frame->tf_eflags |= PSL_IOPL;
2886 #elif defined(__amd64__)
2887 		td->td_frame->tf_rflags |= PSL_IOPL;
2888 #endif
2889 		return (0);
2890 	case KDDISABIO:		/* disallow io operations (default) */
2891 #if defined(__i386__)
2892 		td->td_frame->tf_eflags &= ~PSL_IOPL;
2893 #elif defined(__amd64__)
2894 		td->td_frame->tf_rflags &= ~PSL_IOPL;
2895 #endif
2896 		return (0);
2897 	case KDMKTONE:		/* sound the bell */
2898 		vtterm_beep(tm, *(u_int *)data);
2899 		return (0);
2900 	case KIOCSOUND:		/* make tone (*data) hz */
2901 		/* TODO */
2902 		return (0);
2903 	case CONS_SETKBD:	/* set the new keyboard */
2904 		mtx_lock(&Giant);
2905 		error = 0;
2906 		if (vd->vd_keyboard == NULL ||
2907 		    vd->vd_keyboard->kb_index != *(int *)data) {
2908 			kbd = kbd_get_keyboard(*(int *)data);
2909 			if (kbd == NULL) {
2910 				mtx_unlock(&Giant);
2911 				return (EINVAL);
2912 			}
2913 			i = kbd_allocate(kbd->kb_name, kbd->kb_unit,
2914 			    (void *)vd, vt_kbdevent, vd);
2915 			if (i >= 0) {
2916 				if ((kbd = vd->vd_keyboard) != NULL) {
2917 					vt_save_kbd_state(vd->vd_curwindow, kbd);
2918 					kbd_release(kbd, (void *)vd);
2919 				}
2920 				kbd = vd->vd_keyboard = kbd_get_keyboard(i);
2921 
2922 				vt_update_kbd_mode(vd->vd_curwindow, kbd);
2923 				vt_update_kbd_state(vd->vd_curwindow, kbd);
2924 			} else {
2925 				error = EPERM;	/* XXX */
2926 			}
2927 		}
2928 		mtx_unlock(&Giant);
2929 		return (error);
2930 	case CONS_RELKBD:	/* release the current keyboard */
2931 		mtx_lock(&Giant);
2932 		error = 0;
2933 		if ((kbd = vd->vd_keyboard) != NULL) {
2934 			vt_save_kbd_state(vd->vd_curwindow, kbd);
2935 			error = kbd_release(kbd, (void *)vd);
2936 			if (error == 0) {
2937 				vd->vd_keyboard = NULL;
2938 			}
2939 		}
2940 		mtx_unlock(&Giant);
2941 		return (error);
2942 	case VT_ACTIVATE: {
2943 		int win;
2944 		win = *(int *)data - 1;
2945 		DPRINTF(5, "%s%d: VT_ACTIVATE ttyv%d ", SC_DRIVER_NAME,
2946 		    VT_UNIT(vw), win);
2947 		if ((win >= VT_MAXWINDOWS) || (win < 0))
2948 			return (EINVAL);
2949 		return (vt_proc_window_switch(vd->vd_windows[win]));
2950 	}
2951 	case VT_GETACTIVE:
2952 		*(int *)data = vd->vd_curwindow->vw_number + 1;
2953 		return (0);
2954 	case VT_GETINDEX:
2955 		*(int *)data = vw->vw_number + 1;
2956 		return (0);
2957 	case VT_LOCKSWITCH:
2958 		/* TODO: Check current state, switching can be in progress. */
2959 		if ((*(int *)data) == 0x01)
2960 			vw->vw_flags |= VWF_VTYLOCK;
2961 		else if ((*(int *)data) == 0x02)
2962 			vw->vw_flags &= ~VWF_VTYLOCK;
2963 		else
2964 			return (EINVAL);
2965 		return (0);
2966 	case VT_OPENQRY:
2967 		VT_LOCK(vd);
2968 		for (i = 0; i < VT_MAXWINDOWS; i++) {
2969 			vw = vd->vd_windows[i];
2970 			if (vw == NULL)
2971 				continue;
2972 			if (!(vw->vw_flags & VWF_OPENED)) {
2973 				*(int *)data = vw->vw_number + 1;
2974 				VT_UNLOCK(vd);
2975 				return (0);
2976 			}
2977 		}
2978 		VT_UNLOCK(vd);
2979 		return (EINVAL);
2980 	case VT_WAITACTIVE: {
2981 		unsigned int idx;
2982 
2983 		error = 0;
2984 
2985 		idx = *(unsigned int *)data;
2986 		if (idx > VT_MAXWINDOWS)
2987 			return (EINVAL);
2988 		if (idx > 0)
2989 			vw = vd->vd_windows[idx - 1];
2990 
2991 		VT_LOCK(vd);
2992 		while (vd->vd_curwindow != vw && error == 0)
2993 			error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
2994 		VT_UNLOCK(vd);
2995 		return (error);
2996 	}
2997 	case VT_SETMODE: {	/* set screen switcher mode */
2998 		struct vt_mode *mode;
2999 		struct proc *p1;
3000 
3001 		mode = (struct vt_mode *)data;
3002 		DPRINTF(5, "%s%d: VT_SETMODE ", SC_DRIVER_NAME, VT_UNIT(vw));
3003 		if (vw->vw_smode.mode == VT_PROCESS) {
3004 			p1 = pfind(vw->vw_pid);
3005 			if (vw->vw_proc == p1 && vw->vw_proc != td->td_proc) {
3006 				if (p1)
3007 					PROC_UNLOCK(p1);
3008 				DPRINTF(5, "error EPERM\n");
3009 				return (EPERM);
3010 			}
3011 			if (p1)
3012 				PROC_UNLOCK(p1);
3013 		}
3014 		if (mode->mode == VT_AUTO) {
3015 			vw->vw_smode.mode = VT_AUTO;
3016 			vw->vw_proc = NULL;
3017 			vw->vw_pid = 0;
3018 			DPRINTF(5, "VT_AUTO, ");
3019 			if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
3020 				cnavailable(vw->vw_terminal->consdev, TRUE);
3021 			/* were we in the middle of the vty switching process? */
3022 			if (finish_vt_rel(vw, TRUE, &s) == 0)
3023 				DPRINTF(5, "reset WAIT_REL, ");
3024 			if (finish_vt_acq(vw) == 0)
3025 				DPRINTF(5, "reset WAIT_ACQ, ");
3026 			return (0);
3027 		} else if (mode->mode == VT_PROCESS) {
3028 			if (!ISSIGVALID(mode->relsig) ||
3029 			    !ISSIGVALID(mode->acqsig) ||
3030 			    !ISSIGVALID(mode->frsig)) {
3031 				DPRINTF(5, "error EINVAL\n");
3032 				return (EINVAL);
3033 			}
3034 			DPRINTF(5, "VT_PROCESS %d, ", td->td_proc->p_pid);
3035 			bcopy(data, &vw->vw_smode, sizeof(struct vt_mode));
3036 			vw->vw_proc = td->td_proc;
3037 			vw->vw_pid = vw->vw_proc->p_pid;
3038 			if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
3039 				cnavailable(vw->vw_terminal->consdev, FALSE);
3040 		} else {
3041 			DPRINTF(5, "VT_SETMODE failed, unknown mode %d\n",
3042 			    mode->mode);
3043 			return (EINVAL);
3044 		}
3045 		DPRINTF(5, "\n");
3046 		return (0);
3047 	}
3048 	case VT_GETMODE:	/* get screen switcher mode */
3049 		bcopy(&vw->vw_smode, data, sizeof(struct vt_mode));
3050 		return (0);
3051 
3052 	case VT_RELDISP:	/* screen switcher ioctl */
3053 		/*
3054 		 * This must be the current vty which is in the VT_PROCESS
3055 		 * switching mode...
3056 		 */
3057 		if ((vw != vd->vd_curwindow) || (vw->vw_smode.mode !=
3058 		    VT_PROCESS)) {
3059 			return (EINVAL);
3060 		}
3061 		/* ...and this process is controlling it. */
3062 		if (vw->vw_proc != td->td_proc) {
3063 			return (EPERM);
3064 		}
3065 		error = EINVAL;
3066 		switch(*(int *)data) {
3067 		case VT_FALSE:	/* user refuses to release screen, abort */
3068 			if ((error = finish_vt_rel(vw, FALSE, &s)) == 0)
3069 				DPRINTF(5, "%s%d: VT_RELDISP: VT_FALSE\n",
3070 				    SC_DRIVER_NAME, VT_UNIT(vw));
3071 			break;
3072 		case VT_TRUE:	/* user has released screen, go on */
3073 			/* finish_vt_rel(..., TRUE, ...) should not be locked */
3074 			if (vw->vw_flags & VWF_SWWAIT_REL) {
3075 				if ((error = finish_vt_rel(vw, TRUE, &s)) == 0)
3076 					DPRINTF(5, "%s%d: VT_RELDISP: VT_TRUE\n",
3077 					    SC_DRIVER_NAME, VT_UNIT(vw));
3078 			} else {
3079 				error = EINVAL;
3080 			}
3081 			return (error);
3082 		case VT_ACKACQ:	/* acquire acknowledged, switch completed */
3083 			if ((error = finish_vt_acq(vw)) == 0)
3084 				DPRINTF(5, "%s%d: VT_RELDISP: VT_ACKACQ\n",
3085 				    SC_DRIVER_NAME, VT_UNIT(vw));
3086 			break;
3087 		default:
3088 			break;
3089 		}
3090 		return (error);
3091 	}
3092 
3093 	return (ENOIOCTL);
3094 }
3095 
3096 static struct vt_window *
3097 vt_allocate_window(struct vt_device *vd, unsigned int window)
3098 {
3099 	struct vt_window *vw;
3100 	struct terminal *tm;
3101 	term_pos_t size;
3102 	struct winsize wsz;
3103 
3104 	vw = malloc(sizeof *vw, M_VT, M_WAITOK|M_ZERO);
3105 	vw->vw_device = vd;
3106 	vw->vw_number = window;
3107 	vw->vw_kbdmode = K_XLATE;
3108 
3109 	if ((vd->vd_flags & VDF_TEXTMODE) == 0) {
3110 		vw->vw_font = vtfont_ref(vt_font_assigned);
3111 		vt_compute_drawable_area(vw);
3112 	}
3113 
3114 	vt_termsize(vd, vw->vw_font, &size);
3115 	vt_winsize(vd, vw->vw_font, &wsz);
3116 	tm = vw->vw_terminal = terminal_alloc(&vt_termclass, vw);
3117 	vw->vw_buf.vb_terminal = tm;	/* must be set before vtbuf_init() */
3118 	vtbuf_init(&vw->vw_buf, &size);
3119 
3120 	terminal_set_winsize(tm, &wsz);
3121 	vd->vd_windows[window] = vw;
3122 	TIMEOUT_TASK_INIT(taskqueue_thread, &vw->vw_timeout_task_dead, 0, &vt_switch_timer, vw);
3123 
3124 	return (vw);
3125 }
3126 
3127 void
3128 vt_upgrade(struct vt_device *vd)
3129 {
3130 	struct vt_window *vw;
3131 	unsigned int i;
3132 	int register_handlers;
3133 
3134 	if (!vty_enabled(VTY_VT))
3135 		return;
3136 	if (main_vd->vd_driver == NULL)
3137 		return;
3138 
3139 	for (i = 0; i < VT_MAXWINDOWS; i++) {
3140 		vw = vd->vd_windows[i];
3141 		if (vw == NULL) {
3142 			/* New window. */
3143 			vw = vt_allocate_window(vd, i);
3144 		}
3145 		if (!(vw->vw_flags & VWF_READY)) {
3146 			TIMEOUT_TASK_INIT(taskqueue_thread, &vw->vw_timeout_task_dead, 0, &vt_switch_timer, vw);
3147 			terminal_maketty(vw->vw_terminal, "v%r", VT_UNIT(vw));
3148 			vw->vw_flags |= VWF_READY;
3149 			if (vw->vw_flags & VWF_CONSOLE) {
3150 				/* For existing console window. */
3151 				EVENTHANDLER_REGISTER(shutdown_pre_sync,
3152 				    vt_window_switch, vw, SHUTDOWN_PRI_DEFAULT);
3153 			}
3154 		}
3155 	}
3156 	VT_LOCK(vd);
3157 	if (vd->vd_curwindow == NULL)
3158 		vd->vd_curwindow = vd->vd_windows[VT_CONSWINDOW];
3159 
3160 	register_handlers = 0;
3161 	if (!(vd->vd_flags & VDF_ASYNC)) {
3162 		/* Attach keyboard. */
3163 		vt_allocate_keyboard(vd);
3164 
3165 		/* Init 25 Hz timer. */
3166 		callout_init_mtx(&vd->vd_timer, &vd->vd_lock, 0);
3167 
3168 		/*
3169 		 * Start timer when everything ready.
3170 		 * Note that the operations here are purposefully ordered.
3171 		 * We need to ensure vd_timer_armed is non-zero before we set
3172 		 * the VDF_ASYNC flag. That prevents this function from
3173 		 * racing with vt_resume_flush_timer() to update the
3174 		 * callout structure.
3175 		 */
3176 		atomic_add_acq_int(&vd->vd_timer_armed, 1);
3177 		vd->vd_flags |= VDF_ASYNC;
3178 		callout_reset(&vd->vd_timer, hz / VT_TIMERFREQ, vt_timer, vd);
3179 		register_handlers = 1;
3180 	}
3181 
3182 	VT_UNLOCK(vd);
3183 
3184 	/* Refill settings with new sizes. */
3185 	vt_resize(vd);
3186 
3187 	if (register_handlers) {
3188 		/* Register suspend/resume handlers. */
3189 		EVENTHANDLER_REGISTER(power_suspend_early, vt_suspend_handler,
3190 		    vd, EVENTHANDLER_PRI_ANY);
3191 		EVENTHANDLER_REGISTER(power_resume, vt_resume_handler, vd,
3192 		    EVENTHANDLER_PRI_ANY);
3193 	}
3194 }
3195 
3196 static void
3197 vt_resize(struct vt_device *vd)
3198 {
3199 	struct vt_window *vw;
3200 	int i;
3201 
3202 	for (i = 0; i < VT_MAXWINDOWS; i++) {
3203 		vw = vd->vd_windows[i];
3204 		VT_LOCK(vd);
3205 		/* Assign default font to window, if not textmode. */
3206 		if (!(vd->vd_flags & VDF_TEXTMODE) && vw->vw_font == NULL)
3207 			vw->vw_font = vtfont_ref(vt_font_assigned);
3208 		VT_UNLOCK(vd);
3209 
3210 		/* Resize terminal windows */
3211 		while (vt_change_font(vw, vw->vw_font) == EBUSY) {
3212 			DPRINTF(100, "%s: vt_change_font() is busy, "
3213 			    "window %d\n", __func__, i);
3214 		}
3215 	}
3216 }
3217 
3218 static void
3219 vt_replace_backend(const struct vt_driver *drv, void *softc)
3220 {
3221 	struct vt_device *vd;
3222 
3223 	vd = main_vd;
3224 
3225 	if (vd->vd_flags & VDF_ASYNC) {
3226 		/* Stop vt_flush periodic task. */
3227 		VT_LOCK(vd);
3228 		vt_suspend_flush_timer(vd);
3229 		VT_UNLOCK(vd);
3230 		/*
3231 		 * Mute current terminal until we done. vt_change_font (called
3232 		 * from vt_resize) will unmute it.
3233 		 */
3234 		terminal_mute(vd->vd_curwindow->vw_terminal, 1);
3235 	}
3236 
3237 	/*
3238 	 * Reset VDF_TEXTMODE flag, driver who require that flag (vt_vga) will
3239 	 * set it.
3240 	 */
3241 	VT_LOCK(vd);
3242 	vd->vd_flags &= ~VDF_TEXTMODE;
3243 
3244 	if (drv != NULL) {
3245 		/*
3246 		 * We want to upgrade from the current driver to the
3247 		 * given driver.
3248 		 */
3249 
3250 		vd->vd_prev_driver = vd->vd_driver;
3251 		vd->vd_prev_softc = vd->vd_softc;
3252 		vd->vd_driver = drv;
3253 		vd->vd_softc = softc;
3254 
3255 		vd->vd_driver->vd_init(vd);
3256 	} else if (vd->vd_prev_driver != NULL && vd->vd_prev_softc != NULL) {
3257 		/*
3258 		 * No driver given: we want to downgrade to the previous
3259 		 * driver.
3260 		 */
3261 		const struct vt_driver *old_drv;
3262 		void *old_softc;
3263 
3264 		old_drv = vd->vd_driver;
3265 		old_softc = vd->vd_softc;
3266 
3267 		vd->vd_driver = vd->vd_prev_driver;
3268 		vd->vd_softc = vd->vd_prev_softc;
3269 		vd->vd_prev_driver = NULL;
3270 		vd->vd_prev_softc = NULL;
3271 
3272 		vd->vd_flags |= VDF_DOWNGRADE;
3273 
3274 		vd->vd_driver->vd_init(vd);
3275 
3276 		if (old_drv->vd_fini)
3277 			old_drv->vd_fini(vd, old_softc);
3278 
3279 		vd->vd_flags &= ~VDF_DOWNGRADE;
3280 	}
3281 
3282 	VT_UNLOCK(vd);
3283 
3284 	/* Update windows sizes and initialize last items. */
3285 	vt_upgrade(vd);
3286 
3287 #ifdef DEV_SPLASH
3288 	if (vd->vd_flags & VDF_SPLASH)
3289 		vtterm_splash(vd);
3290 #endif
3291 
3292 	if (vd->vd_flags & VDF_ASYNC) {
3293 		/* Allow to put chars now. */
3294 		terminal_mute(vd->vd_curwindow->vw_terminal, 0);
3295 		/* Rerun timer for screen updates. */
3296 		vt_resume_flush_timer(vd->vd_curwindow, 0);
3297 	}
3298 
3299 	/*
3300 	 * Register as console. If it already registered, cnadd() will ignore
3301 	 * it.
3302 	 */
3303 	termcn_cnregister(vd->vd_windows[VT_CONSWINDOW]->vw_terminal);
3304 }
3305 
3306 static void
3307 vt_suspend_handler(void *priv)
3308 {
3309 	struct vt_device *vd;
3310 
3311 	vd = priv;
3312 	vd->vd_flags |= VDF_SUSPENDED;
3313 	if (vd->vd_driver != NULL && vd->vd_driver->vd_suspend != NULL)
3314 		vd->vd_driver->vd_suspend(vd);
3315 }
3316 
3317 static void
3318 vt_resume_handler(void *priv)
3319 {
3320 	struct vt_device *vd;
3321 
3322 	vd = priv;
3323 	if (vd->vd_driver != NULL && vd->vd_driver->vd_resume != NULL)
3324 		vd->vd_driver->vd_resume(vd);
3325 	vd->vd_flags &= ~VDF_SUSPENDED;
3326 }
3327 
3328 int
3329 vt_allocate(const struct vt_driver *drv, void *softc)
3330 {
3331 
3332 	if (!vty_enabled(VTY_VT))
3333 		return (EINVAL);
3334 
3335 	if (main_vd->vd_driver == NULL) {
3336 		main_vd->vd_driver = drv;
3337 		printf("VT: initialize with new VT driver \"%s\".\n",
3338 		    drv->vd_name);
3339 	} else {
3340 		/*
3341 		 * Check if have rights to replace current driver. For example:
3342 		 * it is bad idea to replace KMS driver with generic VGA one.
3343 		 */
3344 		if (drv->vd_priority <= main_vd->vd_driver->vd_priority) {
3345 			printf("VT: Driver priority %d too low. Current %d\n ",
3346 			    drv->vd_priority, main_vd->vd_driver->vd_priority);
3347 			return (EEXIST);
3348 		}
3349 		printf("VT: Replacing driver \"%s\" with new \"%s\".\n",
3350 		    main_vd->vd_driver->vd_name, drv->vd_name);
3351 	}
3352 
3353 	vt_replace_backend(drv, softc);
3354 
3355 	return (0);
3356 }
3357 
3358 int
3359 vt_deallocate(const struct vt_driver *drv, void *softc)
3360 {
3361 
3362 	if (!vty_enabled(VTY_VT))
3363 		return (EINVAL);
3364 
3365 	if (main_vd->vd_prev_driver == NULL ||
3366 	    main_vd->vd_driver != drv ||
3367 	    main_vd->vd_softc != softc)
3368 		return (EPERM);
3369 
3370 	printf("VT: Switching back from \"%s\" to \"%s\".\n",
3371 	    main_vd->vd_driver->vd_name, main_vd->vd_prev_driver->vd_name);
3372 
3373 	vt_replace_backend(NULL, NULL);
3374 
3375 	return (0);
3376 }
3377 
3378 void
3379 vt_suspend(struct vt_device *vd)
3380 {
3381 	int error;
3382 
3383 	if (vt_suspendswitch == 0)
3384 		return;
3385 	/* Save current window. */
3386 	vd->vd_savedwindow = vd->vd_curwindow;
3387 	/* Ask holding process to free window and switch to console window */
3388 	vt_proc_window_switch(vd->vd_windows[VT_CONSWINDOW]);
3389 
3390 	/* Wait for the window switch to complete. */
3391 	error = 0;
3392 	VT_LOCK(vd);
3393 	while (vd->vd_curwindow != vd->vd_windows[VT_CONSWINDOW] && error == 0)
3394 		error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
3395 	VT_UNLOCK(vd);
3396 }
3397 
3398 void
3399 vt_resume(struct vt_device *vd)
3400 {
3401 
3402 	if (vt_suspendswitch == 0)
3403 		return;
3404 	/* Switch back to saved window, if any */
3405 	vt_proc_window_switch(vd->vd_savedwindow);
3406 	vd->vd_savedwindow = NULL;
3407 }
3408