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