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