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