]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/vt/vt_core.c
ZFS: MFV 2.0-rc1-ga00c61
[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
1426                 top = (vd->vd_height - vt_logo_height) / 2;
1427                 left = (vd->vd_width - vt_logo_width) / 2;
1428                 switch (vt_logo_depth) {
1429                 case 1:
1430                         /* XXX: Unhardcode colors! */
1431                         vd->vd_driver->vd_bitblt_bmp(vd, vd->vd_curwindow,
1432                             vt_logo_image, NULL, vt_logo_width, vt_logo_height,
1433                             left, top, TC_WHITE, TC_BLACK);
1434                 }
1435                 vd->vd_flags |= VDF_SPLASH;
1436         }
1437 }
1438 #endif
1439
1440
1441 static void
1442 vtterm_cnprobe(struct terminal *tm, struct consdev *cp)
1443 {
1444         struct vt_driver *vtd, **vtdlist, *vtdbest = NULL;
1445         struct vt_window *vw = tm->tm_softc;
1446         struct vt_device *vd = vw->vw_device;
1447         struct winsize wsz;
1448         const term_attr_t *a;
1449
1450         if (!vty_enabled(VTY_VT))
1451                 return;
1452
1453         if (vd->vd_flags & VDF_INITIALIZED)
1454                 /* Initialization already done. */
1455                 return;
1456
1457         SET_FOREACH(vtdlist, vt_drv_set) {
1458                 vtd = *vtdlist;
1459                 if (vtd->vd_probe == NULL)
1460                         continue;
1461                 if (vtd->vd_probe(vd) == CN_DEAD)
1462                         continue;
1463                 if ((vtdbest == NULL) ||
1464                     (vtd->vd_priority > vtdbest->vd_priority))
1465                         vtdbest = vtd;
1466         }
1467         if (vtdbest == NULL) {
1468                 cp->cn_pri = CN_DEAD;
1469                 vd->vd_flags |= VDF_DEAD;
1470         } else {
1471                 vd->vd_driver = vtdbest;
1472                 cp->cn_pri = vd->vd_driver->vd_init(vd);
1473         }
1474
1475         /* Check if driver's vt_init return CN_DEAD. */
1476         if (cp->cn_pri == CN_DEAD) {
1477                 vd->vd_flags |= VDF_DEAD;
1478         }
1479
1480         /* Initialize any early-boot keyboard drivers */
1481         kbd_configure(KB_CONF_PROBE_ONLY);
1482
1483         vd->vd_unit = atomic_fetchadd_int(&vt_unit, 1);
1484         vd->vd_windows[VT_CONSWINDOW] = vw;
1485         sprintf(cp->cn_name, "ttyv%r", VT_UNIT(vw));
1486
1487         /* Attach default font if not in TEXTMODE. */
1488         if ((vd->vd_flags & VDF_TEXTMODE) == 0) {
1489                 vw->vw_font = vtfont_ref(&vt_font_default);
1490                 vt_compute_drawable_area(vw);
1491         }
1492
1493         /*
1494          * The original screen size was faked (_VTDEFW x _VTDEFH). Now
1495          * that we have the real viewable size, fix it in the static
1496          * buffer.
1497          */
1498         if (vd->vd_width != 0 && vd->vd_height != 0)
1499                 vt_termsize(vd, vw->vw_font, &vw->vw_buf.vb_scr_size);
1500
1501         /* We need to access terminal attributes from vtbuf */
1502         vw->vw_buf.vb_terminal = tm;
1503         vtbuf_init_early(&vw->vw_buf);
1504         vt_winsize(vd, vw->vw_font, &wsz);
1505         a = teken_get_curattr(&tm->tm_emulator);
1506         terminal_set_winsize_blank(tm, &wsz, 1, a);
1507
1508         if (vtdbest != NULL) {
1509 #ifdef DEV_SPLASH
1510                 if (!vt_splash_cpu)
1511                         vtterm_splash(vd);
1512 #endif
1513                 vd->vd_flags |= VDF_INITIALIZED;
1514         }
1515 }
1516
1517 static int
1518 vtterm_cngetc(struct terminal *tm)
1519 {
1520         struct vt_window *vw = tm->tm_softc;
1521         struct vt_device *vd = vw->vw_device;
1522         keyboard_t *kbd;
1523         u_int c;
1524
1525         if (vw->vw_kbdsq && *vw->vw_kbdsq)
1526                 return (*vw->vw_kbdsq++);
1527
1528         /* Make sure the splash screen is not there. */
1529         if (vd->vd_flags & VDF_SPLASH) {
1530                 /* Remove splash */
1531                 vd->vd_flags &= ~VDF_SPLASH;
1532                 /* Mark screen as invalid to force update */
1533                 vd->vd_flags |= VDF_INVALID;
1534                 vt_flush(vd);
1535         }
1536
1537         /* Stripped down keyboard handler. */
1538         if ((kbd = vd->vd_keyboard) == NULL)
1539                 return (-1);
1540
1541         /* Force keyboard input mode to K_XLATE */
1542         vw->vw_kbdmode = K_XLATE;
1543         vt_update_kbd_mode(vw, kbd);
1544
1545         /* Switch the keyboard to polling to make it work here. */
1546         kbdd_poll(kbd, TRUE);
1547         c = kbdd_read_char(kbd, 0);
1548         kbdd_poll(kbd, FALSE);
1549         if (c & RELKEY)
1550                 return (-1);
1551
1552         if (vw->vw_flags & VWF_SCROLL) {
1553                 vt_scrollmode_kbdevent(vw, c, 1/* Console mode */);
1554                 vt_flush(vd);
1555                 return (-1);
1556         }
1557
1558         /* Stripped down handling of vt_kbdevent(), without locking, etc. */
1559         if (c & SPCLKEY) {
1560                 switch (c) {
1561                 case SPCLKEY | SLK:
1562                         vt_save_kbd_state(vw, kbd);
1563                         if (vw->vw_kbdstate & SLKED) {
1564                                 /* Turn scrolling on. */
1565                                 vw->vw_flags |= VWF_SCROLL;
1566                                 VTBUF_SLCK_ENABLE(&vw->vw_buf);
1567                         } else {
1568                                 /* Turn scrolling off. */
1569                                 vt_scroll(vw, 0, VHS_END);
1570                                 vw->vw_flags &= ~VWF_SCROLL;
1571                                 VTBUF_SLCK_DISABLE(&vw->vw_buf);
1572                         }
1573                         break;
1574                 /* XXX: KDB can handle history. */
1575                 case SPCLKEY | FKEY | F(50): /* Arrow up. */
1576                         vw->vw_kbdsq = "\x1b[A";
1577                         break;
1578                 case SPCLKEY | FKEY | F(58): /* Arrow down. */
1579                         vw->vw_kbdsq = "\x1b[B";
1580                         break;
1581                 case SPCLKEY | FKEY | F(55): /* Arrow right. */
1582                         vw->vw_kbdsq = "\x1b[C";
1583                         break;
1584                 case SPCLKEY | FKEY | F(53): /* Arrow left. */
1585                         vw->vw_kbdsq = "\x1b[D";
1586                         break;
1587                 }
1588
1589                 /* Force refresh to make scrollback work. */
1590                 vt_flush(vd);
1591         } else if (KEYFLAGS(c) == 0) {
1592                 return (KEYCHAR(c));
1593         }
1594
1595         if (vw->vw_kbdsq && *vw->vw_kbdsq)
1596                 return (*vw->vw_kbdsq++);
1597
1598         return (-1);
1599 }
1600
1601 static void
1602 vtterm_cngrab(struct terminal *tm)
1603 {
1604         struct vt_device *vd;
1605         struct vt_window *vw;
1606         keyboard_t *kbd;
1607
1608         vw = tm->tm_softc;
1609         vd = vw->vw_device;
1610
1611         if (!cold)
1612                 vt_window_switch(vw);
1613
1614         if ((kbd = vd->vd_keyboard) == NULL)
1615                 return;
1616
1617         if (vw->vw_grabbed++ > 0)
1618                 return;
1619
1620         /*
1621          * Make sure the keyboard is accessible even when the kbd device
1622          * driver is disabled.
1623          */
1624         kbdd_enable(kbd);
1625
1626         /* We shall always use the keyboard in the XLATE mode here. */
1627         vw->vw_prev_kbdmode = vw->vw_kbdmode;
1628         vw->vw_kbdmode = K_XLATE;
1629         vt_update_kbd_mode(vw, kbd);
1630
1631         kbdd_poll(kbd, TRUE);
1632 }
1633
1634 static void
1635 vtterm_cnungrab(struct terminal *tm)
1636 {
1637         struct vt_device *vd;
1638         struct vt_window *vw;
1639         keyboard_t *kbd;
1640
1641         vw = tm->tm_softc;
1642         vd = vw->vw_device;
1643
1644         if ((kbd = vd->vd_keyboard) == NULL)
1645                 return;
1646
1647         if (--vw->vw_grabbed > 0)
1648                 return;
1649
1650         kbdd_poll(kbd, FALSE);
1651
1652         vw->vw_kbdmode = vw->vw_prev_kbdmode;
1653         vt_update_kbd_mode(vw, kbd);
1654         kbdd_disable(kbd);
1655 }
1656
1657 static void
1658 vtterm_opened(struct terminal *tm, int opened)
1659 {
1660         struct vt_window *vw = tm->tm_softc;
1661         struct vt_device *vd = vw->vw_device;
1662
1663         VT_LOCK(vd);
1664         vd->vd_flags &= ~VDF_SPLASH;
1665         if (opened)
1666                 vw->vw_flags |= VWF_OPENED;
1667         else {
1668                 vw->vw_flags &= ~VWF_OPENED;
1669                 /* TODO: finish ACQ/REL */
1670         }
1671         VT_UNLOCK(vd);
1672 }
1673
1674 static int
1675 vt_change_font(struct vt_window *vw, struct vt_font *vf)
1676 {
1677         struct vt_device *vd = vw->vw_device;
1678         struct terminal *tm = vw->vw_terminal;
1679         term_pos_t size;
1680         struct winsize wsz;
1681
1682         /*
1683          * Changing fonts.
1684          *
1685          * Changing fonts is a little tricky.  We must prevent
1686          * simultaneous access to the device, so we must stop
1687          * the display timer and the terminal from accessing.
1688          * We need to switch fonts and grow our screen buffer.
1689          *
1690          * XXX: Right now the code uses terminal_mute() to
1691          * prevent data from reaching the console driver while
1692          * resizing the screen buffer.  This isn't elegant...
1693          */
1694
1695         VT_LOCK(vd);
1696         if (vw->vw_flags & VWF_BUSY) {
1697                 /* Another process is changing the font. */
1698                 VT_UNLOCK(vd);
1699                 return (EBUSY);
1700         }
1701         vw->vw_flags |= VWF_BUSY;
1702         VT_UNLOCK(vd);
1703
1704         vt_termsize(vd, vf, &size);
1705         vt_winsize(vd, vf, &wsz);
1706
1707         /* Grow the screen buffer and terminal. */
1708         terminal_mute(tm, 1);
1709         vtbuf_grow(&vw->vw_buf, &size, vw->vw_buf.vb_history_size);
1710         terminal_set_winsize_blank(tm, &wsz, 0, NULL);
1711         terminal_set_cursor(tm, &vw->vw_buf.vb_cursor);
1712         terminal_mute(tm, 0);
1713
1714         /* Actually apply the font to the current window. */
1715         VT_LOCK(vd);
1716         if (vw->vw_font != vf && vw->vw_font != NULL && vf != NULL) {
1717                 /*
1718                  * In case vt_change_font called to update size we don't need
1719                  * to update font link.
1720                  */
1721                 vtfont_unref(vw->vw_font);
1722                 vw->vw_font = vtfont_ref(vf);
1723         }
1724
1725         /*
1726          * Compute the drawable area and move the mouse cursor inside
1727          * it, in case the new area is smaller than the previous one.
1728          */
1729         vt_compute_drawable_area(vw);
1730         vd->vd_mx = min(vd->vd_mx,
1731             vw->vw_draw_area.tr_end.tp_col -
1732             vw->vw_draw_area.tr_begin.tp_col - 1);
1733         vd->vd_my = min(vd->vd_my,
1734             vw->vw_draw_area.tr_end.tp_row -
1735             vw->vw_draw_area.tr_begin.tp_row - 1);
1736
1737         /* Force a full redraw the next timer tick. */
1738         if (vd->vd_curwindow == vw) {
1739                 vd->vd_flags |= VDF_INVALID;
1740                 vt_resume_flush_timer(vw, 0);
1741         }
1742         vw->vw_flags &= ~VWF_BUSY;
1743         VT_UNLOCK(vd);
1744         return (0);
1745 }
1746
1747 static int
1748 vt_proc_alive(struct vt_window *vw)
1749 {
1750         struct proc *p;
1751
1752         if (vw->vw_smode.mode != VT_PROCESS)
1753                 return (FALSE);
1754
1755         if (vw->vw_proc) {
1756                 if ((p = pfind(vw->vw_pid)) != NULL)
1757                         PROC_UNLOCK(p);
1758                 if (vw->vw_proc == p)
1759                         return (TRUE);
1760                 vw->vw_proc = NULL;
1761                 vw->vw_smode.mode = VT_AUTO;
1762                 DPRINTF(1, "vt controlling process %d died\n", vw->vw_pid);
1763                 vw->vw_pid = 0;
1764         }
1765         return (FALSE);
1766 }
1767
1768 static int
1769 signal_vt_rel(struct vt_window *vw)
1770 {
1771
1772         if (vw->vw_smode.mode != VT_PROCESS)
1773                 return (FALSE);
1774         if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
1775                 vw->vw_proc = NULL;
1776                 vw->vw_pid = 0;
1777                 return (TRUE);
1778         }
1779         vw->vw_flags |= VWF_SWWAIT_REL;
1780         PROC_LOCK(vw->vw_proc);
1781         kern_psignal(vw->vw_proc, vw->vw_smode.relsig);
1782         PROC_UNLOCK(vw->vw_proc);
1783         DPRINTF(1, "sending relsig to %d\n", vw->vw_pid);
1784         return (TRUE);
1785 }
1786
1787 static int
1788 signal_vt_acq(struct vt_window *vw)
1789 {
1790
1791         if (vw->vw_smode.mode != VT_PROCESS)
1792                 return (FALSE);
1793         if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
1794                 cnavailable(vw->vw_terminal->consdev, FALSE);
1795         if (vw->vw_proc == NULL || vt_proc_alive(vw) == FALSE) {
1796                 vw->vw_proc = NULL;
1797                 vw->vw_pid = 0;
1798                 return (TRUE);
1799         }
1800         vw->vw_flags |= VWF_SWWAIT_ACQ;
1801         PROC_LOCK(vw->vw_proc);
1802         kern_psignal(vw->vw_proc, vw->vw_smode.acqsig);
1803         PROC_UNLOCK(vw->vw_proc);
1804         DPRINTF(1, "sending acqsig to %d\n", vw->vw_pid);
1805         return (TRUE);
1806 }
1807
1808 static int
1809 finish_vt_rel(struct vt_window *vw, int release, int *s)
1810 {
1811
1812         if (vw->vw_flags & VWF_SWWAIT_REL) {
1813                 vw->vw_flags &= ~VWF_SWWAIT_REL;
1814                 if (release) {
1815                         callout_drain(&vw->vw_proc_dead_timer);
1816                         (void)vt_late_window_switch(vw->vw_switch_to);
1817                 }
1818                 return (0);
1819         }
1820         return (EINVAL);
1821 }
1822
1823 static int
1824 finish_vt_acq(struct vt_window *vw)
1825 {
1826
1827         if (vw->vw_flags & VWF_SWWAIT_ACQ) {
1828                 vw->vw_flags &= ~VWF_SWWAIT_ACQ;
1829                 return (0);
1830         }
1831         return (EINVAL);
1832 }
1833
1834 #ifndef SC_NO_CUTPASTE
1835 static void
1836 vt_mouse_terminput_button(struct vt_device *vd, int button)
1837 {
1838         struct vt_window *vw;
1839         struct vt_font *vf;
1840         char mouseb[6] = "\x1B[M";
1841         int i, x, y;
1842
1843         vw = vd->vd_curwindow;
1844         vf = vw->vw_font;
1845
1846         /* Translate to char position. */
1847         x = vd->vd_mx / vf->vf_width;
1848         y = vd->vd_my / vf->vf_height;
1849         /* Avoid overflow. */
1850         x = MIN(x, 255 - '!');
1851         y = MIN(y, 255 - '!');
1852
1853         mouseb[3] = ' ' + button;
1854         mouseb[4] = '!' + x;
1855         mouseb[5] = '!' + y;
1856
1857         for (i = 0; i < sizeof(mouseb); i++)
1858                 terminal_input_char(vw->vw_terminal, mouseb[i]);
1859 }
1860
1861 static void
1862 vt_mouse_terminput(struct vt_device *vd, int type, int x, int y, int event,
1863     int cnt)
1864 {
1865
1866         switch (type) {
1867         case MOUSE_BUTTON_EVENT:
1868                 if (cnt > 0) {
1869                         /* Mouse button pressed. */
1870                         if (event & MOUSE_BUTTON1DOWN)
1871                                 vt_mouse_terminput_button(vd, 0);
1872                         if (event & MOUSE_BUTTON2DOWN)
1873                                 vt_mouse_terminput_button(vd, 1);
1874                         if (event & MOUSE_BUTTON3DOWN)
1875                                 vt_mouse_terminput_button(vd, 2);
1876                 } else {
1877                         /* Mouse button released. */
1878                         vt_mouse_terminput_button(vd, 3);
1879                 }
1880                 break;
1881 #ifdef notyet
1882         case MOUSE_MOTION_EVENT:
1883                 if (mouse->u.data.z < 0) {
1884                         /* Scroll up. */
1885                         sc_mouse_input_button(vd, 64);
1886                 } else if (mouse->u.data.z > 0) {
1887                         /* Scroll down. */
1888                         sc_mouse_input_button(vd, 65);
1889                 }
1890                 break;
1891 #endif
1892         }
1893 }
1894
1895 static void
1896 vt_mouse_paste()
1897 {
1898         term_char_t *buf;
1899         int i, len;
1900
1901         len = VD_PASTEBUFLEN(main_vd);
1902         buf = VD_PASTEBUF(main_vd);
1903         len /= sizeof(term_char_t);
1904         for (i = 0; i < len; i++) {
1905                 if (buf[i] == '\0')
1906                         continue;
1907                 terminal_input_char(main_vd->vd_curwindow->vw_terminal,
1908                     buf[i]);
1909         }
1910 }
1911
1912 void
1913 vt_mouse_event(int type, int x, int y, int event, int cnt, int mlevel)
1914 {
1915         struct vt_device *vd;
1916         struct vt_window *vw;
1917         struct vt_font *vf;
1918         term_pos_t size;
1919         int len, mark;
1920
1921         vd = main_vd;
1922         vw = vd->vd_curwindow;
1923         vf = vw->vw_font;
1924         mark = 0;
1925
1926         if (vw->vw_flags & (VWF_MOUSE_HIDE | VWF_GRAPHICS))
1927                 /*
1928                  * Either the mouse is disabled, or the window is in
1929                  * "graphics mode". The graphics mode is usually set by
1930                  * an X server, using the KDSETMODE ioctl.
1931                  */
1932                 return;
1933
1934         if (vf == NULL) /* Text mode. */
1935                 return;
1936
1937         /*
1938          * TODO: add flag about pointer position changed, to not redraw chars
1939          * under mouse pointer when nothing changed.
1940          */
1941
1942         if (vw->vw_mouse_level > 0)
1943                 vt_mouse_terminput(vd, type, x, y, event, cnt);
1944
1945         switch (type) {
1946         case MOUSE_ACTION:
1947         case MOUSE_MOTION_EVENT:
1948                 /* Movement */
1949                 x += vd->vd_mx;
1950                 y += vd->vd_my;
1951
1952                 vt_termsize(vd, vf, &size);
1953
1954                 /* Apply limits. */
1955                 x = MAX(x, 0);
1956                 y = MAX(y, 0);
1957                 x = MIN(x, (size.tp_col * vf->vf_width) - 1);
1958                 y = MIN(y, (size.tp_row * vf->vf_height) - 1);
1959
1960                 vd->vd_mx = x;
1961                 vd->vd_my = y;
1962                 if (vd->vd_mstate & MOUSE_BUTTON1DOWN)
1963                         vtbuf_set_mark(&vw->vw_buf, VTB_MARK_MOVE,
1964                             vd->vd_mx / vf->vf_width,
1965                             vd->vd_my / vf->vf_height);
1966
1967                 vt_resume_flush_timer(vw, 0);
1968                 return; /* Done */
1969         case MOUSE_BUTTON_EVENT:
1970                 /* Buttons */
1971                 break;
1972         default:
1973                 return; /* Done */
1974         }
1975
1976         switch (event) {
1977         case MOUSE_BUTTON1DOWN:
1978                 switch (cnt % 4) {
1979                 case 0: /* up */
1980                         mark = VTB_MARK_END;
1981                         break;
1982                 case 1: /* single click: start cut operation */
1983                         mark = VTB_MARK_START;
1984                         break;
1985                 case 2: /* double click: cut a word */
1986                         mark = VTB_MARK_WORD;
1987                         break;
1988                 case 3: /* triple click: cut a line */
1989                         mark = VTB_MARK_ROW;
1990                         break;
1991                 }
1992                 break;
1993         case VT_MOUSE_PASTEBUTTON:
1994                 switch (cnt) {
1995                 case 0: /* up */
1996                         break;
1997                 default:
1998                         vt_mouse_paste();
1999                         break;
2000                 }
2001                 return; /* Done */
2002         case VT_MOUSE_EXTENDBUTTON:
2003                 switch (cnt) {
2004                 case 0: /* up */
2005                         if (!(vd->vd_mstate & MOUSE_BUTTON1DOWN))
2006                                 mark = VTB_MARK_EXTEND;
2007                         else
2008                                 mark = 0;
2009                         break;
2010                 default:
2011                         mark = VTB_MARK_EXTEND;
2012                         break;
2013                 }
2014                 break;
2015         default:
2016                 return; /* Done */
2017         }
2018
2019         /* Save buttons state. */
2020         if (cnt > 0)
2021                 vd->vd_mstate |= event;
2022         else
2023                 vd->vd_mstate &= ~event;
2024
2025         if (vtbuf_set_mark(&vw->vw_buf, mark, vd->vd_mx / vf->vf_width,
2026             vd->vd_my / vf->vf_height) == 1) {
2027                 /*
2028                  * We have something marked to copy, so update pointer to
2029                  * window with selection.
2030                  */
2031                 vt_resume_flush_timer(vw, 0);
2032
2033                 switch (mark) {
2034                 case VTB_MARK_END:
2035                 case VTB_MARK_WORD:
2036                 case VTB_MARK_ROW:
2037                 case VTB_MARK_EXTEND:
2038                         break;
2039                 default:
2040                         /* Other types of mark do not require to copy data. */
2041                         return;
2042                 }
2043
2044                 /* Get current selection size in bytes. */
2045                 len = vtbuf_get_marked_len(&vw->vw_buf);
2046                 if (len <= 0)
2047                         return;
2048
2049                 /* Reallocate buffer only if old one is too small. */
2050                 if (len > VD_PASTEBUFSZ(vd)) {
2051                         VD_PASTEBUF(vd) = realloc(VD_PASTEBUF(vd), len, M_VT,
2052                             M_WAITOK | M_ZERO);
2053                         /* Update buffer size. */
2054                         VD_PASTEBUFSZ(vd) = len;
2055                 }
2056                 /* Request copy/paste buffer data, no more than `len' */
2057                 vtbuf_extract_marked(&vw->vw_buf, VD_PASTEBUF(vd),
2058                     VD_PASTEBUFSZ(vd));
2059
2060                 VD_PASTEBUFLEN(vd) = len;
2061
2062                 /* XXX VD_PASTEBUF(vd) have to be freed on shutdown/unload. */
2063         }
2064 }
2065
2066 void
2067 vt_mouse_state(int show)
2068 {
2069         struct vt_device *vd;
2070         struct vt_window *vw;
2071
2072         vd = main_vd;
2073         vw = vd->vd_curwindow;
2074
2075         switch (show) {
2076         case VT_MOUSE_HIDE:
2077                 vw->vw_flags |= VWF_MOUSE_HIDE;
2078                 break;
2079         case VT_MOUSE_SHOW:
2080                 vw->vw_flags &= ~VWF_MOUSE_HIDE;
2081                 break;
2082         }
2083
2084         /* Mark mouse position as dirty. */
2085         vt_mark_mouse_position_as_dirty(vd, false);
2086         vt_resume_flush_timer(vw, 0);
2087 }
2088 #endif
2089
2090 static int
2091 vtterm_mmap(struct terminal *tm, vm_ooffset_t offset, vm_paddr_t * paddr,
2092     int nprot, vm_memattr_t *memattr)
2093 {
2094         struct vt_window *vw = tm->tm_softc;
2095         struct vt_device *vd = vw->vw_device;
2096
2097         if (vd->vd_driver->vd_fb_mmap)
2098                 return (vd->vd_driver->vd_fb_mmap(vd, offset, paddr, nprot,
2099                     memattr));
2100
2101         return (ENXIO);
2102 }
2103
2104 static int
2105 vtterm_ioctl(struct terminal *tm, u_long cmd, caddr_t data,
2106     struct thread *td)
2107 {
2108         struct vt_window *vw = tm->tm_softc;
2109         struct vt_device *vd = vw->vw_device;
2110         keyboard_t *kbd;
2111         int error, i, s;
2112 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
2113     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
2114         int ival;
2115
2116         switch (cmd) {
2117         case _IO('v', 4):
2118                 cmd = VT_RELDISP;
2119                 break;
2120         case _IO('v', 5):
2121                 cmd = VT_ACTIVATE;
2122                 break;
2123         case _IO('v', 6):
2124                 cmd = VT_WAITACTIVE;
2125                 break;
2126         case _IO('K', 20):
2127                 cmd = KDSKBSTATE;
2128                 break;
2129         case _IO('K', 67):
2130                 cmd = KDSETRAD;
2131                 break;
2132         case _IO('K', 7):
2133                 cmd = KDSKBMODE;
2134                 break;
2135         case _IO('K', 8):
2136                 cmd = KDMKTONE;
2137                 break;
2138         case _IO('K', 10):
2139                 cmd = KDSETMODE;
2140                 break;
2141         case _IO('K', 13):
2142                 cmd = KDSBORDER;
2143                 break;
2144         case _IO('K', 63):
2145                 cmd = KIOCSOUND;
2146                 break;
2147         case _IO('K', 66):
2148                 cmd = KDSETLED;
2149                 break;
2150         case _IO('c', 104):
2151                 cmd = CONS_SETWINORG;
2152                 break;
2153         case _IO('c', 110):
2154                 cmd = CONS_SETKBD;
2155                 break;
2156         default:
2157                 goto skip_thunk;
2158         }
2159         ival = IOCPARM_IVAL(data);
2160         data = (caddr_t)&ival;
2161 skip_thunk:
2162 #endif
2163
2164         switch (cmd) {
2165         case KDSETRAD:          /* set keyboard repeat & delay rates (old) */
2166                 if (*(int *)data & ~0x7f)
2167                         return (EINVAL);
2168                 /* FALLTHROUGH */
2169         case GIO_KEYMAP:
2170         case PIO_KEYMAP:
2171         case GIO_DEADKEYMAP:
2172         case PIO_DEADKEYMAP:
2173         case GETFKEY:
2174         case SETFKEY:
2175         case KDGKBINFO:
2176         case KDGKBTYPE:
2177         case KDGETREPEAT:       /* get keyboard repeat & delay rates */
2178         case KDSETREPEAT:       /* set keyboard repeat & delay rates (new) */
2179         case KBADDKBD:          /* add/remove keyboard to/from mux */
2180         case KBRELKBD: {
2181                 error = 0;
2182
2183                 mtx_lock(&Giant);
2184                 if ((kbd = vd->vd_keyboard) != NULL)
2185                         error = kbdd_ioctl(kbd, cmd, data);
2186                 mtx_unlock(&Giant);
2187                 if (error == ENOIOCTL) {
2188                         if (cmd == KDGKBTYPE) {
2189                                 /* always return something? XXX */
2190                                 *(int *)data = 0;
2191                         } else {
2192                                 return (ENODEV);
2193                         }
2194                 }
2195                 return (error);
2196         }
2197         case KDGKBSTATE: {      /* get keyboard state (locks) */
2198                 error = 0;
2199
2200                 if (vw == vd->vd_curwindow) {
2201                         mtx_lock(&Giant);
2202                         if ((kbd = vd->vd_keyboard) != NULL)
2203                                 error = vt_save_kbd_state(vw, kbd);
2204                         mtx_unlock(&Giant);
2205
2206                         if (error != 0)
2207                                 return (error);
2208                 }
2209
2210                 *(int *)data = vw->vw_kbdstate & LOCK_MASK;
2211
2212                 return (error);
2213         }
2214         case KDSKBSTATE: {      /* set keyboard state (locks) */
2215                 int state;
2216
2217                 state = *(int *)data;
2218                 if (state & ~LOCK_MASK)
2219                         return (EINVAL);
2220
2221                 vw->vw_kbdstate &= ~LOCK_MASK;
2222                 vw->vw_kbdstate |= state;
2223
2224                 error = 0;
2225                 if (vw == vd->vd_curwindow) {
2226                         mtx_lock(&Giant);
2227                         if ((kbd = vd->vd_keyboard) != NULL)
2228                                 error = vt_update_kbd_state(vw, kbd);
2229                         mtx_unlock(&Giant);
2230                 }
2231
2232                 return (error);
2233         }
2234         case KDGETLED: {        /* get keyboard LED status */
2235                 error = 0;
2236
2237                 if (vw == vd->vd_curwindow) {
2238                         mtx_lock(&Giant);
2239                         if ((kbd = vd->vd_keyboard) != NULL)
2240                                 error = vt_save_kbd_leds(vw, kbd);
2241                         mtx_unlock(&Giant);
2242
2243                         if (error != 0)
2244                                 return (error);
2245                 }
2246
2247                 *(int *)data = vw->vw_kbdstate & LED_MASK;
2248
2249                 return (error);
2250         }
2251         case KDSETLED: {        /* set keyboard LED status */
2252                 int leds;
2253
2254                 leds = *(int *)data;
2255                 if (leds & ~LED_MASK)
2256                         return (EINVAL);
2257
2258                 vw->vw_kbdstate &= ~LED_MASK;
2259                 vw->vw_kbdstate |= leds;
2260
2261                 error = 0;
2262                 if (vw == vd->vd_curwindow) {
2263                         mtx_lock(&Giant);
2264                         if ((kbd = vd->vd_keyboard) != NULL)
2265                                 error = vt_update_kbd_leds(vw, kbd);
2266                         mtx_unlock(&Giant);
2267                 }
2268
2269                 return (error);
2270         }
2271         case KDGETMODE:
2272                 *(int *)data = (vw->vw_flags & VWF_GRAPHICS) ?
2273                     KD_GRAPHICS : KD_TEXT;
2274                 return (0);
2275         case KDGKBMODE: {
2276                 error = 0;
2277
2278                 if (vw == vd->vd_curwindow) {
2279                         mtx_lock(&Giant);
2280                         if ((kbd = vd->vd_keyboard) != NULL)
2281                                 error = vt_save_kbd_mode(vw, kbd);
2282                         mtx_unlock(&Giant);
2283
2284                         if (error != 0)
2285                                 return (error);
2286                 }
2287
2288                 *(int *)data = vw->vw_kbdmode;
2289
2290                 return (error);
2291         }
2292         case KDSKBMODE: {
2293                 int mode;
2294
2295                 mode = *(int *)data;
2296                 switch (mode) {
2297                 case K_XLATE:
2298                 case K_RAW:
2299                 case K_CODE:
2300                         vw->vw_kbdmode = mode;
2301
2302                         error = 0;
2303                         if (vw == vd->vd_curwindow) {
2304                                 mtx_lock(&Giant);
2305                                 if ((kbd = vd->vd_keyboard) != NULL)
2306                                         error = vt_update_kbd_mode(vw, kbd);
2307                                 mtx_unlock(&Giant);
2308                         }
2309
2310                         return (error);
2311                 default:
2312                         return (EINVAL);
2313                 }
2314         }
2315         case FBIOGTYPE:
2316         case FBIO_GETWINORG:    /* get frame buffer window origin */
2317         case FBIO_GETDISPSTART: /* get display start address */
2318         case FBIO_GETLINEWIDTH: /* get scan line width in bytes */
2319         case FBIO_BLANK:        /* blank display */
2320                 if (vd->vd_driver->vd_fb_ioctl)
2321                         return (vd->vd_driver->vd_fb_ioctl(vd, cmd, data, td));
2322                 break;
2323         case CONS_BLANKTIME:
2324                 /* XXX */
2325                 return (0);
2326         case CONS_HISTORY:
2327                 if (*(int *)data < 0)
2328                         return EINVAL;
2329                 if (*(int *)data != vw->vw_buf.vb_history_size)
2330                         vtbuf_sethistory_size(&vw->vw_buf, *(int *)data);
2331                 return (0);
2332         case CONS_CLRHIST:
2333                 vtbuf_clearhistory(&vw->vw_buf);
2334                 /*
2335                  * Invalidate the entire visible window; it is not guaranteed
2336                  * that this operation will be immediately followed by a scroll
2337                  * event, so it would otherwise be possible for prior artifacts
2338                  * to remain visible.
2339                  */
2340                 VT_LOCK(vd);
2341                 if (vw == vd->vd_curwindow) {
2342                         vd->vd_flags |= VDF_INVALID;
2343                         vt_resume_flush_timer(vw, 0);
2344                 }
2345                 VT_UNLOCK(vd);
2346                 return (0);
2347         case CONS_GET:
2348                 /* XXX */
2349                 *(int *)data = M_CG640x480;
2350                 return (0);
2351         case CONS_BELLTYPE:     /* set bell type sound */
2352                 if ((*(int *)data) & CONS_QUIET_BELL)
2353                         vd->vd_flags |= VDF_QUIET_BELL;
2354                 else
2355                         vd->vd_flags &= ~VDF_QUIET_BELL;
2356                 return (0);
2357         case CONS_GETINFO: {
2358                 vid_info_t *vi = (vid_info_t *)data;
2359                 if (vi->size != sizeof(struct vid_info))
2360                         return (EINVAL);
2361
2362                 if (vw == vd->vd_curwindow) {
2363                         mtx_lock(&Giant);
2364                         if ((kbd = vd->vd_keyboard) != NULL)
2365                                 vt_save_kbd_state(vw, kbd);
2366                         mtx_unlock(&Giant);
2367                 }
2368
2369                 vi->m_num = vd->vd_curwindow->vw_number + 1;
2370                 vi->mk_keylock = vw->vw_kbdstate & LOCK_MASK;
2371                 /* XXX: other fields! */
2372                 return (0);
2373         }
2374         case CONS_GETVERS:
2375                 *(int *)data = 0x200;
2376                 return (0);
2377         case CONS_MODEINFO:
2378                 /* XXX */
2379                 return (0);
2380         case CONS_MOUSECTL: {
2381                 mouse_info_t *mouse = (mouse_info_t*)data;
2382
2383                 /*
2384                  * All the commands except MOUSE_SHOW nd MOUSE_HIDE
2385                  * should not be applied to individual TTYs, but only to
2386                  * consolectl.
2387                  */
2388                 switch (mouse->operation) {
2389                 case MOUSE_HIDE:
2390                         if (vd->vd_flags & VDF_MOUSECURSOR) {
2391                                 vd->vd_flags &= ~VDF_MOUSECURSOR;
2392 #ifndef SC_NO_CUTPASTE
2393                                 vt_mouse_state(VT_MOUSE_HIDE);
2394 #endif
2395                         }
2396                         return (0);
2397                 case MOUSE_SHOW:
2398                         if (!(vd->vd_flags & VDF_MOUSECURSOR)) {
2399                                 vd->vd_flags |= VDF_MOUSECURSOR;
2400                                 vd->vd_mx = vd->vd_width / 2;
2401                                 vd->vd_my = vd->vd_height / 2;
2402 #ifndef SC_NO_CUTPASTE
2403                                 vt_mouse_state(VT_MOUSE_SHOW);
2404 #endif
2405                         }
2406                         return (0);
2407                 default:
2408                         return (EINVAL);
2409                 }
2410         }
2411         case PIO_VFONT: {
2412                 struct vt_font *vf;
2413
2414                 if (vd->vd_flags & VDF_TEXTMODE)
2415                         return (ENOTSUP);
2416
2417                 error = vtfont_load((void *)data, &vf);
2418                 if (error != 0)
2419                         return (error);
2420
2421                 error = vt_change_font(vw, vf);
2422                 vtfont_unref(vf);
2423                 return (error);
2424         }
2425         case PIO_VFONT_DEFAULT: {
2426                 /* Reset to default font. */
2427                 error = vt_change_font(vw, &vt_font_default);
2428                 return (error);
2429         }
2430         case GIO_SCRNMAP: {
2431                 scrmap_t *sm = (scrmap_t *)data;
2432
2433                 /* We don't have screen maps, so return a handcrafted one. */
2434                 for (i = 0; i < 256; i++)
2435                         sm->scrmap[i] = i;
2436                 return (0);
2437         }
2438         case KDSETMODE:
2439                 /*
2440                  * FIXME: This implementation is incomplete compared to
2441                  * syscons.
2442                  */
2443                 switch (*(int *)data) {
2444                 case KD_TEXT:
2445                 case KD_TEXT1:
2446                 case KD_PIXEL:
2447                         vw->vw_flags &= ~VWF_GRAPHICS;
2448                         break;
2449                 case KD_GRAPHICS:
2450                         vw->vw_flags |= VWF_GRAPHICS;
2451                         break;
2452                 }
2453                 return (0);
2454         case KDENABIO:          /* allow io operations */
2455                 error = priv_check(td, PRIV_IO);
2456                 if (error != 0)
2457                         return (error);
2458                 error = securelevel_gt(td->td_ucred, 0);
2459                 if (error != 0)
2460                         return (error);
2461 #if defined(__i386__)
2462                 td->td_frame->tf_eflags |= PSL_IOPL;
2463 #elif defined(__amd64__)
2464                 td->td_frame->tf_rflags |= PSL_IOPL;
2465 #endif
2466                 return (0);
2467         case KDDISABIO:         /* disallow io operations (default) */
2468 #if defined(__i386__)
2469                 td->td_frame->tf_eflags &= ~PSL_IOPL;
2470 #elif defined(__amd64__)
2471                 td->td_frame->tf_rflags &= ~PSL_IOPL;
2472 #endif
2473                 return (0);
2474         case KDMKTONE:          /* sound the bell */
2475                 vtterm_beep(tm, *(u_int *)data);
2476                 return (0);
2477         case KIOCSOUND:         /* make tone (*data) hz */
2478                 /* TODO */
2479                 return (0);
2480         case CONS_SETKBD:       /* set the new keyboard */
2481                 mtx_lock(&Giant);
2482                 error = 0;
2483                 if (vd->vd_keyboard == NULL ||
2484                     vd->vd_keyboard->kb_index != *(int *)data) {
2485                         kbd = kbd_get_keyboard(*(int *)data);
2486                         if (kbd == NULL) {
2487                                 mtx_unlock(&Giant);
2488                                 return (EINVAL);
2489                         }
2490                         i = kbd_allocate(kbd->kb_name, kbd->kb_unit,
2491                             (void *)vd, vt_kbdevent, vd);
2492                         if (i >= 0) {
2493                                 if ((kbd = vd->vd_keyboard) != NULL) {
2494                                         vt_save_kbd_state(vd->vd_curwindow, kbd);
2495                                         kbd_release(kbd, (void *)vd);
2496                                 }
2497                                 kbd = vd->vd_keyboard = kbd_get_keyboard(i);
2498
2499                                 vt_update_kbd_mode(vd->vd_curwindow, kbd);
2500                                 vt_update_kbd_state(vd->vd_curwindow, kbd);
2501                         } else {
2502                                 error = EPERM;  /* XXX */
2503                         }
2504                 }
2505                 mtx_unlock(&Giant);
2506                 return (error);
2507         case CONS_RELKBD:       /* release the current keyboard */
2508                 mtx_lock(&Giant);
2509                 error = 0;
2510                 if ((kbd = vd->vd_keyboard) != NULL) {
2511                         vt_save_kbd_state(vd->vd_curwindow, kbd);
2512                         error = kbd_release(kbd, (void *)vd);
2513                         if (error == 0) {
2514                                 vd->vd_keyboard = NULL;
2515                         }
2516                 }
2517                 mtx_unlock(&Giant);
2518                 return (error);
2519         case VT_ACTIVATE: {
2520                 int win;
2521                 win = *(int *)data - 1;
2522                 DPRINTF(5, "%s%d: VT_ACTIVATE ttyv%d ", SC_DRIVER_NAME,
2523                     VT_UNIT(vw), win);
2524                 if ((win >= VT_MAXWINDOWS) || (win < 0))
2525                         return (EINVAL);
2526                 return (vt_proc_window_switch(vd->vd_windows[win]));
2527         }
2528         case VT_GETACTIVE:
2529                 *(int *)data = vd->vd_curwindow->vw_number + 1;
2530                 return (0);
2531         case VT_GETINDEX:
2532                 *(int *)data = vw->vw_number + 1;
2533                 return (0);
2534         case VT_LOCKSWITCH:
2535                 /* TODO: Check current state, switching can be in progress. */
2536                 if ((*(int *)data) == 0x01)
2537                         vw->vw_flags |= VWF_VTYLOCK;
2538                 else if ((*(int *)data) == 0x02)
2539                         vw->vw_flags &= ~VWF_VTYLOCK;
2540                 else
2541                         return (EINVAL);
2542                 return (0);
2543         case VT_OPENQRY:
2544                 VT_LOCK(vd);
2545                 for (i = 0; i < VT_MAXWINDOWS; i++) {
2546                         vw = vd->vd_windows[i];
2547                         if (vw == NULL)
2548                                 continue;
2549                         if (!(vw->vw_flags & VWF_OPENED)) {
2550                                 *(int *)data = vw->vw_number + 1;
2551                                 VT_UNLOCK(vd);
2552                                 return (0);
2553                         }
2554                 }
2555                 VT_UNLOCK(vd);
2556                 return (EINVAL);
2557         case VT_WAITACTIVE: {
2558                 unsigned int idx;
2559
2560                 error = 0;
2561
2562                 idx = *(unsigned int *)data;
2563                 if (idx > VT_MAXWINDOWS)
2564                         return (EINVAL);
2565                 if (idx > 0)
2566                         vw = vd->vd_windows[idx - 1];
2567
2568                 VT_LOCK(vd);
2569                 while (vd->vd_curwindow != vw && error == 0)
2570                         error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
2571                 VT_UNLOCK(vd);
2572                 return (error);
2573         }
2574         case VT_SETMODE: {      /* set screen switcher mode */
2575                 struct vt_mode *mode;
2576                 struct proc *p1;
2577
2578                 mode = (struct vt_mode *)data;
2579                 DPRINTF(5, "%s%d: VT_SETMODE ", SC_DRIVER_NAME, VT_UNIT(vw));
2580                 if (vw->vw_smode.mode == VT_PROCESS) {
2581                         p1 = pfind(vw->vw_pid);
2582                         if (vw->vw_proc == p1 && vw->vw_proc != td->td_proc) {
2583                                 if (p1)
2584                                         PROC_UNLOCK(p1);
2585                                 DPRINTF(5, "error EPERM\n");
2586                                 return (EPERM);
2587                         }
2588                         if (p1)
2589                                 PROC_UNLOCK(p1);
2590                 }
2591                 if (mode->mode == VT_AUTO) {
2592                         vw->vw_smode.mode = VT_AUTO;
2593                         vw->vw_proc = NULL;
2594                         vw->vw_pid = 0;
2595                         DPRINTF(5, "VT_AUTO, ");
2596                         if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
2597                                 cnavailable(vw->vw_terminal->consdev, TRUE);
2598                         /* were we in the middle of the vty switching process? */
2599                         if (finish_vt_rel(vw, TRUE, &s) == 0)
2600                                 DPRINTF(5, "reset WAIT_REL, ");
2601                         if (finish_vt_acq(vw) == 0)
2602                                 DPRINTF(5, "reset WAIT_ACQ, ");
2603                         return (0);
2604                 } else if (mode->mode == VT_PROCESS) {
2605                         if (!ISSIGVALID(mode->relsig) ||
2606                             !ISSIGVALID(mode->acqsig) ||
2607                             !ISSIGVALID(mode->frsig)) {
2608                                 DPRINTF(5, "error EINVAL\n");
2609                                 return (EINVAL);
2610                         }
2611                         DPRINTF(5, "VT_PROCESS %d, ", td->td_proc->p_pid);
2612                         bcopy(data, &vw->vw_smode, sizeof(struct vt_mode));
2613                         vw->vw_proc = td->td_proc;
2614                         vw->vw_pid = vw->vw_proc->p_pid;
2615                         if (vw == vw->vw_device->vd_windows[VT_CONSWINDOW])
2616                                 cnavailable(vw->vw_terminal->consdev, FALSE);
2617                 } else {
2618                         DPRINTF(5, "VT_SETMODE failed, unknown mode %d\n",
2619                             mode->mode);
2620                         return (EINVAL);
2621                 }
2622                 DPRINTF(5, "\n");
2623                 return (0);
2624         }
2625         case VT_GETMODE:        /* get screen switcher mode */
2626                 bcopy(&vw->vw_smode, data, sizeof(struct vt_mode));
2627                 return (0);
2628
2629         case VT_RELDISP:        /* screen switcher ioctl */
2630                 /*
2631                  * This must be the current vty which is in the VT_PROCESS
2632                  * switching mode...
2633                  */
2634                 if ((vw != vd->vd_curwindow) || (vw->vw_smode.mode !=
2635                     VT_PROCESS)) {
2636                         return (EINVAL);
2637                 }
2638                 /* ...and this process is controlling it. */
2639                 if (vw->vw_proc != td->td_proc) {
2640                         return (EPERM);
2641                 }
2642                 error = EINVAL;
2643                 switch(*(int *)data) {
2644                 case VT_FALSE:  /* user refuses to release screen, abort */
2645                         if ((error = finish_vt_rel(vw, FALSE, &s)) == 0)
2646                                 DPRINTF(5, "%s%d: VT_RELDISP: VT_FALSE\n",
2647                                     SC_DRIVER_NAME, VT_UNIT(vw));
2648                         break;
2649                 case VT_TRUE:   /* user has released screen, go on */
2650                         /* finish_vt_rel(..., TRUE, ...) should not be locked */
2651                         if (vw->vw_flags & VWF_SWWAIT_REL) {
2652                                 if ((error = finish_vt_rel(vw, TRUE, &s)) == 0)
2653                                         DPRINTF(5, "%s%d: VT_RELDISP: VT_TRUE\n",
2654                                             SC_DRIVER_NAME, VT_UNIT(vw));
2655                         } else {
2656                                 error = EINVAL;
2657                         }
2658                         return (error);
2659                 case VT_ACKACQ: /* acquire acknowledged, switch completed */
2660                         if ((error = finish_vt_acq(vw)) == 0)
2661                                 DPRINTF(5, "%s%d: VT_RELDISP: VT_ACKACQ\n",
2662                                     SC_DRIVER_NAME, VT_UNIT(vw));
2663                         break;
2664                 default:
2665                         break;
2666                 }
2667                 return (error);
2668         }
2669
2670         return (ENOIOCTL);
2671 }
2672
2673 static struct vt_window *
2674 vt_allocate_window(struct vt_device *vd, unsigned int window)
2675 {
2676         struct vt_window *vw;
2677         struct terminal *tm;
2678         term_pos_t size;
2679         struct winsize wsz;
2680
2681         vw = malloc(sizeof *vw, M_VT, M_WAITOK|M_ZERO);
2682         vw->vw_device = vd;
2683         vw->vw_number = window;
2684         vw->vw_kbdmode = K_XLATE;
2685
2686         if ((vd->vd_flags & VDF_TEXTMODE) == 0) {
2687                 vw->vw_font = vtfont_ref(&vt_font_default);
2688                 vt_compute_drawable_area(vw);
2689         }
2690
2691         vt_termsize(vd, vw->vw_font, &size);
2692         vt_winsize(vd, vw->vw_font, &wsz);
2693         tm = vw->vw_terminal = terminal_alloc(&vt_termclass, vw);
2694         vw->vw_buf.vb_terminal = tm;    /* must be set before vtbuf_init() */
2695         vtbuf_init(&vw->vw_buf, &size);
2696
2697         terminal_set_winsize(tm, &wsz);
2698         vd->vd_windows[window] = vw;
2699         callout_init(&vw->vw_proc_dead_timer, 0);
2700
2701         return (vw);
2702 }
2703
2704 void
2705 vt_upgrade(struct vt_device *vd)
2706 {
2707         struct vt_window *vw;
2708         unsigned int i;
2709         int register_handlers;
2710
2711         if (!vty_enabled(VTY_VT))
2712                 return;
2713         if (main_vd->vd_driver == NULL)
2714                 return;
2715
2716         for (i = 0; i < VT_MAXWINDOWS; i++) {
2717                 vw = vd->vd_windows[i];
2718                 if (vw == NULL) {
2719                         /* New window. */
2720                         vw = vt_allocate_window(vd, i);
2721                 }
2722                 if (!(vw->vw_flags & VWF_READY)) {
2723                         callout_init(&vw->vw_proc_dead_timer, 0);
2724                         terminal_maketty(vw->vw_terminal, "v%r", VT_UNIT(vw));
2725                         vw->vw_flags |= VWF_READY;
2726                         if (vw->vw_flags & VWF_CONSOLE) {
2727                                 /* For existing console window. */
2728                                 EVENTHANDLER_REGISTER(shutdown_pre_sync,
2729                                     vt_window_switch, vw, SHUTDOWN_PRI_DEFAULT);
2730                         }
2731                 }
2732
2733         }
2734         VT_LOCK(vd);
2735         if (vd->vd_curwindow == NULL)
2736                 vd->vd_curwindow = vd->vd_windows[VT_CONSWINDOW];
2737
2738         register_handlers = 0;
2739         if (!(vd->vd_flags & VDF_ASYNC)) {
2740                 /* Attach keyboard. */
2741                 vt_allocate_keyboard(vd);
2742
2743                 /* Init 25 Hz timer. */
2744                 callout_init_mtx(&vd->vd_timer, &vd->vd_lock, 0);
2745
2746                 /*
2747                  * Start timer when everything ready.
2748                  * Note that the operations here are purposefully ordered.
2749                  * We need to ensure vd_timer_armed is non-zero before we set
2750                  * the VDF_ASYNC flag. That prevents this function from
2751                  * racing with vt_resume_flush_timer() to update the
2752                  * callout structure.
2753                  */
2754                 atomic_add_acq_int(&vd->vd_timer_armed, 1);
2755                 vd->vd_flags |= VDF_ASYNC;
2756                 callout_reset(&vd->vd_timer, hz / VT_TIMERFREQ, vt_timer, vd);
2757                 register_handlers = 1;
2758         }
2759
2760         VT_UNLOCK(vd);
2761
2762         /* Refill settings with new sizes. */
2763         vt_resize(vd);
2764
2765         if (register_handlers) {
2766                 /* Register suspend/resume handlers. */
2767                 EVENTHANDLER_REGISTER(power_suspend_early, vt_suspend_handler,
2768                     vd, EVENTHANDLER_PRI_ANY);
2769                 EVENTHANDLER_REGISTER(power_resume, vt_resume_handler, vd,
2770                     EVENTHANDLER_PRI_ANY);
2771         }
2772 }
2773
2774 static void
2775 vt_resize(struct vt_device *vd)
2776 {
2777         struct vt_window *vw;
2778         int i;
2779
2780         for (i = 0; i < VT_MAXWINDOWS; i++) {
2781                 vw = vd->vd_windows[i];
2782                 VT_LOCK(vd);
2783                 /* Assign default font to window, if not textmode. */
2784                 if (!(vd->vd_flags & VDF_TEXTMODE) && vw->vw_font == NULL)
2785                         vw->vw_font = vtfont_ref(&vt_font_default);
2786                 VT_UNLOCK(vd);
2787
2788                 /* Resize terminal windows */
2789                 while (vt_change_font(vw, vw->vw_font) == EBUSY) {
2790                         DPRINTF(100, "%s: vt_change_font() is busy, "
2791                             "window %d\n", __func__, i);
2792                 }
2793         }
2794 }
2795
2796 static void
2797 vt_replace_backend(const struct vt_driver *drv, void *softc)
2798 {
2799         struct vt_device *vd;
2800
2801         vd = main_vd;
2802
2803         if (vd->vd_flags & VDF_ASYNC) {
2804                 /* Stop vt_flush periodic task. */
2805                 VT_LOCK(vd);
2806                 vt_suspend_flush_timer(vd);
2807                 VT_UNLOCK(vd);
2808                 /*
2809                  * Mute current terminal until we done. vt_change_font (called
2810                  * from vt_resize) will unmute it.
2811                  */
2812                 terminal_mute(vd->vd_curwindow->vw_terminal, 1);
2813         }
2814
2815         /*
2816          * Reset VDF_TEXTMODE flag, driver who require that flag (vt_vga) will
2817          * set it.
2818          */
2819         VT_LOCK(vd);
2820         vd->vd_flags &= ~VDF_TEXTMODE;
2821
2822         if (drv != NULL) {
2823                 /*
2824                  * We want to upgrade from the current driver to the
2825                  * given driver.
2826                  */
2827
2828                 vd->vd_prev_driver = vd->vd_driver;
2829                 vd->vd_prev_softc = vd->vd_softc;
2830                 vd->vd_driver = drv;
2831                 vd->vd_softc = softc;
2832
2833                 vd->vd_driver->vd_init(vd);
2834         } else if (vd->vd_prev_driver != NULL && vd->vd_prev_softc != NULL) {
2835                 /*
2836                  * No driver given: we want to downgrade to the previous
2837                  * driver.
2838                  */
2839                 const struct vt_driver *old_drv;
2840                 void *old_softc;
2841
2842                 old_drv = vd->vd_driver;
2843                 old_softc = vd->vd_softc;
2844
2845                 vd->vd_driver = vd->vd_prev_driver;
2846                 vd->vd_softc = vd->vd_prev_softc;
2847                 vd->vd_prev_driver = NULL;
2848                 vd->vd_prev_softc = NULL;
2849
2850                 vd->vd_flags |= VDF_DOWNGRADE;
2851
2852                 vd->vd_driver->vd_init(vd);
2853
2854                 if (old_drv->vd_fini)
2855                         old_drv->vd_fini(vd, old_softc);
2856
2857                 vd->vd_flags &= ~VDF_DOWNGRADE;
2858         }
2859
2860         VT_UNLOCK(vd);
2861
2862         /* Update windows sizes and initialize last items. */
2863         vt_upgrade(vd);
2864
2865 #ifdef DEV_SPLASH
2866         if (vd->vd_flags & VDF_SPLASH)
2867                 vtterm_splash(vd);
2868 #endif
2869
2870         if (vd->vd_flags & VDF_ASYNC) {
2871                 /* Allow to put chars now. */
2872                 terminal_mute(vd->vd_curwindow->vw_terminal, 0);
2873                 /* Rerun timer for screen updates. */
2874                 vt_resume_flush_timer(vd->vd_curwindow, 0);
2875         }
2876
2877         /*
2878          * Register as console. If it already registered, cnadd() will ignore
2879          * it.
2880          */
2881         termcn_cnregister(vd->vd_windows[VT_CONSWINDOW]->vw_terminal);
2882 }
2883
2884 static void
2885 vt_suspend_handler(void *priv)
2886 {
2887         struct vt_device *vd;
2888
2889         vd = priv;
2890         vd->vd_flags |= VDF_SUSPENDED;
2891         if (vd->vd_driver != NULL && vd->vd_driver->vd_suspend != NULL)
2892                 vd->vd_driver->vd_suspend(vd);
2893 }
2894
2895 static void
2896 vt_resume_handler(void *priv)
2897 {
2898         struct vt_device *vd;
2899
2900         vd = priv;
2901         if (vd->vd_driver != NULL && vd->vd_driver->vd_resume != NULL)
2902                 vd->vd_driver->vd_resume(vd);
2903         vd->vd_flags &= ~VDF_SUSPENDED;
2904 }
2905
2906 void
2907 vt_allocate(const struct vt_driver *drv, void *softc)
2908 {
2909
2910         if (!vty_enabled(VTY_VT))
2911                 return;
2912
2913         if (main_vd->vd_driver == NULL) {
2914                 main_vd->vd_driver = drv;
2915                 printf("VT: initialize with new VT driver \"%s\".\n",
2916                     drv->vd_name);
2917         } else {
2918                 /*
2919                  * Check if have rights to replace current driver. For example:
2920                  * it is bad idea to replace KMS driver with generic VGA one.
2921                  */
2922                 if (drv->vd_priority <= main_vd->vd_driver->vd_priority) {
2923                         printf("VT: Driver priority %d too low. Current %d\n ",
2924                             drv->vd_priority, main_vd->vd_driver->vd_priority);
2925                         return;
2926                 }
2927                 printf("VT: Replacing driver \"%s\" with new \"%s\".\n",
2928                     main_vd->vd_driver->vd_name, drv->vd_name);
2929         }
2930
2931         vt_replace_backend(drv, softc);
2932 }
2933
2934 void
2935 vt_deallocate(const struct vt_driver *drv, void *softc)
2936 {
2937
2938         if (!vty_enabled(VTY_VT))
2939                 return;
2940
2941         if (main_vd->vd_prev_driver == NULL ||
2942             main_vd->vd_driver != drv ||
2943             main_vd->vd_softc != softc)
2944                 return;
2945
2946         printf("VT: Switching back from \"%s\" to \"%s\".\n",
2947             main_vd->vd_driver->vd_name, main_vd->vd_prev_driver->vd_name);
2948
2949         vt_replace_backend(NULL, NULL);
2950 }
2951
2952 void
2953 vt_suspend(struct vt_device *vd)
2954 {
2955         int error;
2956
2957         if (vt_suspendswitch == 0)
2958                 return;
2959         /* Save current window. */
2960         vd->vd_savedwindow = vd->vd_curwindow;
2961         /* Ask holding process to free window and switch to console window */
2962         vt_proc_window_switch(vd->vd_windows[VT_CONSWINDOW]);
2963
2964         /* Wait for the window switch to complete. */
2965         error = 0;
2966         VT_LOCK(vd);
2967         while (vd->vd_curwindow != vd->vd_windows[VT_CONSWINDOW] && error == 0)
2968                 error = cv_wait_sig(&vd->vd_winswitch, &vd->vd_lock);
2969         VT_UNLOCK(vd);
2970 }
2971
2972 void
2973 vt_resume(struct vt_device *vd)
2974 {
2975
2976         if (vt_suspendswitch == 0)
2977                 return;
2978         /* Switch back to saved window, if any */
2979         vt_proc_window_switch(vd->vd_savedwindow);
2980         vd->vd_savedwindow = NULL;
2981 }