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