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