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