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