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