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