Merge from vendor branch GDB:
[dragonfly.git] / sys / dev / misc / syscons / syscons.c
1 /*-
2  * Copyright (c) 1992-1998 Søren Schmidt
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Sascha Wildner <saw@online.de>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  * $FreeBSD: /usr/local/www/cvsroot/FreeBSD/src/sys/dev/syscons/syscons.c,v 1.336.2.17 2004/03/25 08:41:09 ru Exp $
32  * $DragonFly: src/sys/dev/misc/syscons/syscons.c,v 1.33 2007/08/19 11:39:11 swildner Exp $
33  */
34
35 #include "use_splash.h"
36 #include "opt_syscons.h"
37 #include "opt_ddb.h"
38 #include "use_apm.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/eventhandler.h>
43 #include <sys/reboot.h>
44 #include <sys/conf.h>
45 #include <sys/proc.h>
46 #include <sys/signalvar.h>
47 #include <sys/sysctl.h>
48 #include <sys/tty.h>
49 #include <sys/kernel.h>
50 #include <sys/cons.h>
51 #include <sys/random.h>
52 #include <sys/thread2.h>
53
54 #include <machine/clock.h>
55 #include <machine/console.h>
56 #include <machine/psl.h>
57 #include <machine/pc/display.h>
58 #include <machine/apm_bios.h>
59 #include <machine/frame.h>
60
61 #include <dev/misc/kbd/kbdreg.h>
62 #include <dev/video/fb/fbreg.h>
63 #include <dev/video/fb/splashreg.h>
64 #include "syscons.h"
65
66 #define COLD 0
67 #define WARM 1
68
69 #define DEFAULT_BLANKTIME       (5*60)          /* 5 minutes */
70 #define MAX_BLANKTIME           (7*24*60*60)    /* 7 days!? */
71
72 #define KEYCODE_BS              0x0e            /* "<-- Backspace" key, XXX */
73
74 MALLOC_DEFINE(M_SYSCONS, "syscons", "Syscons");
75
76 typedef struct default_attr {
77         int             std_color;              /* normal hardware color */
78         int             rev_color;              /* reverse hardware color */
79 } default_attr;
80
81 static default_attr user_default = {
82     SC_NORM_ATTR,
83     SC_NORM_REV_ATTR,
84 };
85
86 static default_attr kernel_default = {
87     SC_KERNEL_CONS_ATTR,
88     SC_KERNEL_CONS_REV_ATTR,
89 };
90
91 static  int             sc_console_unit = -1;
92 static  scr_stat        *sc_console;
93 static  struct tty      *sc_console_tty;
94 static  void            *kernel_console_ts;
95
96 static  char            init_done = COLD;
97 static  char            shutdown_in_progress = FALSE;
98 static  char            sc_malloc = FALSE;
99
100 static  int             saver_mode = CONS_NO_SAVER; /* LKM/user saver */
101 static  int             run_scrn_saver = FALSE; /* should run the saver? */
102 static  long            scrn_blank_time = 0;    /* screen saver timeout value */
103 #if NSPLASH > 0
104 static  int             scrn_blanked;           /* # of blanked screen */
105 static  int             sticky_splash = FALSE;
106
107 static  void            none_saver(sc_softc_t *sc, int blank) { }
108 static  void            (*current_saver)(sc_softc_t *, int) = none_saver;
109 #endif
110
111 #if !defined(SC_NO_FONT_LOADING) && defined(SC_DFLT_FONT)
112 #include "font.h"
113 #endif
114
115 static  bios_values_t   bios_value;
116
117 static  int             enable_panic_key;
118 SYSCTL_INT(_machdep, OID_AUTO, enable_panic_key, CTLFLAG_RW, &enable_panic_key,
119            0, "");
120
121 #define SC_CONSOLECTL   255
122
123 #define VIRTUAL_TTY(sc, x) (SC_DEV((sc), (x)) != NULL ? \
124         SC_DEV((sc), (x))->si_tty : NULL)
125 #define ISTTYOPEN(tp)   ((tp) && ((tp)->t_state & TS_ISOPEN))
126
127 static  int             debugger;
128
129 /* prototypes */
130 static int scvidprobe(int unit, int flags, int cons);
131 static int sckbdprobe(int unit, int flags, int cons);
132 static void scmeminit(void *arg);
133 static int scdevtounit(cdev_t dev);
134 static kbd_callback_func_t sckbdevent;
135 static int scparam(struct tty *tp, struct termios *t);
136 static void scstart(struct tty *tp);
137 static void scinit(int unit, int flags);
138 static void scterm(int unit, int flags);
139 static void scshutdown(void *arg, int howto);
140 static u_int scgetc(sc_softc_t *sc, u_int flags);
141 #define SCGETC_CN       1
142 #define SCGETC_NONBLOCK 2
143 static int sccngetch(int flags);
144 static void sccnupdate(scr_stat *scp);
145 static scr_stat *alloc_scp(sc_softc_t *sc, int vty);
146 static void init_scp(sc_softc_t *sc, int vty, scr_stat *scp);
147 static timeout_t scrn_timer;
148 static int and_region(int *s1, int *e1, int s2, int e2);
149 static void scrn_update(scr_stat *scp, int show_cursor);
150
151 #if NSPLASH > 0
152 static int scsplash_callback(int event, void *arg);
153 static void scsplash_saver(sc_softc_t *sc, int show);
154 static int add_scrn_saver(void (*this_saver)(sc_softc_t *, int));
155 static int remove_scrn_saver(void (*this_saver)(sc_softc_t *, int));
156 static int set_scrn_saver_mode(scr_stat *scp, int mode, u_char *pal, int border);
157 static int restore_scrn_saver_mode(scr_stat *scp, int changemode);
158 static void stop_scrn_saver(sc_softc_t *sc, void (*saver)(sc_softc_t *, int));
159 static int wait_scrn_saver_stop(sc_softc_t *sc);
160 #define scsplash_stick(stick)           (sticky_splash = (stick))
161 #else /* !NSPLASH */
162 #define scsplash_stick(stick)
163 #endif /* NSPLASH */
164
165 static void do_switch_scr(sc_softc_t *sc);
166 static int vt_proc_alive(scr_stat *scp);
167 static int signal_vt_rel(scr_stat *scp);
168 static int signal_vt_acq(scr_stat *scp);
169 static int finish_vt_rel(scr_stat *scp, int release);
170 static int finish_vt_acq(scr_stat *scp);
171 static void exchange_scr(sc_softc_t *sc);
172 static void update_cursor_image(scr_stat *scp);
173 static int save_kbd_state(scr_stat *scp);
174 static int update_kbd_state(scr_stat *scp, int state, int mask);
175 static int update_kbd_leds(scr_stat *scp, int which);
176 static timeout_t blink_screen;
177
178 #define CDEV_MAJOR      12
179
180 static cn_probe_t       sccnprobe;
181 static cn_init_t        sccninit;
182 static cn_init_t        sccninit_fini;
183 static cn_getc_t        sccngetc;
184 static cn_checkc_t      sccncheckc;
185 static cn_putc_t        sccnputc;
186 static cn_dbctl_t       sccndbctl;
187 static cn_term_t        sccnterm;
188
189 CONS_DRIVER(sc, sccnprobe, sccninit, sccninit_fini, sccnterm,
190             sccngetc, sccncheckc, sccnputc, sccndbctl);
191
192 static  d_open_t        scopen;
193 static  d_close_t       scclose;
194 static  d_read_t        scread;
195 static  d_ioctl_t       scioctl;
196 static  d_mmap_t        scmmap;
197
198 static struct dev_ops sc_ops = {
199         { "sc", CDEV_MAJOR, D_TTY | D_KQFILTER },
200         .d_open =       scopen,
201         .d_close =      scclose,
202         .d_read =       scread,
203         .d_write =      ttywrite,
204         .d_ioctl =      scioctl,
205         .d_poll =       ttypoll,
206         .d_mmap =       scmmap,
207         .d_kqfilter =   ttykqfilter
208 };
209
210 int
211 sc_probe_unit(int unit, int flags)
212 {
213     if (!scvidprobe(unit, flags, FALSE)) {
214         if (bootverbose)
215             kprintf("sc%d: no video adapter found.\n", unit);
216         return ENXIO;
217     }
218
219     /* syscons will be attached even when there is no keyboard */
220     sckbdprobe(unit, flags, FALSE);
221
222     return 0;
223 }
224
225 /* probe video adapters, return TRUE if found */ 
226 static int
227 scvidprobe(int unit, int flags, int cons)
228 {
229     /*
230      * Access the video adapter driver through the back door!
231      * Video adapter drivers need to be configured before syscons.
232      * However, when syscons is being probed as the low-level console,
233      * they have not been initialized yet.  We force them to initialize
234      * themselves here. XXX
235      */
236     vid_configure(cons ? VIO_PROBE_ONLY : 0);
237
238     return (vid_find_adapter("*", unit) >= 0);
239 }
240
241 /* probe the keyboard, return TRUE if found */
242 static int
243 sckbdprobe(int unit, int flags, int cons)
244 {
245     /* access the keyboard driver through the backdoor! */
246     kbd_configure(cons ? KB_CONF_PROBE_ONLY : 0);
247
248     return (kbd_find_keyboard("*", unit) >= 0);
249 }
250
251 static char *
252 adapter_name(video_adapter_t *adp)
253 {
254     static struct {
255         int type;
256         char *name[2];
257     } names[] = {
258         { KD_MONO,      { "MDA",        "MDA" } },
259         { KD_HERCULES,  { "Hercules",   "Hercules" } },
260         { KD_CGA,       { "CGA",        "CGA" } },
261         { KD_EGA,       { "EGA",        "EGA (mono)" } },
262         { KD_VGA,       { "VGA",        "VGA (mono)" } },
263         { KD_TGA,       { "TGA",        "TGA" } },
264         { -1,           { "Unknown",    "Unknown" } },
265     };
266     int i;
267
268     for (i = 0; names[i].type != -1; ++i)
269         if (names[i].type == adp->va_type)
270             break;
271     return names[i].name[(adp->va_flags & V_ADP_COLOR) ? 0 : 1];
272 }
273
274 int
275 sc_attach_unit(int unit, int flags)
276 {
277     sc_softc_t *sc;
278     scr_stat *scp;
279 #ifdef SC_PIXEL_MODE
280     video_info_t info;
281 #endif
282     int vc;
283     cdev_t dev;
284
285     flags &= ~SC_KERNEL_CONSOLE;
286
287     if (sc_console_unit == unit) {
288         /*
289          * If this unit is being used as the system console, we need to
290          * adjust some variables and buffers before and after scinit().
291          */
292         /* assert(sc_console != NULL) */
293         flags |= SC_KERNEL_CONSOLE;
294         scmeminit(NULL);
295
296         scinit(unit, flags);
297
298         if (sc_console->tsw->te_size > 0) {
299             /* assert(sc_console->ts != NULL); */
300             kernel_console_ts = sc_console->ts;
301             sc_console->ts = kmalloc(sc_console->tsw->te_size,
302                                     M_SYSCONS, M_WAITOK);
303             bcopy(kernel_console_ts, sc_console->ts, sc_console->tsw->te_size);
304             (*sc_console->tsw->te_default_attr)(sc_console,
305                                                 user_default.std_color,
306                                                 user_default.rev_color);
307         }
308     } else {
309         scinit(unit, flags);
310     }
311
312     sc = sc_get_softc(unit, flags & SC_KERNEL_CONSOLE);
313
314     /*
315      * If this is the console we couldn't setup sc->dev before because
316      * malloc wasn't working.  Set it up now.
317      */
318     if (flags & SC_KERNEL_CONSOLE) {
319         KKASSERT(sc->dev == NULL);
320         sc->dev = kmalloc(sizeof(cdev_t)*sc->vtys, M_SYSCONS, M_WAITOK|M_ZERO);
321         sc->dev[0] = make_dev(&sc_ops, sc_console_unit*MAXCONS, UID_ROOT, 
322                               GID_WHEEL, 0600, 
323                               "ttyv%r", sc_console_unit*MAXCONS);
324         sc->dev[0]->si_tty = ttymalloc(sc->dev[0]->si_tty);
325         sc->dev[0]->si_drv1 = sc_console;
326     }
327
328     /*
329      * Finish up the standard attach
330      */
331     sc->config = flags;
332     callout_init(&sc->scrn_timer_ch);
333     scp = SC_STAT(sc->dev[0]);
334     if (sc_console == NULL)     /* sc_console_unit < 0 */
335         sc_console = scp;
336
337 #ifdef SC_PIXEL_MODE
338     if ((sc->config & SC_VESA800X600)
339         && ((*vidsw[sc->adapter]->get_info)(sc->adp, M_VESA_800x600, &info) == 0)) {
340 #if NSPLASH > 0
341         if (sc->flags & SC_SPLASH_SCRN)
342             splash_term(sc->adp);
343 #endif
344         sc_set_graphics_mode(scp, NULL, M_VESA_800x600);
345         sc_set_pixel_mode(scp, NULL, COL, ROW, 16);
346         sc->initial_mode = M_VESA_800x600;
347 #if NSPLASH > 0
348         /* put up the splash again! */
349         if (sc->flags & SC_SPLASH_SCRN)
350             splash_init(sc->adp, scsplash_callback, sc);
351 #endif
352     }
353 #endif /* SC_PIXEL_MODE */
354
355     /* initialize cursor */
356     if (!ISGRAPHSC(scp))
357         update_cursor_image(scp);
358
359     /* get screen update going */
360     scrn_timer(sc);
361
362     /* set up the keyboard */
363     kbd_ioctl(sc->kbd, KDSKBMODE, (caddr_t)&scp->kbd_mode);
364     update_kbd_state(scp, scp->status, LOCK_MASK);
365
366     kprintf("sc%d: %s <%d virtual consoles, flags=0x%x>\n",
367            unit, adapter_name(sc->adp), sc->vtys, sc->config);
368     if (bootverbose) {
369         kprintf("sc%d:", unit);
370         if (sc->adapter >= 0)
371             kprintf(" fb%d", sc->adapter);
372         if (sc->keyboard >= 0)
373             kprintf(", kbd%d", sc->keyboard);
374         if (scp->tsw)
375             kprintf(", terminal emulator: %s (%s)",
376                    scp->tsw->te_name, scp->tsw->te_desc);
377         kprintf("\n");
378     }
379
380     /* register a shutdown callback for the kernel console */
381     if (sc_console_unit == unit)
382         EVENTHANDLER_REGISTER(shutdown_pre_sync, scshutdown, 
383                               (void *)(uintptr_t)unit, SHUTDOWN_PRI_DEFAULT);
384
385     /* 
386      * create devices.  dev_ops_add() must be called to make devices under
387      * this major number available to userland.
388      */
389     dev_ops_add(&sc_ops, ~(MAXCONS - 1), unit * MAXCONS);
390
391     for (vc = 0; vc < sc->vtys; vc++) {
392         dev = make_dev(&sc_ops, vc + unit * MAXCONS,
393             UID_ROOT, GID_WHEEL, 0600, "ttyv%r", vc + unit * MAXCONS);
394         sc->dev[vc] = dev;
395         /*
396          * The first vty already has struct tty and scr_stat initialized
397          * in scinit().  The other vtys will have these structs when
398          * first opened.
399          */
400     }
401
402     dev_ops_add(&sc_ops, -1, SC_CONSOLECTL);    /* XXX */
403     dev = make_dev(&sc_ops, SC_CONSOLECTL,
404                    UID_ROOT, GID_WHEEL, 0600, "consolectl");
405     dev->si_tty = sc_console_tty = ttymalloc(sc_console_tty);
406     dev->si_drv1 = sc_console;
407
408     return 0;
409 }
410
411 static void
412 scmeminit(void *arg)
413 {
414     if (sc_malloc)
415         return;
416     sc_malloc = TRUE;
417
418     /*
419      * As soon as malloc() becomes functional, we had better allocate
420      * various buffers for the kernel console.
421      */
422
423     if (sc_console_unit < 0)    /* sc_console == NULL */
424         return;
425
426     /* copy the temporary buffer to the final buffer */
427     sc_alloc_scr_buffer(sc_console, TRUE, FALSE);
428
429 #ifndef SC_NO_CUTPASTE
430     sc_alloc_cut_buffer(sc_console, TRUE);
431 #endif
432
433 #ifndef SC_NO_HISTORY
434     /* initialize history buffer & pointers */
435     sc_alloc_history_buffer(sc_console, 0, 0, TRUE);
436 #endif
437 }
438
439 SYSINIT(sc_mem, SI_BOOT1_POST, SI_ORDER_ANY, scmeminit, NULL);
440
441 static int
442 scdevtounit(cdev_t dev)
443 {
444     int vty = SC_VTY(dev);
445
446     if (vty == SC_CONSOLECTL)
447         return ((sc_console != NULL) ? sc_console->sc->unit : -1);
448     else if ((vty < 0) || (vty >= MAXCONS*sc_max_unit()))
449         return -1;
450     else
451         return vty/MAXCONS;
452 }
453
454 int
455 scopen(struct dev_open_args *ap)
456 {
457     cdev_t dev = ap->a_head.a_dev;
458     int unit = scdevtounit(dev);
459     sc_softc_t *sc;
460     struct tty *tp;
461     scr_stat *scp;
462     keyarg_t key;
463     int error;
464
465     DPRINTF(5, ("scopen: dev:%d,%d, unit:%d, vty:%d\n",
466                 major(dev), minor(dev), unit, SC_VTY(dev)));
467
468     sc = sc_get_softc(unit, (sc_console_unit == unit) ? SC_KERNEL_CONSOLE : 0);
469     if (sc == NULL)
470         return ENXIO;
471
472     tp = dev->si_tty = ttymalloc(dev->si_tty);
473     tp->t_oproc = scstart;
474     tp->t_param = scparam;
475     tp->t_stop = nottystop;
476     tp->t_dev = dev;
477     if (!ISTTYOPEN(tp)) {
478         ttychars(tp);
479         /* Use the current setting of the <-- key as default VERASE. */  
480         /* If the Delete key is preferable, an stty is necessary     */
481         if (sc->kbd != NULL) {
482             key.keynum = KEYCODE_BS;
483             kbd_ioctl(sc->kbd, GIO_KEYMAPENT, (caddr_t)&key);
484             tp->t_cc[VERASE] = key.key.map[0];
485         }
486         tp->t_iflag = TTYDEF_IFLAG;
487         tp->t_oflag = TTYDEF_OFLAG;
488         tp->t_cflag = TTYDEF_CFLAG;
489         tp->t_lflag = TTYDEF_LFLAG;
490         tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
491         scparam(tp, &tp->t_termios);
492         (*linesw[tp->t_line].l_modem)(tp, 1);
493     }
494     else
495         if (tp->t_state & TS_XCLUDE && suser_cred(ap->a_cred, 0))
496             return(EBUSY);
497
498     error = (*linesw[tp->t_line].l_open)(dev, tp);
499
500     scp = SC_STAT(dev);
501     if (scp == NULL) {
502         scp = dev->si_drv1 = alloc_scp(sc, SC_VTY(dev));
503         if (ISGRAPHSC(scp))
504             sc_set_pixel_mode(scp, NULL, COL, ROW, 16);
505     }
506     if (!tp->t_winsize.ws_col && !tp->t_winsize.ws_row) {
507         tp->t_winsize.ws_col = scp->xsize;
508         tp->t_winsize.ws_row = scp->ysize;
509     }
510
511     return error;
512 }
513
514 int
515 scclose(struct dev_close_args *ap)
516 {
517     cdev_t dev = ap->a_head.a_dev;
518     struct tty *tp = dev->si_tty;
519     scr_stat *scp;
520
521     crit_enter();
522     if (SC_VTY(dev) != SC_CONSOLECTL) {
523         scp = SC_STAT(tp->t_dev);
524         /* were we in the middle of the VT switching process? */
525         DPRINTF(5, ("sc%d: scclose(), ", scp->sc->unit));
526         if ((scp == scp->sc->cur_scp) && (scp->sc->unit == sc_console_unit))
527             cons_unavail = FALSE;
528         /* 
529          * note: must be called from a critical section because finish_vt_rel
530          * will call do_switch_scr which releases it temporarily 
531          */
532         if (finish_vt_rel(scp, TRUE) == 0)      /* force release */
533             DPRINTF(5, ("reset WAIT_REL, "));
534         if (finish_vt_acq(scp) == 0)            /* force acknowledge */
535             DPRINTF(5, ("reset WAIT_ACQ, "));
536 #if not_yet_done
537         if (scp == &main_console) {
538             scp->pid = 0;
539             scp->proc = NULL;
540             scp->smode.mode = VT_AUTO;
541         }
542         else {
543             sc_vtb_destroy(&scp->vtb);
544             sc_vtb_destroy(&scp->scr);
545             sc_free_history_buffer(scp, scp->ysize);
546             SC_STAT(dev) = NULL;
547             kfree(scp, M_SYSCONS);
548         }
549 #else
550         scp->pid = 0;
551         scp->proc = NULL;
552         scp->smode.mode = VT_AUTO;
553 #endif
554         scp->kbd_mode = K_XLATE;
555         if (scp == scp->sc->cur_scp)
556             kbd_ioctl(scp->sc->kbd, KDSKBMODE, (caddr_t)&scp->kbd_mode);
557         DPRINTF(5, ("done.\n"));
558     }
559     (*linesw[tp->t_line].l_close)(tp, ap->a_fflag);
560     ttyclose(tp);
561     crit_exit();
562     return(0);
563 }
564
565 int
566 scread(struct dev_read_args *ap)
567 {
568     sc_touch_scrn_saver();
569     return (ttyread(ap));
570 }
571
572 static int
573 sckbdevent(keyboard_t *thiskbd, int event, void *arg)
574 {
575     sc_softc_t *sc;
576     struct tty *cur_tty;
577     int c; 
578     size_t len;
579     u_char *cp;
580
581     sc = (sc_softc_t *)arg;
582     /* assert(thiskbd == sc->kbd) */
583
584     switch (event) {
585     case KBDIO_KEYINPUT:
586         break;
587     case KBDIO_UNLOADING:
588         sc->kbd = NULL;
589         sc->keyboard = -1;
590         kbd_release(thiskbd, (void *)&sc->keyboard);
591         return 0;
592     default:
593         return EINVAL;
594     }
595
596     /* 
597      * Loop while there is still input to get from the keyboard.
598      * I don't think this is nessesary, and it doesn't fix
599      * the Xaccel-2.1 keyboard hang, but it can't hurt.         XXX
600      */
601     while ((c = scgetc(sc, SCGETC_NONBLOCK)) != NOKEY) {
602
603         cur_tty = VIRTUAL_TTY(sc, sc->cur_scp->index);
604         if (!ISTTYOPEN(cur_tty)) {
605             cur_tty = sc_console_tty;
606             if (!ISTTYOPEN(cur_tty))
607                 continue;
608         }
609
610         if ((*sc->cur_scp->tsw->te_input)(sc->cur_scp, c, cur_tty))
611             continue;
612
613         switch (KEYFLAGS(c)) {
614         case 0x0000: /* normal key */
615             (*linesw[cur_tty->t_line].l_rint)(KEYCHAR(c), cur_tty);
616             break;
617         case FKEY:  /* function key, return string */
618             cp = kbd_get_fkeystr(thiskbd, KEYCHAR(c), &len);
619             if (cp != NULL) {
620                 while (len-- >  0)
621                     (*linesw[cur_tty->t_line].l_rint)(*cp++, cur_tty);
622             }
623             break;
624         case MKEY:  /* meta is active, prepend ESC */
625             (*linesw[cur_tty->t_line].l_rint)(0x1b, cur_tty);
626             (*linesw[cur_tty->t_line].l_rint)(KEYCHAR(c), cur_tty);
627             break;
628         case BKEY:  /* backtab fixed sequence (esc [ Z) */
629             (*linesw[cur_tty->t_line].l_rint)(0x1b, cur_tty);
630             (*linesw[cur_tty->t_line].l_rint)('[', cur_tty);
631             (*linesw[cur_tty->t_line].l_rint)('Z', cur_tty);
632             break;
633         }
634     }
635
636     sc->cur_scp->status |= MOUSE_HIDDEN;
637
638     return 0;
639 }
640
641 static int
642 scparam(struct tty *tp, struct termios *t)
643 {
644     tp->t_ispeed = t->c_ispeed;
645     tp->t_ospeed = t->c_ospeed;
646     tp->t_cflag = t->c_cflag;
647     return 0;
648 }
649
650 int
651 scioctl(struct dev_ioctl_args *ap)
652 {
653     cdev_t dev = ap->a_head.a_dev;
654     u_long cmd = ap->a_cmd;
655     caddr_t data = ap->a_data;
656     int flag = ap->a_fflag;
657     int error;
658     int i;
659     struct tty *tp;
660     sc_softc_t *sc;
661     scr_stat *scp;
662
663     tp = dev->si_tty;
664
665     error = sc_vid_ioctl(tp, cmd, data, flag);
666     if (error != ENOIOCTL)
667         return error;
668
669 #ifndef SC_NO_HISTORY
670     error = sc_hist_ioctl(tp, cmd, data, flag);
671     if (error != ENOIOCTL)
672         return error;
673 #endif
674
675 #ifndef SC_NO_SYSMOUSE
676     error = sc_mouse_ioctl(tp, cmd, data, flag);
677     if (error != ENOIOCTL)
678         return error;
679 #endif
680
681     scp = SC_STAT(tp->t_dev);
682     /* assert(scp != NULL) */
683     /* scp is sc_console, if SC_VTY(dev) == SC_CONSOLECTL. */
684     sc = scp->sc;
685
686     if (scp->tsw) {
687         error = (*scp->tsw->te_ioctl)(scp, tp, cmd, data, flag);
688         if (error != ENOIOCTL)
689             return error;
690     }
691
692     switch (cmd) {              /* process console hardware related ioctl's */
693
694     case GIO_ATTR:              /* get current attributes */
695         /* this ioctl is not processed here, but in the terminal emulator */
696         return ENOTTY;
697
698     case GIO_COLOR:             /* is this a color console ? */
699         *(int *)data = (sc->adp->va_flags & V_ADP_COLOR) ? 1 : 0;
700         return 0;
701
702     case CONS_BLANKTIME:        /* set screen saver timeout (0 = no saver) */
703         if (*(int *)data < 0 || *(int *)data > MAX_BLANKTIME)
704             return EINVAL;
705         crit_enter();
706         scrn_blank_time = *(int *)data;
707         run_scrn_saver = (scrn_blank_time != 0);
708         crit_exit();
709         return 0;
710
711     case CONS_CURSORTYPE:       /* set cursor type blink/noblink */
712         crit_enter();
713         if (!ISGRAPHSC(sc->cur_scp))
714             sc_remove_cursor_image(sc->cur_scp);
715         if ((*(int*)data) & 0x01)
716             sc->flags |= SC_BLINK_CURSOR;
717         else
718             sc->flags &= ~SC_BLINK_CURSOR;
719         if ((*(int*)data) & 0x02) {
720             sc->flags |= SC_CHAR_CURSOR;
721         } else
722             sc->flags &= ~SC_CHAR_CURSOR;
723         /* 
724          * The cursor shape is global property; all virtual consoles
725          * are affected. Update the cursor in the current console...
726          */
727         if (!ISGRAPHSC(sc->cur_scp)) {
728             sc_set_cursor_image(sc->cur_scp);
729             sc_draw_cursor_image(sc->cur_scp);
730         }
731         crit_exit();
732         return 0;
733
734     case CONS_BELLTYPE:         /* set bell type sound/visual */
735         if ((*(int *)data) & 0x01)
736             sc->flags |= SC_VISUAL_BELL;
737         else
738             sc->flags &= ~SC_VISUAL_BELL;
739         if ((*(int *)data) & 0x02)
740             sc->flags |= SC_QUIET_BELL;
741         else
742             sc->flags &= ~SC_QUIET_BELL;
743         return 0;
744
745     case CONS_GETINFO:          /* get current (virtual) console info */
746     {
747         vid_info_t *ptr = (vid_info_t*)data;
748         if (ptr->size == sizeof(struct vid_info)) {
749             ptr->m_num = sc->cur_scp->index;
750             ptr->font_size = scp->font_size;
751             ptr->mv_col = scp->xpos;
752             ptr->mv_row = scp->ypos;
753             ptr->mv_csz = scp->xsize;
754             ptr->mv_rsz = scp->ysize;
755             /*
756              * The following fields are filled by the terminal emulator. XXX
757              *
758              * ptr->mv_norm.fore
759              * ptr->mv_norm.back
760              * ptr->mv_rev.fore
761              * ptr->mv_rev.back
762              */
763             ptr->mv_grfc.fore = 0;      /* not supported */
764             ptr->mv_grfc.back = 0;      /* not supported */
765             ptr->mv_ovscan = scp->border;
766             if (scp == sc->cur_scp)
767                 save_kbd_state(scp);
768             ptr->mk_keylock = scp->status & LOCK_MASK;
769             return 0;
770         }
771         return EINVAL;
772     }
773
774     case CONS_GETVERS:          /* get version number */
775         *(int*)data = 0x200;    /* version 2.0 */
776         return 0;
777
778     case CONS_IDLE:             /* see if the screen has been idle */
779         /*
780          * When the screen is in the GRAPHICS_MODE or UNKNOWN_MODE,
781          * the user process may have been writing something on the
782          * screen and syscons is not aware of it. Declare the screen
783          * is NOT idle if it is in one of these modes. But there is
784          * an exception to it; if a screen saver is running in the 
785          * graphics mode in the current screen, we should say that the
786          * screen has been idle.
787          */
788         *(int *)data = (sc->flags & SC_SCRN_IDLE)
789                        && (!ISGRAPHSC(sc->cur_scp)
790                            || (sc->cur_scp->status & SAVER_RUNNING));
791         return 0;
792
793     case CONS_SAVERMODE:        /* set saver mode */
794         switch(*(int *)data) {
795         case CONS_NO_SAVER:
796         case CONS_USR_SAVER:
797             /* if a LKM screen saver is running, stop it first. */
798             scsplash_stick(FALSE);
799             saver_mode = *(int *)data;
800             crit_enter();
801 #if NSPLASH > 0
802             if ((error = wait_scrn_saver_stop(NULL))) {
803                 crit_exit();
804                 return error;
805             }
806 #endif /* NSPLASH */
807             run_scrn_saver = TRUE;
808             if (saver_mode == CONS_USR_SAVER)
809                 scp->status |= SAVER_RUNNING;
810             else
811                 scp->status &= ~SAVER_RUNNING;
812             scsplash_stick(TRUE);
813             crit_exit();
814             break;
815         case CONS_LKM_SAVER:
816             crit_enter();
817             if ((saver_mode == CONS_USR_SAVER) && (scp->status & SAVER_RUNNING))
818                 scp->status &= ~SAVER_RUNNING;
819             saver_mode = *(int *)data;
820             crit_exit();
821             break;
822         default:
823             return EINVAL;
824         }
825         return 0;
826
827     case CONS_SAVERSTART:       /* immediately start/stop the screen saver */
828         /*
829          * Note that this ioctl does not guarantee the screen saver 
830          * actually starts or stops. It merely attempts to do so...
831          */
832         crit_enter();
833         run_scrn_saver = (*(int *)data != 0);
834         if (run_scrn_saver)
835             sc->scrn_time_stamp -= scrn_blank_time;
836         crit_exit();
837         return 0;
838
839     case CONS_SCRSHOT:          /* get a screen shot */
840     {
841         scrshot_t *ptr = (scrshot_t*)data;
842         crit_enter();
843         if (ISGRAPHSC(scp)) {
844             crit_exit();
845             return EOPNOTSUPP;
846         }
847         if (scp->xsize != ptr->xsize || scp->ysize != ptr->ysize) {
848             crit_exit();
849             return EINVAL;
850         }
851         copyout ((void*)scp->vtb.vtb_buffer, ptr->buf,
852                  ptr->xsize * ptr->ysize * sizeof(uint16_t));
853         crit_exit();
854         return 0;
855     }
856
857     case VT_SETMODE:            /* set screen switcher mode */
858     {
859         struct vt_mode *mode;
860
861         mode = (struct vt_mode *)data;
862         DPRINTF(5, ("sc%d: VT_SETMODE ", sc->unit));
863         if (scp->smode.mode == VT_PROCESS) {
864             if (scp->proc == pfind(scp->pid) && scp->proc != curproc) {
865                 DPRINTF(5, ("error EPERM\n"));
866                 return EPERM;
867             }
868         }
869         crit_enter();
870         if (mode->mode == VT_AUTO) {
871             scp->smode.mode = VT_AUTO;
872             scp->proc = NULL;
873             scp->pid = 0;
874             DPRINTF(5, ("VT_AUTO, "));
875             if ((scp == sc->cur_scp) && (sc->unit == sc_console_unit))
876                 cons_unavail = FALSE;
877             /* 
878              * note: must be called from a critical section because 
879              * finish_vt_rel will call do_switch_scr which releases it
880              * temporarily.
881              */
882             if (finish_vt_rel(scp, TRUE) == 0)
883                 DPRINTF(5, ("reset WAIT_REL, "));
884             if (finish_vt_acq(scp) == 0)
885                 DPRINTF(5, ("reset WAIT_ACQ, "));
886         } else {
887             if (!ISSIGVALID(mode->relsig) || !ISSIGVALID(mode->acqsig)
888                 || !ISSIGVALID(mode->frsig)) {
889                 crit_exit();
890                 DPRINTF(5, ("error EINVAL\n"));
891                 return EINVAL;
892             }
893             DPRINTF(5, ("VT_PROCESS %d, ", curproc->p_pid));
894             bcopy(data, &scp->smode, sizeof(struct vt_mode));
895             scp->proc = curproc;
896             scp->pid = scp->proc->p_pid;
897             if ((scp == sc->cur_scp) && (sc->unit == sc_console_unit))
898                 cons_unavail = TRUE;
899         }
900         crit_exit();
901         DPRINTF(5, ("\n"));
902         return 0;
903     }
904
905     case VT_GETMODE:            /* get screen switcher mode */
906         bcopy(&scp->smode, data, sizeof(struct vt_mode));
907         return 0;
908
909     case VT_RELDISP:            /* screen switcher ioctl */
910         crit_enter();
911         /*
912          * This must be the current vty which is in the VT_PROCESS
913          * switching mode...
914          */
915         if ((scp != sc->cur_scp) || (scp->smode.mode != VT_PROCESS)) {
916             crit_exit();
917             return EINVAL;
918         }
919         /* ...and this process is controlling it. */
920         if (scp->proc != curproc) {
921             crit_exit();
922             return EPERM;
923         }
924         error = EINVAL;
925         switch(*(int *)data) {
926         case VT_FALSE:          /* user refuses to release screen, abort */
927             /* 
928              * note: must be called from a critical section because 
929              * finish_vt_rel will call do_switch_scr which releases it
930              * temporarily.
931              */
932             if ((error = finish_vt_rel(scp, FALSE)) == 0)
933                 DPRINTF(5, ("sc%d: VT_FALSE\n", sc->unit));
934             break;
935         case VT_TRUE:           /* user has released screen, go on */
936             /* 
937              * note: must be called from a critical section because 
938              * finish_vt_rel will call do_switch_scr which releases it
939              * temporarily.
940              */
941             if ((error = finish_vt_rel(scp, TRUE)) == 0)
942                 DPRINTF(5, ("sc%d: VT_TRUE\n", sc->unit));
943             break;
944         case VT_ACKACQ:         /* acquire acknowledged, switch completed */
945             if ((error = finish_vt_acq(scp)) == 0)
946                 DPRINTF(5, ("sc%d: VT_ACKACQ\n", sc->unit));
947             break;
948         default:
949             break;
950         }
951         crit_exit();
952         return error;
953
954     case VT_OPENQRY:            /* return free virtual console */
955         for (i = sc->first_vty; i < sc->first_vty + sc->vtys; i++) {
956             tp = VIRTUAL_TTY(sc, i);
957             if (!ISTTYOPEN(tp)) {
958                 *(int *)data = i + 1;
959                 return 0;
960             }
961         }
962         return EINVAL;
963
964     case VT_ACTIVATE:           /* switch to screen *data */
965         i = (*(int *)data == 0) ? scp->index : (*(int *)data - 1);
966         crit_enter();
967         sc_clean_up(sc->cur_scp);
968         crit_exit();
969         return sc_switch_scr(sc, i);
970
971     case VT_WAITACTIVE:         /* wait for switch to occur */
972         i = (*(int *)data == 0) ? scp->index : (*(int *)data - 1);
973         if ((i < sc->first_vty) || (i >= sc->first_vty + sc->vtys))
974             return EINVAL;
975         crit_enter();
976         error = sc_clean_up(sc->cur_scp);
977         crit_exit();
978         if (error)
979             return error;
980         scp = SC_STAT(SC_DEV(sc, i));
981         if (scp == scp->sc->cur_scp)
982             return 0;
983         while ((error=tsleep((caddr_t)&scp->smode, PCATCH,
984                              "waitvt", 0)) == ERESTART) ;
985         return error;
986
987     case VT_GETACTIVE:          /* get active vty # */
988         *(int *)data = sc->cur_scp->index + 1;
989         return 0;
990
991     case VT_GETINDEX:           /* get this vty # */
992         *(int *)data = scp->index + 1;
993         return 0;
994
995     case VT_LOCKSWITCH:         /* prevent vty switching */
996         if ((*(int *)data) & 0x01)
997             sc->flags |= SC_SCRN_VTYLOCK;
998         else
999             sc->flags &= ~SC_SCRN_VTYLOCK;
1000         return 0;
1001
1002     case KDENABIO:              /* allow io operations */
1003         error = suser_cred(ap->a_cred, 0);
1004         if (error != 0)
1005             return error;
1006         if (securelevel > 0)
1007             return EPERM;
1008         curthread->td_lwp->lwp_md.md_regs->tf_eflags |= PSL_IOPL;
1009         return 0;
1010
1011     case KDDISABIO:             /* disallow io operations (default) */
1012         curthread->td_lwp->lwp_md.md_regs->tf_eflags &= ~PSL_IOPL;
1013         return 0;
1014
1015     case KDSKBSTATE:            /* set keyboard state (locks) */
1016         if (*(int *)data & ~LOCK_MASK)
1017             return EINVAL;
1018         scp->status &= ~LOCK_MASK;
1019         scp->status |= *(int *)data;
1020         if (scp == sc->cur_scp)
1021             update_kbd_state(scp, scp->status, LOCK_MASK);
1022         return 0;
1023
1024     case KDGKBSTATE:            /* get keyboard state (locks) */
1025         if (scp == sc->cur_scp)
1026             save_kbd_state(scp);
1027         *(int *)data = scp->status & LOCK_MASK;
1028         return 0;
1029
1030     case KDGETREPEAT:           /* get keyboard repeat & delay rates */
1031     case KDSETREPEAT:           /* set keyboard repeat & delay rates (new) */
1032         error = kbd_ioctl(sc->kbd, cmd, data);
1033         if (error == ENOIOCTL)
1034             error = ENODEV;
1035         return error;
1036
1037     case KDSETRAD:              /* set keyboard repeat & delay rates (old) */
1038         if (*(int *)data & ~0x7f)
1039             return EINVAL;
1040         error = kbd_ioctl(sc->kbd, cmd, data);
1041         if (error == ENOIOCTL)
1042             error = ENODEV;
1043         return error;
1044
1045     case KDSKBMODE:             /* set keyboard mode */
1046         switch (*(int *)data) {
1047         case K_XLATE:           /* switch to XLT ascii mode */
1048         case K_RAW:             /* switch to RAW scancode mode */
1049         case K_CODE:            /* switch to CODE mode */
1050             scp->kbd_mode = *(int *)data;
1051             if (scp == sc->cur_scp)
1052                 kbd_ioctl(sc->kbd, cmd, data);
1053             return 0;
1054         default:
1055             return EINVAL;
1056         }
1057         /* NOT REACHED */
1058
1059     case KDGKBMODE:             /* get keyboard mode */
1060         *(int *)data = scp->kbd_mode;
1061         return 0;
1062
1063     case KDGKBINFO:
1064         error = kbd_ioctl(sc->kbd, cmd, data);
1065         if (error == ENOIOCTL)
1066             error = ENODEV;
1067         return error;
1068
1069     case KDMKTONE:              /* sound the bell */
1070         if (*(int*)data)
1071             sc_bell(scp, (*(int*)data)&0xffff,
1072                     (((*(int*)data)>>16)&0xffff)*hz/1000);
1073         else
1074             sc_bell(scp, scp->bell_pitch, scp->bell_duration);
1075         return 0;
1076
1077     case KIOCSOUND:             /* make tone (*data) hz */
1078         if (scp == sc->cur_scp) {
1079             if (*(int *)data)
1080                 return sc_tone(*(int *)data);
1081             else
1082                 return sc_tone(0);
1083         }
1084         return 0;
1085
1086     case KDGKBTYPE:             /* get keyboard type */
1087         error = kbd_ioctl(sc->kbd, cmd, data);
1088         if (error == ENOIOCTL) {
1089             /* always return something? XXX */
1090             *(int *)data = 0;
1091         }
1092         return 0;
1093
1094     case KDSETLED:              /* set keyboard LED status */
1095         if (*(int *)data & ~LED_MASK)   /* FIXME: LOCK_MASK? */
1096             return EINVAL;
1097         scp->status &= ~LED_MASK;
1098         scp->status |= *(int *)data;
1099         if (scp == sc->cur_scp)
1100             update_kbd_leds(scp, scp->status);
1101         return 0;
1102
1103     case KDGETLED:              /* get keyboard LED status */
1104         if (scp == sc->cur_scp)
1105             save_kbd_state(scp);
1106         *(int *)data = scp->status & LED_MASK;
1107         return 0;
1108
1109     case CONS_SETKBD:           /* set the new keyboard */
1110         {
1111             keyboard_t *newkbd;
1112
1113             crit_enter();
1114             newkbd = kbd_get_keyboard(*(int *)data);
1115             if (newkbd == NULL) {
1116                 crit_exit();
1117                 return EINVAL;
1118             }
1119             error = 0;
1120             if (sc->kbd != newkbd) {
1121                 i = kbd_allocate(newkbd->kb_name, newkbd->kb_unit,
1122                                  (void *)&sc->keyboard, sckbdevent, sc);
1123                 /* i == newkbd->kb_index */
1124                 if (i >= 0) {
1125                     if (sc->kbd != NULL) {
1126                         save_kbd_state(sc->cur_scp);
1127                         kbd_release(sc->kbd, (void *)&sc->keyboard);
1128                     }
1129                     sc->kbd = kbd_get_keyboard(i); /* sc->kbd == newkbd */
1130                     sc->keyboard = i;
1131                     kbd_ioctl(sc->kbd, KDSKBMODE,
1132                               (caddr_t)&sc->cur_scp->kbd_mode);
1133                     update_kbd_state(sc->cur_scp, sc->cur_scp->status,
1134                                      LOCK_MASK);
1135                 } else {
1136                     error = EPERM;      /* XXX */
1137                 }
1138             }
1139             crit_exit();
1140             return error;
1141         }
1142
1143     case CONS_RELKBD:           /* release the current keyboard */
1144         crit_enter();
1145         error = 0;
1146         if (sc->kbd != NULL) {
1147             save_kbd_state(sc->cur_scp);
1148             error = kbd_release(sc->kbd, (void *)&sc->keyboard);
1149             if (error == 0) {
1150                 sc->kbd = NULL;
1151                 sc->keyboard = -1;
1152             }
1153         }
1154         crit_exit();
1155         return error;
1156
1157     case CONS_GETTERM:          /* get the current terminal emulator info */
1158         {
1159             sc_term_sw_t *sw;
1160
1161             if (((term_info_t *)data)->ti_index == 0) {
1162                 sw = scp->tsw;
1163             } else {
1164                 sw = sc_term_match_by_number(((term_info_t *)data)->ti_index);
1165             }
1166             if (sw != NULL) {
1167                 strncpy(((term_info_t *)data)->ti_name, sw->te_name, 
1168                         sizeof(((term_info_t *)data)->ti_name));
1169                 strncpy(((term_info_t *)data)->ti_desc, sw->te_desc, 
1170                         sizeof(((term_info_t *)data)->ti_desc));
1171                 ((term_info_t *)data)->ti_flags = 0;
1172                 return 0;
1173             } else {
1174                 ((term_info_t *)data)->ti_name[0] = '\0';
1175                 ((term_info_t *)data)->ti_desc[0] = '\0';
1176                 ((term_info_t *)data)->ti_flags = 0;
1177                 return EINVAL;
1178             }
1179         }
1180
1181     case CONS_SETTERM:          /* set the current terminal emulator */
1182         crit_enter();
1183         error = sc_init_emulator(scp, ((term_info_t *)data)->ti_name);
1184         /* FIXME: what if scp == sc_console! XXX */
1185         crit_exit();
1186         return error;
1187
1188     case GIO_SCRNMAP:           /* get output translation table */
1189         bcopy(&sc->scr_map, data, sizeof(sc->scr_map));
1190         return 0;
1191
1192     case PIO_SCRNMAP:           /* set output translation table */
1193         bcopy(data, &sc->scr_map, sizeof(sc->scr_map));
1194         for (i=0; i<sizeof(sc->scr_map); i++) {
1195             sc->scr_rmap[sc->scr_map[i]] = i;
1196         }
1197         return 0;
1198
1199     case GIO_KEYMAP:            /* get keyboard translation table */
1200     case PIO_KEYMAP:            /* set keyboard translation table */
1201     case GIO_DEADKEYMAP:        /* get accent key translation table */
1202     case PIO_DEADKEYMAP:        /* set accent key translation table */
1203     case GETFKEY:               /* get function key string */
1204     case SETFKEY:               /* set function key string */
1205         error = kbd_ioctl(sc->kbd, cmd, data);
1206         if (error == ENOIOCTL)
1207             error = ENODEV;
1208         return error;
1209
1210 #ifndef SC_NO_FONT_LOADING
1211
1212     case PIO_FONT8x8:           /* set 8x8 dot font */
1213         if (!ISFONTAVAIL(sc->adp->va_flags))
1214             return ENXIO;
1215         bcopy(data, sc->font_8, 8*256);
1216         sc->fonts_loaded |= FONT_8;
1217         /*
1218          * FONT KLUDGE
1219          * Always use the font page #0. XXX
1220          * Don't load if the current font size is not 8x8.
1221          */
1222         if (ISTEXTSC(sc->cur_scp) && (sc->cur_scp->font_size < 14))
1223             sc_load_font(sc->cur_scp, 0, 8, sc->font_8, 0, 256);
1224         return 0;
1225
1226     case GIO_FONT8x8:           /* get 8x8 dot font */
1227         if (!ISFONTAVAIL(sc->adp->va_flags))
1228             return ENXIO;
1229         if (sc->fonts_loaded & FONT_8) {
1230             bcopy(sc->font_8, data, 8*256);
1231             return 0;
1232         }
1233         else
1234             return ENXIO;
1235
1236     case PIO_FONT8x14:          /* set 8x14 dot font */
1237         if (!ISFONTAVAIL(sc->adp->va_flags))
1238             return ENXIO;
1239         bcopy(data, sc->font_14, 14*256);
1240         sc->fonts_loaded |= FONT_14;
1241         /*
1242          * FONT KLUDGE
1243          * Always use the font page #0. XXX
1244          * Don't load if the current font size is not 8x14.
1245          */
1246         if (ISTEXTSC(sc->cur_scp)
1247             && (sc->cur_scp->font_size >= 14)
1248             && (sc->cur_scp->font_size < 16))
1249             sc_load_font(sc->cur_scp, 0, 14, sc->font_14, 0, 256);
1250         return 0;
1251
1252     case GIO_FONT8x14:          /* get 8x14 dot font */
1253         if (!ISFONTAVAIL(sc->adp->va_flags))
1254             return ENXIO;
1255         if (sc->fonts_loaded & FONT_14) {
1256             bcopy(sc->font_14, data, 14*256);
1257             return 0;
1258         }
1259         else
1260             return ENXIO;
1261
1262     case PIO_FONT8x16:          /* set 8x16 dot font */
1263         if (!ISFONTAVAIL(sc->adp->va_flags))
1264             return ENXIO;
1265         bcopy(data, sc->font_16, 16*256);
1266         sc->fonts_loaded |= FONT_16;
1267         /*
1268          * FONT KLUDGE
1269          * Always use the font page #0. XXX
1270          * Don't load if the current font size is not 8x16.
1271          */
1272         if (ISTEXTSC(sc->cur_scp) && (sc->cur_scp->font_size >= 16))
1273             sc_load_font(sc->cur_scp, 0, 16, sc->font_16, 0, 256);
1274         return 0;
1275
1276     case GIO_FONT8x16:          /* get 8x16 dot font */
1277         if (!ISFONTAVAIL(sc->adp->va_flags))
1278             return ENXIO;
1279         if (sc->fonts_loaded & FONT_16) {
1280             bcopy(sc->font_16, data, 16*256);
1281             return 0;
1282         }
1283         else
1284             return ENXIO;
1285
1286 #endif /* SC_NO_FONT_LOADING */
1287
1288     default:
1289         break;
1290     }
1291
1292     error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, ap->a_cred);
1293     if (error != ENOIOCTL)
1294         return(error);
1295     error = ttioctl(tp, cmd, data, flag);
1296     if (error != ENOIOCTL)
1297         return(error);
1298     return(ENOTTY);
1299 }
1300
1301 static void
1302 scstart(struct tty *tp)
1303 {
1304     struct clist *rbp;
1305     int len;
1306     u_char buf[PCBURST];
1307     scr_stat *scp = SC_STAT(tp->t_dev);
1308
1309     if (scp->status & SLKED ||
1310         (scp == scp->sc->cur_scp && scp->sc->blink_in_progress))
1311         return;
1312     crit_enter();
1313     if (!(tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP))) {
1314         tp->t_state |= TS_BUSY;
1315         rbp = &tp->t_outq;
1316         while (rbp->c_cc) {
1317             len = q_to_b(rbp, buf, PCBURST);
1318             crit_exit();
1319             sc_puts(scp, buf, len);
1320             crit_enter();
1321         }
1322         tp->t_state &= ~TS_BUSY;
1323         ttwwakeup(tp);
1324     }
1325     crit_exit();
1326 }
1327
1328 static void
1329 sccnprobe(struct consdev *cp)
1330 {
1331     int unit;
1332     int flags;
1333
1334     cp->cn_pri = sc_get_cons_priority(&unit, &flags);
1335
1336     /* a video card is always required */
1337     if (!scvidprobe(unit, flags, TRUE))
1338         cp->cn_pri = CN_DEAD;
1339
1340     /* syscons will become console even when there is no keyboard */
1341     sckbdprobe(unit, flags, TRUE);
1342
1343     if (cp->cn_pri == CN_DEAD)
1344         return;
1345
1346     /* initialize required fields */
1347     cp->cn_probegood = 1;
1348 }
1349
1350 static void
1351 sccninit(struct consdev *cp)
1352 {
1353     int unit;
1354     int flags;
1355
1356     sc_get_cons_priority(&unit, &flags);
1357     scinit(unit, flags | SC_KERNEL_CONSOLE);
1358     sc_console_unit = unit;
1359     sc_console = sc_get_softc(unit, SC_KERNEL_CONSOLE)->console_scp;
1360 }
1361
1362 static void
1363 sccninit_fini(struct consdev *cp)
1364 {
1365     cp->cn_dev = make_dev(&sc_ops, SC_CONSOLECTL,
1366                           UID_ROOT, GID_WHEEL, 0600, "consolectl");
1367 }
1368
1369 static void
1370 sccnterm(struct consdev *cp)
1371 {
1372     /* we are not the kernel console any more, release everything */
1373
1374     if (sc_console_unit < 0)
1375         return;                 /* shouldn't happen */
1376
1377 #if 0 /* XXX */
1378     sc_clear_screen(sc_console);
1379     sccnupdate(sc_console);
1380 #endif
1381     scterm(sc_console_unit, SC_KERNEL_CONSOLE);
1382     sc_console_unit = -1;
1383     sc_console = NULL;
1384 }
1385
1386 static void
1387 sccnputc(void *private, int c)
1388 {
1389     u_char buf[1];
1390     scr_stat *scp = sc_console;
1391     void *save;
1392 #ifndef SC_NO_HISTORY
1393     struct tty *tp;
1394 #endif /* !SC_NO_HISTORY */
1395
1396     /* assert(sc_console != NULL) */
1397
1398 #ifndef SC_NO_HISTORY
1399     if (scp == scp->sc->cur_scp && scp->status & SLKED) {
1400         scp->status &= ~SLKED;
1401         update_kbd_state(scp, scp->status, SLKED);
1402         if (scp->status & BUFFER_SAVED) {
1403             if (!sc_hist_restore(scp))
1404                 sc_remove_cutmarking(scp);
1405             scp->status &= ~BUFFER_SAVED;
1406             scp->status |= CURSOR_ENABLED;
1407             sc_draw_cursor_image(scp);
1408         }
1409         tp = VIRTUAL_TTY(scp->sc, scp->index);
1410         if (ISTTYOPEN(tp))
1411             scstart(tp);
1412     }
1413 #endif /* !SC_NO_HISTORY */
1414
1415     save = scp->ts;
1416     if (kernel_console_ts != NULL)
1417         scp->ts = kernel_console_ts;
1418     buf[0] = c;
1419     sc_puts(scp, buf, 1);
1420     scp->ts = save;
1421
1422     crit_enter();
1423     sccnupdate(scp);
1424     crit_exit();
1425 }
1426
1427 static int
1428 sccngetc(void *private)
1429 {
1430     return sccngetch(0);
1431 }
1432
1433 static int
1434 sccncheckc(void *private)
1435 {
1436     return sccngetch(SCGETC_NONBLOCK);
1437 }
1438
1439 static void
1440 sccndbctl(void *private, int on)
1441 {
1442     /* assert(sc_console_unit >= 0) */
1443     /* try to switch to the kernel console screen */
1444     if (on && debugger == 0) {
1445         /*
1446          * TRY to make sure the screen saver is stopped, 
1447          * and the screen is updated before switching to 
1448          * the vty0.
1449          */
1450         scrn_timer(NULL);
1451         if (!cold
1452             && sc_console->sc->cur_scp->smode.mode == VT_AUTO
1453             && sc_console->smode.mode == VT_AUTO) {
1454             sc_console->sc->cur_scp->status |= MOUSE_HIDDEN;
1455             sc_switch_scr(sc_console->sc, sc_console->index);
1456         }
1457     }
1458     if (on)
1459         ++debugger;
1460     else
1461         --debugger;
1462 }
1463
1464 static int
1465 sccngetch(int flags)
1466 {
1467     static struct fkeytab fkey;
1468     static int fkeycp;
1469     scr_stat *scp;
1470     u_char *p;
1471     int cur_mode;
1472     int c;
1473
1474     crit_enter();
1475     /* assert(sc_console != NULL) */
1476
1477     /* 
1478      * Stop the screen saver and update the screen if necessary.
1479      * What if we have been running in the screen saver code... XXX
1480      */
1481     sc_touch_scrn_saver();
1482     scp = sc_console->sc->cur_scp;      /* XXX */
1483     sccnupdate(scp);
1484
1485     if (fkeycp < fkey.len) {
1486         crit_exit();
1487         return fkey.str[fkeycp++];
1488     }
1489
1490     if (scp->sc->kbd == NULL) {
1491         crit_exit();
1492         return -1;
1493     }
1494
1495     /* 
1496      * Make sure the keyboard is accessible even when the kbd device
1497      * driver is disabled.
1498      */
1499     kbd_enable(scp->sc->kbd);
1500
1501     /* we shall always use the keyboard in the XLATE mode here */
1502     cur_mode = scp->kbd_mode;
1503     scp->kbd_mode = K_XLATE;
1504     kbd_ioctl(scp->sc->kbd, KDSKBMODE, (caddr_t)&scp->kbd_mode);
1505
1506     kbd_poll(scp->sc->kbd, TRUE);
1507     c = scgetc(scp->sc, SCGETC_CN | flags);
1508     kbd_poll(scp->sc->kbd, FALSE);
1509
1510     scp->kbd_mode = cur_mode;
1511     kbd_ioctl(scp->sc->kbd, KDSKBMODE, (caddr_t)&scp->kbd_mode);
1512     kbd_disable(scp->sc->kbd);
1513     crit_exit();
1514
1515     switch (KEYFLAGS(c)) {
1516     case 0:     /* normal char */
1517         return KEYCHAR(c);
1518     case FKEY:  /* function key */
1519         p = kbd_get_fkeystr(scp->sc->kbd, KEYCHAR(c), (size_t *)&fkeycp);
1520         fkey.len = fkeycp;
1521         if ((p != NULL) && (fkey.len > 0)) {
1522             bcopy(p, fkey.str, fkey.len);
1523             fkeycp = 1;
1524             return fkey.str[0];
1525         }
1526         return c;       /* XXX */
1527     case NOKEY:
1528     case ERRKEY:
1529     default:
1530         return -1;
1531     }
1532     /* NOT REACHED */
1533 }
1534
1535 static void
1536 sccnupdate(scr_stat *scp)
1537 {
1538     /* this is a cut-down version of scrn_timer()... */
1539
1540     if (scp->sc->font_loading_in_progress || scp->sc->videoio_in_progress)
1541         return;
1542
1543     if (debugger > 0 || panicstr || shutdown_in_progress) {
1544         sc_touch_scrn_saver();
1545     } else if (scp != scp->sc->cur_scp) {
1546         return;
1547     }
1548
1549     if (!run_scrn_saver)
1550         scp->sc->flags &= ~SC_SCRN_IDLE;
1551 #if NSPLASH > 0
1552     if ((saver_mode != CONS_LKM_SAVER) || !(scp->sc->flags & SC_SCRN_IDLE))
1553         if (scp->sc->flags & SC_SCRN_BLANKED)
1554             stop_scrn_saver(scp->sc, current_saver);
1555 #endif /* NSPLASH */
1556
1557     if (scp != scp->sc->cur_scp || scp->sc->blink_in_progress
1558         || scp->sc->switch_in_progress)
1559         return;
1560     /*
1561      * FIXME: unlike scrn_timer(), we call scrn_update() from here even
1562      * when write_in_progress is non-zero.  XXX
1563      */
1564
1565     if (!ISGRAPHSC(scp) && !(scp->sc->flags & SC_SCRN_BLANKED))
1566         scrn_update(scp, TRUE);
1567 }
1568
1569 static void
1570 scrn_timer(void *arg)
1571 {
1572     static int kbd_interval = 0;
1573     struct timeval tv;
1574     sc_softc_t *sc;
1575     scr_stat *scp;
1576     int again;
1577
1578     again = (arg != NULL);
1579     if (arg != NULL)
1580         sc = (sc_softc_t *)arg;
1581     else if (sc_console != NULL)
1582         sc = sc_console->sc;
1583     else
1584         return;
1585
1586     /* don't do anything when we are performing some I/O operations */
1587     if (sc->font_loading_in_progress || sc->videoio_in_progress) {
1588         if (again)
1589             callout_reset(&sc->scrn_timer_ch, hz / 10, scrn_timer, sc);
1590         return;
1591     }
1592     crit_enter();
1593
1594     if ((sc->kbd == NULL) && (sc->config & SC_AUTODETECT_KBD)) {
1595         /* try to allocate a keyboard automatically */
1596         if (++kbd_interval >= 25) {
1597             sc->keyboard = kbd_allocate("*", -1, (void *)&sc->keyboard,
1598                                         sckbdevent, sc);
1599             if (sc->keyboard >= 0) {
1600                 sc->kbd = kbd_get_keyboard(sc->keyboard);
1601                 kbd_ioctl(sc->kbd, KDSKBMODE,
1602                           (caddr_t)&sc->cur_scp->kbd_mode);
1603                 update_kbd_state(sc->cur_scp, sc->cur_scp->status,
1604                                  LOCK_MASK);
1605             }
1606             kbd_interval = 0;
1607         }
1608     }
1609
1610     /* find the vty to update */
1611     scp = sc->cur_scp;
1612
1613     /* should we stop the screen saver? */
1614     getmicrouptime(&tv);
1615     if (debugger > 0 || panicstr || shutdown_in_progress)
1616         sc_touch_scrn_saver();
1617     if (run_scrn_saver) {
1618         if (tv.tv_sec > sc->scrn_time_stamp + scrn_blank_time)
1619             sc->flags |= SC_SCRN_IDLE;
1620         else
1621             sc->flags &= ~SC_SCRN_IDLE;
1622     } else {
1623         sc->scrn_time_stamp = tv.tv_sec;
1624         sc->flags &= ~SC_SCRN_IDLE;
1625         if (scrn_blank_time > 0)
1626             run_scrn_saver = TRUE;
1627     }
1628 #if NSPLASH > 0
1629     if ((saver_mode != CONS_LKM_SAVER) || !(sc->flags & SC_SCRN_IDLE))
1630         if (sc->flags & SC_SCRN_BLANKED)
1631             stop_scrn_saver(sc, current_saver);
1632 #endif /* NSPLASH */
1633
1634     /* should we just return ? */
1635     if (sc->blink_in_progress || sc->switch_in_progress
1636         || sc->write_in_progress) {
1637         if (again)
1638             callout_reset(&sc->scrn_timer_ch, hz / 10, scrn_timer, sc);
1639         crit_exit();
1640         return;
1641     }
1642
1643     /* Update the screen */
1644     scp = sc->cur_scp;          /* cur_scp may have changed... */
1645     if (!ISGRAPHSC(scp) && !(sc->flags & SC_SCRN_BLANKED))
1646         scrn_update(scp, TRUE);
1647
1648 #if NSPLASH > 0
1649     /* should we activate the screen saver? */
1650     if ((saver_mode == CONS_LKM_SAVER) && (sc->flags & SC_SCRN_IDLE))
1651         if (!ISGRAPHSC(scp) || (sc->flags & SC_SCRN_BLANKED))
1652             (*current_saver)(sc, TRUE);
1653 #endif /* NSPLASH */
1654
1655     if (again)
1656         callout_reset(&sc->scrn_timer_ch, hz / 25, scrn_timer, sc);
1657     crit_exit();
1658 }
1659
1660 static int
1661 and_region(int *s1, int *e1, int s2, int e2)
1662 {
1663     if (*e1 < s2 || e2 < *s1)
1664         return FALSE;
1665     *s1 = imax(*s1, s2);
1666     *e1 = imin(*e1, e2);
1667     return TRUE;
1668 }
1669
1670 static void 
1671 scrn_update(scr_stat *scp, int show_cursor)
1672 {
1673     int start;
1674     int end;
1675     int s;
1676     int e;
1677
1678     /* assert(scp == scp->sc->cur_scp) */
1679
1680     ++scp->sc->videoio_in_progress;
1681
1682 #ifndef SC_NO_CUTPASTE
1683     /* remove the previous mouse pointer image if necessary */
1684     if (scp->status & MOUSE_VISIBLE) {
1685         s = scp->mouse_pos;
1686         e = scp->mouse_pos + scp->xsize + 1;
1687         if ((scp->status & (MOUSE_MOVED | MOUSE_HIDDEN))
1688             || and_region(&s, &e, scp->start, scp->end)
1689             || ((scp->status & CURSOR_ENABLED) && 
1690                 (scp->cursor_pos != scp->cursor_oldpos) &&
1691                 (and_region(&s, &e, scp->cursor_pos, scp->cursor_pos)
1692                  || and_region(&s, &e, scp->cursor_oldpos, scp->cursor_oldpos)))) {
1693             sc_remove_mouse_image(scp);
1694             if (scp->end >= scp->xsize*scp->ysize)
1695                 scp->end = scp->xsize*scp->ysize - 1;
1696         }
1697     }
1698 #endif /* !SC_NO_CUTPASTE */
1699
1700 #if 1
1701     /* debug: XXX */
1702     if (scp->end >= scp->xsize*scp->ysize) {
1703         kprintf("scrn_update(): scp->end %d > size_of_screen!!\n", scp->end);
1704         scp->end = scp->xsize*scp->ysize - 1;
1705     }
1706     if (scp->start < 0) {
1707         kprintf("scrn_update(): scp->start %d < 0\n", scp->start);
1708         scp->start = 0;
1709     }
1710 #endif
1711
1712     /* update screen image */
1713     if (scp->start <= scp->end)  {
1714         if (scp->mouse_cut_end >= 0) {
1715             /* there is a marked region for cut & paste */
1716             if (scp->mouse_cut_start <= scp->mouse_cut_end) {
1717                 start = scp->mouse_cut_start;
1718                 end = scp->mouse_cut_end;
1719             } else {
1720                 start = scp->mouse_cut_end;
1721                 end = scp->mouse_cut_start - 1;
1722             }
1723             s = start;
1724             e = end;
1725             /* does the cut-mark region overlap with the update region? */
1726             if (and_region(&s, &e, scp->start, scp->end)) {
1727                 (*scp->rndr->draw)(scp, s, e - s + 1, TRUE);
1728                 s = 0;
1729                 e = start - 1;
1730                 if (and_region(&s, &e, scp->start, scp->end))
1731                     (*scp->rndr->draw)(scp, s, e - s + 1, FALSE);
1732                 s = end + 1;
1733                 e = scp->xsize*scp->ysize - 1;
1734                 if (and_region(&s, &e, scp->start, scp->end))
1735                     (*scp->rndr->draw)(scp, s, e - s + 1, FALSE);
1736             } else {
1737                 (*scp->rndr->draw)(scp, scp->start,
1738                                    scp->end - scp->start + 1, FALSE);
1739             }
1740         } else {
1741             (*scp->rndr->draw)(scp, scp->start,
1742                                scp->end - scp->start + 1, FALSE);
1743         }
1744     }
1745
1746     /* we are not to show the cursor and the mouse pointer... */
1747     if (!show_cursor) {
1748         scp->end = 0;
1749         scp->start = scp->xsize*scp->ysize - 1;
1750         --scp->sc->videoio_in_progress;
1751         return;
1752     }
1753
1754     /* update cursor image */
1755     if (scp->status & CURSOR_ENABLED) {
1756         s = scp->start;
1757         e = scp->end;
1758         /* did cursor move since last time ? */
1759         if (scp->cursor_pos != scp->cursor_oldpos) {
1760             /* do we need to remove old cursor image ? */
1761             if (!and_region(&s, &e, scp->cursor_oldpos, scp->cursor_oldpos))
1762                 sc_remove_cursor_image(scp);
1763             sc_draw_cursor_image(scp);
1764         } else {
1765             if (and_region(&s, &e, scp->cursor_pos, scp->cursor_pos))
1766                 /* cursor didn't move, but has been overwritten */
1767                 sc_draw_cursor_image(scp);
1768             else if (scp->sc->flags & SC_BLINK_CURSOR)
1769                 /* if it's a blinking cursor, update it */
1770                 (*scp->rndr->blink_cursor)(scp, scp->cursor_pos,
1771                                            sc_inside_cutmark(scp,
1772                                                scp->cursor_pos));
1773         }
1774     }
1775
1776 #ifndef SC_NO_CUTPASTE
1777     /* update "pseudo" mouse pointer image */
1778     if (scp->sc->flags & SC_MOUSE_ENABLED) {
1779         if (!(scp->status & (MOUSE_VISIBLE | MOUSE_HIDDEN))) {
1780             scp->status &= ~MOUSE_MOVED;
1781             sc_draw_mouse_image(scp);
1782         }
1783     }
1784 #endif /* SC_NO_CUTPASTE */
1785
1786     scp->end = 0;
1787     scp->start = scp->xsize*scp->ysize - 1;
1788
1789     --scp->sc->videoio_in_progress;
1790 }
1791
1792 #if NSPLASH > 0
1793 static int
1794 scsplash_callback(int event, void *arg)
1795 {
1796     sc_softc_t *sc;
1797     int error;
1798
1799     sc = (sc_softc_t *)arg;
1800
1801     switch (event) {
1802     case SPLASH_INIT:
1803         if (add_scrn_saver(scsplash_saver) == 0) {
1804             sc->flags &= ~SC_SAVER_FAILED;
1805             run_scrn_saver = TRUE;
1806             if (cold && !(boothowto & (RB_VERBOSE | RB_CONFIG))) {
1807                 scsplash_stick(TRUE);
1808                 (*current_saver)(sc, TRUE);
1809             }
1810         }
1811         return 0;
1812
1813     case SPLASH_TERM:
1814         if (current_saver == scsplash_saver) {
1815             scsplash_stick(FALSE);
1816             error = remove_scrn_saver(scsplash_saver);
1817             if (error)
1818                 return error;
1819         }
1820         return 0;
1821
1822     default:
1823         return EINVAL;
1824     }
1825 }
1826
1827 static void
1828 scsplash_saver(sc_softc_t *sc, int show)
1829 {
1830     static int busy = FALSE;
1831     scr_stat *scp;
1832
1833     if (busy)
1834         return;
1835     busy = TRUE;
1836
1837     scp = sc->cur_scp;
1838     if (show) {
1839         if (!(sc->flags & SC_SAVER_FAILED)) {
1840             if (!(sc->flags & SC_SCRN_BLANKED))
1841                 set_scrn_saver_mode(scp, -1, NULL, 0);
1842             switch (splash(sc->adp, TRUE)) {
1843             case 0:             /* succeeded */
1844                 break;
1845             case EAGAIN:        /* try later */
1846                 restore_scrn_saver_mode(scp, FALSE);
1847                 sc_touch_scrn_saver();          /* XXX */
1848                 break;
1849             default:
1850                 sc->flags |= SC_SAVER_FAILED;
1851                 scsplash_stick(FALSE);
1852                 restore_scrn_saver_mode(scp, TRUE);
1853                 kprintf("scsplash_saver(): failed to put up the image\n");
1854                 break;
1855             }
1856         }
1857     } else if (!sticky_splash) {
1858         if ((sc->flags & SC_SCRN_BLANKED) && (splash(sc->adp, FALSE) == 0))
1859             restore_scrn_saver_mode(scp, TRUE);
1860     }
1861     busy = FALSE;
1862 }
1863
1864 static int
1865 add_scrn_saver(void (*this_saver)(sc_softc_t *, int))
1866 {
1867 #if 0
1868     int error;
1869
1870     if (current_saver != none_saver) {
1871         error = remove_scrn_saver(current_saver);
1872         if (error)
1873             return error;
1874     }
1875 #endif
1876     if (current_saver != none_saver)
1877         return EBUSY;
1878
1879     run_scrn_saver = FALSE;
1880     saver_mode = CONS_LKM_SAVER;
1881     current_saver = this_saver;
1882     return 0;
1883 }
1884
1885 static int
1886 remove_scrn_saver(void (*this_saver)(sc_softc_t *, int))
1887 {
1888     if (current_saver != this_saver)
1889         return EINVAL;
1890
1891 #if 0
1892     /*
1893      * In order to prevent `current_saver' from being called by
1894      * the timeout routine `scrn_timer()' while we manipulate 
1895      * the saver list, we shall set `current_saver' to `none_saver' 
1896      * before stopping the current saver, rather than blocking by `splXX()'.
1897      */
1898     current_saver = none_saver;
1899     if (scrn_blanked)
1900         stop_scrn_saver(this_saver);
1901 #endif
1902
1903     /* unblank all blanked screens */
1904     wait_scrn_saver_stop(NULL);
1905     if (scrn_blanked)
1906         return EBUSY;
1907
1908     current_saver = none_saver;
1909     return 0;
1910 }
1911
1912 static int
1913 set_scrn_saver_mode(scr_stat *scp, int mode, u_char *pal, int border)
1914 {
1915
1916     /* assert(scp == scp->sc->cur_scp) */
1917     crit_enter();
1918     if (!ISGRAPHSC(scp))
1919         sc_remove_cursor_image(scp);
1920     scp->splash_save_mode = scp->mode;
1921     scp->splash_save_status = scp->status & (GRAPHICS_MODE | PIXEL_MODE);
1922     scp->status &= ~(GRAPHICS_MODE | PIXEL_MODE);
1923     scp->status |= (UNKNOWN_MODE | SAVER_RUNNING);
1924     scp->sc->flags |= SC_SCRN_BLANKED;
1925     ++scrn_blanked;
1926     crit_exit();
1927     if (mode < 0)
1928         return 0;
1929     scp->mode = mode;
1930     if (set_mode(scp) == 0) {
1931         if (scp->sc->adp->va_info.vi_flags & V_INFO_GRAPHICS)
1932             scp->status |= GRAPHICS_MODE;
1933 #ifndef SC_NO_PALETTE_LOADING
1934         if (pal != NULL)
1935             load_palette(scp->sc->adp, pal);
1936 #endif
1937         sc_set_border(scp, border);
1938         return 0;
1939     } else {
1940         crit_enter();
1941         scp->mode = scp->splash_save_mode;
1942         scp->status &= ~(UNKNOWN_MODE | SAVER_RUNNING);
1943         scp->status |= scp->splash_save_status;
1944         crit_exit();
1945         return 1;
1946     }
1947 }
1948
1949 static int
1950 restore_scrn_saver_mode(scr_stat *scp, int changemode)
1951 {
1952     int mode;
1953     int status;
1954
1955     /* assert(scp == scp->sc->cur_scp) */
1956     crit_enter();
1957     mode = scp->mode;
1958     status = scp->status;
1959     scp->mode = scp->splash_save_mode;
1960     scp->status &= ~(UNKNOWN_MODE | SAVER_RUNNING);
1961     scp->status |= scp->splash_save_status;
1962     scp->sc->flags &= ~SC_SCRN_BLANKED;
1963     if (!changemode) {
1964         if (!ISGRAPHSC(scp))
1965             sc_draw_cursor_image(scp);
1966         --scrn_blanked;
1967         crit_exit();
1968         return 0;
1969     }
1970     if (set_mode(scp) == 0) {
1971 #ifndef SC_NO_PALETTE_LOADING
1972         load_palette(scp->sc->adp, scp->sc->palette);
1973 #endif
1974         --scrn_blanked;
1975         crit_exit();
1976         return 0;
1977     } else {
1978         scp->mode = mode;
1979         scp->status = status;
1980         crit_exit();
1981         return 1;
1982     }
1983 }
1984
1985 static void
1986 stop_scrn_saver(sc_softc_t *sc, void (*saver)(sc_softc_t *, int))
1987 {
1988     (*saver)(sc, FALSE);
1989     run_scrn_saver = FALSE;
1990     /* the screen saver may have chosen not to stop after all... */
1991     if (sc->flags & SC_SCRN_BLANKED)
1992         return;
1993
1994     mark_all(sc->cur_scp);
1995     if (sc->delayed_next_scr)
1996         sc_switch_scr(sc, sc->delayed_next_scr - 1);
1997     wakeup((caddr_t)&scrn_blanked);
1998 }
1999
2000 static int
2001 wait_scrn_saver_stop(sc_softc_t *sc)
2002 {
2003     int error = 0;
2004
2005     while (scrn_blanked > 0) {
2006         run_scrn_saver = FALSE;
2007         if (sc && !(sc->flags & SC_SCRN_BLANKED)) {
2008             error = 0;
2009             break;
2010         }
2011         error = tsleep((caddr_t)&scrn_blanked, PCATCH, "scrsav", 0);
2012         if ((error != 0) && (error != ERESTART))
2013             break;
2014     }
2015     run_scrn_saver = FALSE;
2016     return error;
2017 }
2018 #endif /* NSPLASH */
2019
2020 void
2021 sc_touch_scrn_saver(void)
2022 {
2023     scsplash_stick(FALSE);
2024     run_scrn_saver = FALSE;
2025 }
2026
2027 int
2028 sc_switch_scr(sc_softc_t *sc, u_int next_scr)
2029 {
2030     scr_stat *cur_scp;
2031     struct tty *tp;
2032
2033     DPRINTF(5, ("sc0: sc_switch_scr() %d ", next_scr + 1));
2034
2035     /* prevent switch if previously requested */
2036     if (sc->flags & SC_SCRN_VTYLOCK) {
2037             sc_bell(sc->cur_scp, sc->cur_scp->bell_pitch,
2038                 sc->cur_scp->bell_duration);
2039             return EPERM;
2040     }
2041
2042     /* delay switch if the screen is blanked or being updated */
2043     if ((sc->flags & SC_SCRN_BLANKED) || sc->write_in_progress
2044         || sc->blink_in_progress || sc->videoio_in_progress) {
2045         sc->delayed_next_scr = next_scr + 1;
2046         sc_touch_scrn_saver();
2047         DPRINTF(5, ("switch delayed\n"));
2048         return 0;
2049     }
2050
2051     crit_enter();
2052     cur_scp = sc->cur_scp;
2053
2054     /* we are in the middle of the vty switching process... */
2055     if (sc->switch_in_progress
2056         && (cur_scp->smode.mode == VT_PROCESS)
2057         && cur_scp->proc) {
2058         if (cur_scp->proc != pfind(cur_scp->pid)) {
2059             /* 
2060              * The controlling process has died!!.  Do some clean up.
2061              * NOTE:`cur_scp->proc' and `cur_scp->smode.mode' 
2062              * are not reset here yet; they will be cleared later.
2063              */
2064             DPRINTF(5, ("cur_scp controlling process %d died, ",
2065                cur_scp->pid));
2066             if (cur_scp->status & SWITCH_WAIT_REL) {
2067                 /*
2068                  * Force the previous switch to finish, but return now 
2069                  * with error.
2070                  *
2071                  * note: must be called from a critical section because 
2072                  * finish_vt_rel will call do_switch_scr which releases it
2073                  * temporarily.
2074                  */
2075                 DPRINTF(5, ("reset WAIT_REL, "));
2076                 finish_vt_rel(cur_scp, TRUE);
2077                 crit_exit();
2078                 DPRINTF(5, ("finishing previous switch\n"));
2079                 return EINVAL;
2080             } else if (cur_scp->status & SWITCH_WAIT_ACQ) {
2081                 /* let's assume screen switch has been completed. */
2082                 DPRINTF(5, ("reset WAIT_ACQ, "));
2083                 finish_vt_acq(cur_scp);
2084             } else {
2085                 /* 
2086                  * We are in between screen release and acquisition, and
2087                  * reached here via scgetc() or scrn_timer() which has 
2088                  * interrupted exchange_scr(). Don't do anything stupid.
2089                  */
2090                 DPRINTF(5, ("waiting nothing, "));
2091             }
2092         } else {
2093             /*
2094              * The controlling process is alive, but not responding... 
2095              * It is either buggy or it may be just taking time.
2096              * The following code is a gross kludge to cope with this
2097              * problem for which there is no clean solution. XXX
2098              */
2099             if (cur_scp->status & SWITCH_WAIT_REL) {
2100                 switch (sc->switch_in_progress++) {
2101                 case 1:
2102                     break;
2103                 case 2:
2104                     DPRINTF(5, ("sending relsig again, "));
2105                     signal_vt_rel(cur_scp);
2106                     break;
2107                 case 3:
2108                     break;
2109                 case 4:
2110                 default:
2111                     /*
2112                      * Act as if the controlling program returned
2113                      * VT_FALSE.
2114                      *
2115                      * note: must be called from a critical section because 
2116                      * finish_vt_rel will call do_switch_scr which releases it
2117                      * temporarily.
2118                      */
2119                     DPRINTF(5, ("force reset WAIT_REL, "));
2120                     finish_vt_rel(cur_scp, FALSE);
2121                     crit_exit();
2122                     DPRINTF(5, ("act as if VT_FALSE was seen\n"));
2123                     return EINVAL;
2124                 }
2125             } else if (cur_scp->status & SWITCH_WAIT_ACQ) {
2126                 switch (sc->switch_in_progress++) {
2127                 case 1:
2128                     break;
2129                 case 2:
2130                     DPRINTF(5, ("sending acqsig again, "));
2131                     signal_vt_acq(cur_scp);
2132                     break;
2133                 case 3:
2134                     break;
2135                 case 4:
2136                 default:
2137                      /* clear the flag and finish the previous switch */
2138                     DPRINTF(5, ("force reset WAIT_ACQ, "));
2139                     finish_vt_acq(cur_scp);
2140                     break;
2141                 }
2142             }
2143         }
2144     }
2145
2146     /*
2147      * Return error if an invalid argument is given, or vty switch
2148      * is still in progress.
2149      */
2150     if ((next_scr < sc->first_vty) || (next_scr >= sc->first_vty + sc->vtys)
2151         || sc->switch_in_progress) {
2152         crit_exit();
2153         sc_bell(cur_scp, bios_value.bell_pitch, BELL_DURATION);
2154         DPRINTF(5, ("error 1\n"));
2155         return EINVAL;
2156     }
2157
2158     /*
2159      * Don't allow switching away from the graphics mode vty
2160      * if the switch mode is VT_AUTO, unless the next vty is the same 
2161      * as the current or the current vty has been closed (but showing).
2162      */
2163     tp = VIRTUAL_TTY(sc, cur_scp->index);
2164     if ((cur_scp->index != next_scr)
2165         && ISTTYOPEN(tp)
2166         && (cur_scp->smode.mode == VT_AUTO)
2167         && ISGRAPHSC(cur_scp)) {
2168         crit_exit();
2169         sc_bell(cur_scp, bios_value.bell_pitch, BELL_DURATION);
2170         DPRINTF(5, ("error, graphics mode\n"));
2171         return EINVAL;
2172     }
2173
2174     /*
2175      * Is the wanted vty open? Don't allow switching to a closed vty.
2176      * If we are in DDB, don't switch to a vty in the VT_PROCESS mode.
2177      * Note that we always allow the user to switch to the kernel 
2178      * console even if it is closed.
2179      */
2180     if ((sc_console == NULL) || (next_scr != sc_console->index)) {
2181         tp = VIRTUAL_TTY(sc, next_scr);
2182         if (!ISTTYOPEN(tp)) {
2183             crit_exit();
2184             sc_bell(cur_scp, bios_value.bell_pitch, BELL_DURATION);
2185             DPRINTF(5, ("error 2, requested vty isn't open!\n"));
2186             return EINVAL;
2187         }
2188         if ((debugger > 0) && (SC_STAT(tp->t_dev)->smode.mode == VT_PROCESS)) {
2189             crit_exit();
2190             DPRINTF(5, ("error 3, requested vty is in the VT_PROCESS mode\n"));
2191             return EINVAL;
2192         }
2193     }
2194
2195     /* this is the start of vty switching process... */
2196     ++sc->switch_in_progress;
2197     sc->delayed_next_scr = 0;
2198     sc->old_scp = cur_scp;
2199     sc->new_scp = SC_STAT(SC_DEV(sc, next_scr));
2200     if (sc->new_scp == sc->old_scp) {
2201         sc->switch_in_progress = 0;
2202         wakeup((caddr_t)&sc->new_scp->smode);
2203         crit_exit();
2204         DPRINTF(5, ("switch done (new == old)\n"));
2205         return 0;
2206     }
2207
2208     /* has controlling process died? */
2209     vt_proc_alive(sc->old_scp);
2210     vt_proc_alive(sc->new_scp);
2211
2212     /* wait for the controlling process to release the screen, if necessary */
2213     if (signal_vt_rel(sc->old_scp)) {
2214         crit_exit();
2215         return 0;
2216     }
2217
2218     /* go set up the new vty screen */
2219     crit_exit();
2220     exchange_scr(sc);
2221     crit_enter();
2222
2223     /* wake up processes waiting for this vty */
2224     wakeup((caddr_t)&sc->cur_scp->smode);
2225
2226     /* wait for the controlling process to acknowledge, if necessary */
2227     if (signal_vt_acq(sc->cur_scp)) {
2228         crit_exit();
2229         return 0;
2230     }
2231
2232     sc->switch_in_progress = 0;
2233     if (sc->unit == sc_console_unit)
2234         cons_unavail = FALSE;
2235     crit_exit();
2236     DPRINTF(5, ("switch done\n"));
2237
2238     return 0;
2239 }
2240
2241 /*
2242  * NOTE: must be called from a critical section because do_switch_scr
2243  * will release it temporarily.
2244  */
2245 static void
2246 do_switch_scr(sc_softc_t *sc)
2247 {
2248     vt_proc_alive(sc->new_scp);
2249
2250     crit_exit();
2251     exchange_scr(sc);
2252     crit_enter();
2253     /* sc->cur_scp == sc->new_scp */
2254     wakeup((caddr_t)&sc->cur_scp->smode);
2255
2256     /* wait for the controlling process to acknowledge, if necessary */
2257     if (!signal_vt_acq(sc->cur_scp)) {
2258         sc->switch_in_progress = 0;
2259         if (sc->unit == sc_console_unit)
2260             cons_unavail = FALSE;
2261     }
2262 }
2263
2264 static int
2265 vt_proc_alive(scr_stat *scp)
2266 {
2267     if (scp->proc) {
2268         if (scp->proc == pfind(scp->pid))
2269             return TRUE;
2270         scp->proc = NULL;
2271         scp->smode.mode = VT_AUTO;
2272         DPRINTF(5, ("vt controlling process %d died\n", scp->pid));
2273     }
2274     return FALSE;
2275 }
2276
2277 static int
2278 signal_vt_rel(scr_stat *scp)
2279 {
2280     if (scp->smode.mode != VT_PROCESS)
2281         return FALSE;
2282     scp->status |= SWITCH_WAIT_REL;
2283     ksignal(scp->proc, scp->smode.relsig);
2284     DPRINTF(5, ("sending relsig to %d\n", scp->pid));
2285     return TRUE;
2286 }
2287
2288 static int
2289 signal_vt_acq(scr_stat *scp)
2290 {
2291     if (scp->smode.mode != VT_PROCESS)
2292         return FALSE;
2293     if (scp->sc->unit == sc_console_unit)
2294         cons_unavail = TRUE;
2295     scp->status |= SWITCH_WAIT_ACQ;
2296     ksignal(scp->proc, scp->smode.acqsig);
2297     DPRINTF(5, ("sending acqsig to %d\n", scp->pid));
2298     return TRUE;
2299 }
2300
2301 /*
2302  * NOTE: must be called from a critical section because do_switch_scr
2303  * will release it temporarily.
2304  */
2305 static int
2306 finish_vt_rel(scr_stat *scp, int release)
2307 {
2308     if (scp == scp->sc->old_scp && scp->status & SWITCH_WAIT_REL) {
2309         scp->status &= ~SWITCH_WAIT_REL;
2310         if (release)
2311             do_switch_scr(scp->sc);
2312         else
2313             scp->sc->switch_in_progress = 0;
2314         return 0;
2315     }
2316     return EINVAL;
2317 }
2318
2319 static int
2320 finish_vt_acq(scr_stat *scp)
2321 {
2322     if (scp == scp->sc->new_scp && scp->status & SWITCH_WAIT_ACQ) {
2323         scp->status &= ~SWITCH_WAIT_ACQ;
2324         scp->sc->switch_in_progress = 0;
2325         return 0;
2326     }
2327     return EINVAL;
2328 }
2329
2330 static void
2331 exchange_scr(sc_softc_t *sc)
2332 {
2333     scr_stat *scp;
2334
2335     /* save the current state of video and keyboard */
2336     sc_move_cursor(sc->old_scp, sc->old_scp->xpos, sc->old_scp->ypos);
2337     if (!ISGRAPHSC(sc->old_scp))
2338         sc_remove_cursor_image(sc->old_scp);
2339     if (sc->old_scp->kbd_mode == K_XLATE)
2340         save_kbd_state(sc->old_scp);
2341
2342     /* set up the video for the new screen */
2343     scp = sc->cur_scp = sc->new_scp;
2344     if (sc->old_scp->mode != scp->mode || ISUNKNOWNSC(sc->old_scp))
2345         set_mode(scp);
2346     else
2347         sc_vtb_init(&scp->scr, VTB_FRAMEBUFFER, scp->xsize, scp->ysize,
2348                     (void *)sc->adp->va_window, FALSE);
2349     scp->status |= MOUSE_HIDDEN;
2350     sc_move_cursor(scp, scp->xpos, scp->ypos);
2351     if (!ISGRAPHSC(scp))
2352         sc_set_cursor_image(scp);
2353 #ifndef SC_NO_PALETTE_LOADING
2354     if (ISGRAPHSC(sc->old_scp))
2355         load_palette(sc->adp, sc->palette);
2356 #endif
2357     sc_set_border(scp, scp->border);
2358
2359     /* set up the keyboard for the new screen */
2360     if (sc->old_scp->kbd_mode != scp->kbd_mode)
2361         kbd_ioctl(sc->kbd, KDSKBMODE, (caddr_t)&scp->kbd_mode);
2362     update_kbd_state(scp, scp->status, LOCK_MASK);
2363
2364     mark_all(scp);
2365 }
2366
2367 void
2368 sc_puts(scr_stat *scp, u_char *buf, int len)
2369 {
2370 #if NSPLASH > 0
2371     /* make screensaver happy */
2372     if (!sticky_splash && scp == scp->sc->cur_scp)
2373         run_scrn_saver = FALSE;
2374 #endif
2375
2376     if (scp->tsw)
2377         (*scp->tsw->te_puts)(scp, buf, len);
2378
2379     if (scp->sc->delayed_next_scr)
2380         sc_switch_scr(scp->sc, scp->sc->delayed_next_scr - 1);
2381 }
2382
2383 void
2384 sc_draw_cursor_image(scr_stat *scp)
2385 {
2386     /* assert(scp == scp->sc->cur_scp); */
2387     ++scp->sc->videoio_in_progress;
2388     (*scp->rndr->draw_cursor)(scp, scp->cursor_pos,
2389                               scp->sc->flags & SC_BLINK_CURSOR, TRUE,
2390                               sc_inside_cutmark(scp, scp->cursor_pos));
2391     scp->cursor_oldpos = scp->cursor_pos;
2392     --scp->sc->videoio_in_progress;
2393 }
2394
2395 void
2396 sc_remove_cursor_image(scr_stat *scp)
2397 {
2398     /* assert(scp == scp->sc->cur_scp); */
2399     ++scp->sc->videoio_in_progress;
2400     (*scp->rndr->draw_cursor)(scp, scp->cursor_oldpos,
2401                               scp->sc->flags & SC_BLINK_CURSOR, FALSE,
2402                               sc_inside_cutmark(scp, scp->cursor_oldpos));
2403     --scp->sc->videoio_in_progress;
2404 }
2405
2406 static void
2407 update_cursor_image(scr_stat *scp)
2408 {
2409     int blink;
2410
2411     if (scp->sc->flags & SC_CHAR_CURSOR) {
2412         scp->cursor_base = imax(0, scp->sc->cursor_base);
2413         scp->cursor_height = imin(scp->sc->cursor_height, scp->font_size);
2414     } else {
2415         scp->cursor_base = 0;
2416         scp->cursor_height = scp->font_size;
2417     }
2418     blink = scp->sc->flags & SC_BLINK_CURSOR;
2419
2420     /* assert(scp == scp->sc->cur_scp); */
2421     ++scp->sc->videoio_in_progress;
2422     (*scp->rndr->draw_cursor)(scp, scp->cursor_oldpos, blink, FALSE, 
2423                               sc_inside_cutmark(scp, scp->cursor_pos));
2424     (*scp->rndr->set_cursor)(scp, scp->cursor_base, scp->cursor_height, blink);
2425     (*scp->rndr->draw_cursor)(scp, scp->cursor_pos, blink, TRUE, 
2426                               sc_inside_cutmark(scp, scp->cursor_pos));
2427     --scp->sc->videoio_in_progress;
2428 }
2429
2430 void
2431 sc_set_cursor_image(scr_stat *scp)
2432 {
2433     if (scp->sc->flags & SC_CHAR_CURSOR) {
2434         scp->cursor_base = imax(0, scp->sc->cursor_base);
2435         scp->cursor_height = imin(scp->sc->cursor_height, scp->font_size);
2436     } else {
2437         scp->cursor_base = 0;
2438         scp->cursor_height = scp->font_size;
2439     }
2440
2441     /* assert(scp == scp->sc->cur_scp); */
2442     ++scp->sc->videoio_in_progress;
2443     (*scp->rndr->set_cursor)(scp, scp->cursor_base, scp->cursor_height,
2444                              scp->sc->flags & SC_BLINK_CURSOR);
2445     --scp->sc->videoio_in_progress;
2446 }
2447
2448 static void
2449 scinit(int unit, int flags)
2450 {
2451     /*
2452      * When syscons is being initialized as the kernel console, malloc()
2453      * is not yet functional, because various kernel structures has not been
2454      * fully initialized yet.  Therefore, we need to declare the following
2455      * static buffers for the console.  This is less than ideal, 
2456      * but is necessry evil for the time being.  XXX
2457      */
2458     static scr_stat main_console;
2459     static u_short sc_buffer[ROW*COL];  /* XXX */
2460 #ifndef SC_NO_FONT_LOADING
2461     static u_char font_8[256*8];
2462     static u_char font_14[256*14];
2463     static u_char font_16[256*16];
2464 #endif
2465
2466     sc_softc_t *sc;
2467     scr_stat *scp;
2468     video_adapter_t *adp;
2469     int col;
2470     int row;
2471     int i;
2472
2473     /* one time initialization */
2474     if (init_done == COLD)
2475         sc_get_bios_values(&bios_value);
2476     init_done = WARM;
2477
2478     /*
2479      * Allocate resources.  Even if we are being called for the second
2480      * time, we must allocate them again, because they might have 
2481      * disappeared...
2482      */
2483     sc = sc_get_softc(unit, flags & SC_KERNEL_CONSOLE);
2484     adp = NULL;
2485     if (sc->adapter >= 0) {
2486         vid_release(sc->adp, (void *)&sc->adapter);
2487         adp = sc->adp;
2488         sc->adp = NULL;
2489     }
2490     if (sc->keyboard >= 0) {
2491         DPRINTF(5, ("sc%d: releasing kbd%d\n", unit, sc->keyboard));
2492         i = kbd_release(sc->kbd, (void *)&sc->keyboard);
2493         DPRINTF(5, ("sc%d: kbd_release returned %d\n", unit, i));
2494         if (sc->kbd != NULL) {
2495             DPRINTF(5, ("sc%d: kbd != NULL!, index:%d, unit:%d, flags:0x%x\n",
2496                 unit, sc->kbd->kb_index, sc->kbd->kb_unit, sc->kbd->kb_flags));
2497         }
2498         sc->kbd = NULL;
2499     }
2500     sc->adapter = vid_allocate("*", unit, (void *)&sc->adapter);
2501     sc->adp = vid_get_adapter(sc->adapter);
2502     /* assert((sc->adapter >= 0) && (sc->adp != NULL)) */
2503     sc->keyboard = kbd_allocate("*", unit, (void *)&sc->keyboard,
2504                                 sckbdevent, sc);
2505     DPRINTF(1, ("sc%d: keyboard %d\n", unit, sc->keyboard));
2506     sc->kbd = kbd_get_keyboard(sc->keyboard);
2507     if (sc->kbd != NULL) {
2508         DPRINTF(1, ("sc%d: kbd index:%d, unit:%d, flags:0x%x\n",
2509                 unit, sc->kbd->kb_index, sc->kbd->kb_unit, sc->kbd->kb_flags));
2510     }
2511
2512     if (!(sc->flags & SC_INIT_DONE) || (adp != sc->adp)) {
2513
2514         sc->initial_mode = sc->adp->va_initial_mode;
2515
2516 #ifndef SC_NO_FONT_LOADING
2517         if (flags & SC_KERNEL_CONSOLE) {
2518             sc->font_8 = font_8;
2519             sc->font_14 = font_14;
2520             sc->font_16 = font_16;
2521         } else if (sc->font_8 == NULL) {
2522             /* assert(sc_malloc) */
2523             sc->font_8 = kmalloc(sizeof(font_8), M_SYSCONS, M_WAITOK);
2524             sc->font_14 = kmalloc(sizeof(font_14), M_SYSCONS, M_WAITOK);
2525             sc->font_16 = kmalloc(sizeof(font_16), M_SYSCONS, M_WAITOK);
2526         }
2527 #endif
2528
2529         /* extract the hardware cursor location and hide the cursor for now */
2530         (*vidsw[sc->adapter]->read_hw_cursor)(sc->adp, &col, &row);
2531         (*vidsw[sc->adapter]->set_hw_cursor)(sc->adp, -1, -1);
2532
2533         /* set up the first console */
2534         sc->first_vty = unit*MAXCONS;
2535         sc->vtys = MAXCONS;             /* XXX: should be configurable */
2536         if (flags & SC_KERNEL_CONSOLE) {
2537             scp = &main_console;
2538             sc->console_scp = scp;
2539             init_scp(sc, sc->first_vty, scp);
2540             sc_vtb_init(&scp->vtb, VTB_MEMORY, scp->xsize, scp->ysize,
2541                         (void *)sc_buffer, FALSE);
2542             if (sc_init_emulator(scp, SC_DFLT_TERM))
2543                 sc_init_emulator(scp, "*");
2544             (*scp->tsw->te_default_attr)(scp,
2545                                          kernel_default.std_color,
2546                                          kernel_default.rev_color);
2547         } else {
2548             /* assert(sc_malloc) */
2549             sc->dev = kmalloc(sizeof(cdev_t)*sc->vtys, M_SYSCONS, M_WAITOK | M_ZERO);
2550             sc->dev[0] = make_dev(&sc_ops, unit*MAXCONS, UID_ROOT, 
2551                                 GID_WHEEL, 0600, "ttyv%r", unit*MAXCONS);
2552             sc->dev[0]->si_tty = ttymalloc(sc->dev[0]->si_tty);
2553             scp = alloc_scp(sc, sc->first_vty);
2554             sc->dev[0]->si_drv1 = scp;
2555         }
2556         sc->cur_scp = scp;
2557
2558         /* copy screen to temporary buffer */
2559         sc_vtb_init(&scp->scr, VTB_FRAMEBUFFER, scp->xsize, scp->ysize,
2560                     (void *)scp->sc->adp->va_window, FALSE);
2561         if (ISTEXTSC(scp))
2562             sc_vtb_copy(&scp->scr, 0, &scp->vtb, 0, scp->xsize*scp->ysize);
2563
2564         /* move cursors to the initial positions */
2565         if (col >= scp->xsize)
2566             col = 0;
2567         if (row >= scp->ysize)
2568             row = scp->ysize - 1;
2569         scp->xpos = col;
2570         scp->ypos = row;
2571         scp->cursor_pos = scp->cursor_oldpos = row*scp->xsize + col;
2572         if (bios_value.cursor_end < scp->font_size)
2573             sc->cursor_base = scp->font_size - bios_value.cursor_end - 1;
2574         else
2575             sc->cursor_base = 0;
2576         i = bios_value.cursor_end - bios_value.cursor_start + 1;
2577         sc->cursor_height = imin(i, scp->font_size);
2578 #ifndef SC_NO_SYSMOUSE
2579         sc_mouse_move(scp, scp->xpixel/2, scp->ypixel/2);
2580 #endif
2581         if (!ISGRAPHSC(scp)) {
2582             sc_set_cursor_image(scp);
2583             sc_draw_cursor_image(scp);
2584         }
2585
2586         /* save font and palette */
2587 #ifndef SC_NO_FONT_LOADING
2588         sc->fonts_loaded = 0;
2589         if (ISFONTAVAIL(sc->adp->va_flags)) {
2590 #ifdef SC_DFLT_FONT
2591             bcopy(dflt_font_8, sc->font_8, sizeof(dflt_font_8));
2592             bcopy(dflt_font_14, sc->font_14, sizeof(dflt_font_14));
2593             bcopy(dflt_font_16, sc->font_16, sizeof(dflt_font_16));
2594             sc->fonts_loaded = FONT_16 | FONT_14 | FONT_8;
2595             if (scp->font_size < 14) {
2596                 sc_load_font(scp, 0, 8, sc->font_8, 0, 256);
2597             } else if (scp->font_size >= 16) {
2598                 sc_load_font(scp, 0, 16, sc->font_16, 0, 256);
2599             } else {
2600                 sc_load_font(scp, 0, 14, sc->font_14, 0, 256);
2601             }
2602 #else /* !SC_DFLT_FONT */
2603             if (scp->font_size < 14) {
2604                 sc_save_font(scp, 0, 8, sc->font_8, 0, 256);
2605                 sc->fonts_loaded = FONT_8;
2606             } else if (scp->font_size >= 16) {
2607                 sc_save_font(scp, 0, 16, sc->font_16, 0, 256);
2608                 sc->fonts_loaded = FONT_16;
2609             } else {
2610                 sc_save_font(scp, 0, 14, sc->font_14, 0, 256);
2611                 sc->fonts_loaded = FONT_14;
2612             }
2613 #endif /* SC_DFLT_FONT */
2614             /* FONT KLUDGE: always use the font page #0. XXX */
2615             sc_show_font(scp, 0);
2616         }
2617 #endif /* !SC_NO_FONT_LOADING */
2618
2619 #ifndef SC_NO_PALETTE_LOADING
2620         save_palette(sc->adp, sc->palette);
2621 #endif
2622
2623 #if NSPLASH > 0
2624         if (!(sc->flags & SC_SPLASH_SCRN) && (flags & SC_KERNEL_CONSOLE)) {
2625             /* we are ready to put up the splash image! */
2626             splash_init(sc->adp, scsplash_callback, sc);
2627             sc->flags |= SC_SPLASH_SCRN;
2628         }
2629 #endif /* NSPLASH */
2630     }
2631
2632     /* the rest is not necessary, if we have done it once */
2633     if (sc->flags & SC_INIT_DONE)
2634         return;
2635
2636     /* initialize mapscrn arrays to a one to one map */
2637     for (i = 0; i < sizeof(sc->scr_map); i++)
2638         sc->scr_map[i] = sc->scr_rmap[i] = i;
2639
2640     sc->flags |= SC_INIT_DONE;
2641 }
2642
2643 static void
2644 scterm(int unit, int flags)
2645 {
2646     sc_softc_t *sc;
2647     scr_stat *scp;
2648
2649     sc = sc_get_softc(unit, flags & SC_KERNEL_CONSOLE);
2650     if (sc == NULL)
2651         return;                 /* shouldn't happen */
2652
2653 #if NSPLASH > 0
2654     /* this console is no longer available for the splash screen */
2655     if (sc->flags & SC_SPLASH_SCRN) {
2656         splash_term(sc->adp);
2657         sc->flags &= ~SC_SPLASH_SCRN;
2658     }
2659 #endif /* NSPLASH */
2660
2661 #if 0 /* XXX */
2662     /* move the hardware cursor to the upper-left corner */
2663     (*vidsw[sc->adapter]->set_hw_cursor)(sc->adp, 0, 0);
2664 #endif
2665
2666     /* release the keyboard and the video card */
2667     if (sc->keyboard >= 0)
2668         kbd_release(sc->kbd, &sc->keyboard);
2669     if (sc->adapter >= 0)
2670         vid_release(sc->adp, &sc->adapter);
2671
2672     /* 
2673      * Stop the terminal emulator, if any.  If operating on the
2674      * kernel console sc->dev may not be setup yet.
2675      */
2676     if (flags & SC_KERNEL_CONSOLE)
2677         scp = sc->console_scp;
2678     else
2679         scp = SC_STAT(sc->dev[0]);
2680     if (scp->tsw)
2681         (*scp->tsw->te_term)(scp, &scp->ts);
2682     if (scp->ts != NULL)
2683         kfree(scp->ts, M_SYSCONS);
2684
2685     /* clear the structure */
2686     if (!(flags & SC_KERNEL_CONSOLE)) {
2687         /* XXX: We need delete_dev() for this */
2688         kfree(sc->dev, M_SYSCONS);
2689 #if 0
2690         /* XXX: We need a ttyunregister for this */
2691         kfree(sc->tty, M_SYSCONS);
2692 #endif
2693 #ifndef SC_NO_FONT_LOADING
2694         kfree(sc->font_8, M_SYSCONS);
2695         kfree(sc->font_14, M_SYSCONS);
2696         kfree(sc->font_16, M_SYSCONS);
2697 #endif
2698         /* XXX vtb, history */
2699     }
2700     bzero(sc, sizeof(*sc));
2701     sc->keyboard = -1;
2702     sc->adapter = -1;
2703 }
2704
2705 static void
2706 scshutdown(void *arg, int howto)
2707 {
2708     /* assert(sc_console != NULL) */
2709
2710     sc_touch_scrn_saver();
2711     if (!cold && sc_console
2712         && sc_console->sc->cur_scp->smode.mode == VT_AUTO 
2713         && sc_console->smode.mode == VT_AUTO)
2714         sc_switch_scr(sc_console->sc, sc_console->index);
2715     shutdown_in_progress = TRUE;
2716 }
2717
2718 int
2719 sc_clean_up(scr_stat *scp)
2720 {
2721 #if NSPLASH > 0
2722     int error;
2723 #endif /* NSPLASH */
2724
2725     if (scp->sc->flags & SC_SCRN_BLANKED) {
2726         sc_touch_scrn_saver();
2727 #if NSPLASH > 0
2728         if ((error = wait_scrn_saver_stop(scp->sc)))
2729             return error;
2730 #endif /* NSPLASH */
2731     }
2732     scp->status |= MOUSE_HIDDEN;
2733     sc_remove_mouse_image(scp);
2734     sc_remove_cutmarking(scp);
2735     return 0;
2736 }
2737
2738 void
2739 sc_alloc_scr_buffer(scr_stat *scp, int wait, int discard)
2740 {
2741     sc_vtb_t new;
2742     sc_vtb_t old;
2743
2744     old = scp->vtb;
2745     sc_vtb_init(&new, VTB_MEMORY, scp->xsize, scp->ysize, NULL, wait);
2746     if (!discard && (old.vtb_flags & VTB_VALID)) {
2747         /* retain the current cursor position and buffer contants */
2748         scp->cursor_oldpos = scp->cursor_pos;
2749         /* 
2750          * This works only if the old buffer has the same size as or larger 
2751          * than the new one. XXX
2752          */
2753         sc_vtb_copy(&old, 0, &new, 0, scp->xsize*scp->ysize);
2754         scp->vtb = new;
2755     } else {
2756         scp->vtb = new;
2757         sc_vtb_destroy(&old);
2758     }
2759
2760 #ifndef SC_NO_SYSMOUSE
2761     /* move the mouse cursor at the center of the screen */
2762     sc_mouse_move(scp, scp->xpixel / 2, scp->ypixel / 2);
2763 #endif
2764 }
2765
2766 static scr_stat *
2767 alloc_scp(sc_softc_t *sc, int vty)
2768 {
2769     scr_stat *scp;
2770
2771     /* assert(sc_malloc) */
2772
2773     scp = kmalloc(sizeof(scr_stat), M_SYSCONS, M_WAITOK);
2774     init_scp(sc, vty, scp);
2775
2776     sc_alloc_scr_buffer(scp, TRUE, TRUE);
2777     if (sc_init_emulator(scp, SC_DFLT_TERM))
2778         sc_init_emulator(scp, "*");
2779
2780 #ifndef SC_NO_CUTPASTE
2781     sc_alloc_cut_buffer(scp, TRUE);
2782 #endif
2783
2784 #ifndef SC_NO_HISTORY
2785     sc_alloc_history_buffer(scp, 0, 0, TRUE);
2786 #endif
2787
2788     return scp;
2789 }
2790
2791 static void
2792 init_scp(sc_softc_t *sc, int vty, scr_stat *scp)
2793 {
2794     video_info_t info;
2795
2796     bzero(scp, sizeof(*scp));
2797
2798     scp->index = vty;
2799     scp->sc = sc;
2800     scp->status = 0;
2801     scp->mode = sc->initial_mode;
2802     callout_init(&scp->blink_screen_ch);
2803     (*vidsw[sc->adapter]->get_info)(sc->adp, scp->mode, &info);
2804     if (info.vi_flags & V_INFO_GRAPHICS) {
2805         scp->status |= GRAPHICS_MODE;
2806         scp->xpixel = info.vi_width;
2807         scp->ypixel = info.vi_height;
2808         scp->xsize = info.vi_width/8;
2809         scp->ysize = info.vi_height/info.vi_cheight;
2810         scp->font_size = 0;
2811         scp->font = NULL;
2812     } else {
2813         scp->xsize = info.vi_width;
2814         scp->ysize = info.vi_height;
2815         scp->xpixel = scp->xsize*8;
2816         scp->ypixel = scp->ysize*info.vi_cheight;
2817         if (info.vi_cheight < 14) {
2818             scp->font_size = 8;
2819 #ifndef SC_NO_FONT_LOADING
2820             scp->font = sc->font_8;
2821 #else
2822             scp->font = NULL;
2823 #endif
2824         } else if (info.vi_cheight >= 16) {
2825             scp->font_size = 16;
2826 #ifndef SC_NO_FONT_LOADING
2827             scp->font = sc->font_16;
2828 #else
2829             scp->font = NULL;
2830 #endif
2831         } else {
2832             scp->font_size = 14;
2833 #ifndef SC_NO_FONT_LOADING
2834             scp->font = sc->font_14;
2835 #else
2836             scp->font = NULL;
2837 #endif
2838         }
2839     }
2840     sc_vtb_init(&scp->vtb, VTB_MEMORY, 0, 0, NULL, FALSE);
2841     sc_vtb_init(&scp->scr, VTB_FRAMEBUFFER, 0, 0, NULL, FALSE);
2842     scp->xoff = scp->yoff = 0;
2843     scp->xpos = scp->ypos = 0;
2844     scp->start = scp->xsize * scp->ysize - 1;
2845     scp->end = 0;
2846     scp->tsw = NULL;
2847     scp->ts = NULL;
2848     scp->rndr = NULL;
2849     scp->border = BG_BLACK;
2850     scp->cursor_base = sc->cursor_base;
2851     scp->cursor_height = imin(sc->cursor_height, scp->font_size);
2852     scp->mouse_cut_start = scp->xsize*scp->ysize;
2853     scp->mouse_cut_end = -1;
2854     scp->mouse_signal = 0;
2855     scp->mouse_pid = 0;
2856     scp->mouse_proc = NULL;
2857     scp->kbd_mode = K_XLATE;
2858     scp->bell_pitch = bios_value.bell_pitch;
2859     scp->bell_duration = BELL_DURATION;
2860     scp->status |= (bios_value.shift_state & NLKED);
2861     scp->status |= CURSOR_ENABLED | MOUSE_HIDDEN;
2862     scp->pid = 0;
2863     scp->proc = NULL;
2864     scp->smode.mode = VT_AUTO;
2865     scp->history = NULL;
2866     scp->history_pos = 0;
2867     scp->history_size = 0;
2868 }
2869
2870 int
2871 sc_init_emulator(scr_stat *scp, char *name)
2872 {
2873     sc_term_sw_t *sw;
2874     sc_rndr_sw_t *rndr;
2875     void *p;
2876     int error;
2877
2878     if (name == NULL)   /* if no name is given, use the current emulator */
2879         sw = scp->tsw;
2880     else                /* ...otherwise find the named emulator */
2881         sw = sc_term_match(name);
2882     if (sw == NULL)
2883         return EINVAL;
2884
2885     rndr = NULL;
2886     if (strcmp(sw->te_renderer, "*") != 0) {
2887         rndr = sc_render_match(scp, sw->te_renderer,
2888                                scp->status & (GRAPHICS_MODE | PIXEL_MODE));
2889     }
2890     if (rndr == NULL) {
2891         rndr = sc_render_match(scp, scp->sc->adp->va_name,
2892                                scp->status & (GRAPHICS_MODE | PIXEL_MODE));
2893         if (rndr == NULL)
2894             return ENODEV;
2895     }
2896
2897     if (sw == scp->tsw) {
2898         error = (*sw->te_init)(scp, &scp->ts, SC_TE_WARM_INIT);
2899         scp->rndr = rndr;
2900         scp->rndr->init(scp);
2901         sc_clear_screen(scp);
2902         /* assert(error == 0); */
2903         return error;
2904     }
2905
2906     if (sc_malloc && (sw->te_size > 0))
2907         p = kmalloc(sw->te_size, M_SYSCONS, M_NOWAIT);
2908     else
2909         p = NULL;
2910     error = (*sw->te_init)(scp, &p, SC_TE_COLD_INIT);
2911     if (error)
2912         return error;
2913
2914     if (scp->tsw)
2915         (*scp->tsw->te_term)(scp, &scp->ts);
2916     if (scp->ts != NULL)
2917         kfree(scp->ts, M_SYSCONS);
2918     scp->tsw = sw;
2919     scp->ts = p;
2920     scp->rndr = rndr;
2921     scp->rndr->init(scp);
2922
2923     /* XXX */
2924     (*sw->te_default_attr)(scp, user_default.std_color, user_default.rev_color);
2925     sc_clear_screen(scp);
2926
2927     return 0;
2928 }
2929
2930 /*
2931  * scgetc(flags) - get character from keyboard.
2932  * If flags & SCGETC_CN, then avoid harmful side effects.
2933  * If flags & SCGETC_NONBLOCK, then wait until a key is pressed, else
2934  * return NOKEY if there is nothing there.
2935  */
2936 static u_int
2937 scgetc(sc_softc_t *sc, u_int flags)
2938 {
2939     scr_stat *scp;
2940 #ifndef SC_NO_HISTORY
2941     struct tty *tp;
2942 #endif
2943     u_int c;
2944     int this_scr;
2945     int f;
2946     int i;
2947
2948     if (sc->kbd == NULL)
2949         return NOKEY;
2950
2951 next_code:
2952 #if 1
2953     /* I don't like this, but... XXX */
2954     if (flags & SCGETC_CN)
2955         sccnupdate(sc->cur_scp);
2956 #endif
2957     scp = sc->cur_scp;
2958     /* first see if there is something in the keyboard port */
2959     for (;;) {
2960         c = kbd_read_char(sc->kbd, !(flags & SCGETC_NONBLOCK));
2961         if (c == ERRKEY) {
2962             if (!(flags & SCGETC_CN))
2963                 sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
2964         } else if (c == NOKEY)
2965             return c;
2966         else
2967             break;
2968     }
2969
2970     /* make screensaver happy */
2971     if (!(c & RELKEY))
2972         sc_touch_scrn_saver();
2973
2974     if (!(flags & SCGETC_CN))
2975         /* do the /dev/random device a favour */
2976         add_keyboard_randomness(c);
2977
2978     if (scp->kbd_mode != K_XLATE)
2979         return KEYCHAR(c);
2980
2981     /* if scroll-lock pressed allow history browsing */
2982     if (!ISGRAPHSC(scp) && scp->history && scp->status & SLKED) {
2983
2984         scp->status &= ~CURSOR_ENABLED;
2985         sc_remove_cursor_image(scp);
2986
2987 #ifndef SC_NO_HISTORY
2988         if (!(scp->status & BUFFER_SAVED)) {
2989             scp->status |= BUFFER_SAVED;
2990             sc_hist_save(scp);
2991         }
2992         switch (c) {
2993         /* FIXME: key codes */
2994         case SPCLKEY | FKEY | F(49):  /* home key */
2995             sc_remove_cutmarking(scp);
2996             sc_hist_home(scp);
2997             goto next_code;
2998
2999         case SPCLKEY | FKEY | F(57):  /* end key */
3000             sc_remove_cutmarking(scp);
3001             sc_hist_end(scp);
3002             goto next_code;
3003
3004         case SPCLKEY | FKEY | F(50):  /* up arrow key */
3005             sc_remove_cutmarking(scp);
3006             if (sc_hist_up_line(scp))
3007                 if (!(flags & SCGETC_CN))
3008                     sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3009             goto next_code;
3010
3011         case SPCLKEY | FKEY | F(58):  /* down arrow key */
3012             sc_remove_cutmarking(scp);
3013             if (sc_hist_down_line(scp))
3014                 if (!(flags & SCGETC_CN))
3015                     sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3016             goto next_code;
3017
3018         case SPCLKEY | FKEY | F(51):  /* page up key */
3019             sc_remove_cutmarking(scp);
3020             for (i=0; i<scp->ysize; i++)
3021             if (sc_hist_up_line(scp)) {
3022                 if (!(flags & SCGETC_CN))
3023                     sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3024                 break;
3025             }
3026             goto next_code;
3027
3028         case SPCLKEY | FKEY | F(59):  /* page down key */
3029             sc_remove_cutmarking(scp);
3030             for (i=0; i<scp->ysize; i++)
3031             if (sc_hist_down_line(scp)) {
3032                 if (!(flags & SCGETC_CN))
3033                     sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3034                 break;
3035             }
3036             goto next_code;
3037         }
3038 #endif /* SC_NO_HISTORY */
3039     }
3040
3041     /* 
3042      * Process and consume special keys here.  Return a plain char code
3043      * or a char code with the META flag or a function key code.
3044      */
3045     if (c & RELKEY) {
3046         /* key released */
3047         /* goto next_code */
3048     } else {
3049         /* key pressed */
3050         if (c & SPCLKEY) {
3051             c &= ~SPCLKEY;
3052             switch (KEYCHAR(c)) {
3053             /* LOCKING KEYS */
3054             case NLK: case CLK: case ALK:
3055                 break;
3056             case SLK:
3057                 kbd_ioctl(sc->kbd, KDGKBSTATE, (caddr_t)&f);
3058                 if (f & SLKED) {
3059                     scp->status |= SLKED;
3060                 } else {
3061                     if (scp->status & SLKED) {
3062                         scp->status &= ~SLKED;
3063 #ifndef SC_NO_HISTORY
3064                         if (scp->status & BUFFER_SAVED) {
3065                             if (!sc_hist_restore(scp))
3066                                 sc_remove_cutmarking(scp);
3067                             scp->status &= ~BUFFER_SAVED;
3068                             scp->status |= CURSOR_ENABLED;
3069                             sc_draw_cursor_image(scp);
3070                         }
3071                         tp = VIRTUAL_TTY(sc, scp->index);
3072                         if (ISTTYOPEN(tp))
3073                             scstart(tp);
3074 #endif
3075                     }
3076                 }
3077                 break;
3078
3079             /* NON-LOCKING KEYS */
3080             case NOP:
3081             case LSH:  case RSH:  case LCTR: case RCTR:
3082             case LALT: case RALT: case ASH:  case META:
3083                 break;
3084
3085             case BTAB:
3086                 if (!(sc->flags & SC_SCRN_BLANKED))
3087                     return c;
3088                 break;
3089
3090             case SPSC:
3091 #if NSPLASH > 0
3092                 /* force activatation/deactivation of the screen saver */
3093                 if (!(sc->flags & SC_SCRN_BLANKED)) {
3094                     run_scrn_saver = TRUE;
3095                     sc->scrn_time_stamp -= scrn_blank_time;
3096                 }
3097                 if (cold) {
3098                     /*
3099                      * While devices are being probed, the screen saver need
3100                      * to be invoked explictly. XXX
3101                      */
3102                     if (sc->flags & SC_SCRN_BLANKED) {
3103                         scsplash_stick(FALSE);
3104                         stop_scrn_saver(sc, current_saver);
3105                     } else {
3106                         if (!ISGRAPHSC(scp)) {
3107                             scsplash_stick(TRUE);
3108                             (*current_saver)(sc, TRUE);
3109                         }
3110                     }
3111                 }
3112 #endif /* NSPLASH */
3113                 break;
3114
3115             case RBT:
3116 #ifndef SC_DISABLE_REBOOT
3117                 shutdown_nice(0);
3118 #endif
3119                 break;
3120
3121             case HALT:
3122 #ifndef SC_DISABLE_REBOOT
3123                 shutdown_nice(RB_HALT);
3124 #endif
3125                 break;
3126
3127             case PDWN:
3128 #ifndef SC_DISABLE_REBOOT
3129                 shutdown_nice(RB_HALT|RB_POWEROFF);
3130 #endif
3131                 break;
3132
3133 #if NAPM > 0
3134             case SUSP:
3135                 apm_suspend(PMST_SUSPEND);
3136                 break;
3137             case STBY:
3138                 apm_suspend(PMST_STANDBY);
3139                 break;
3140 #else
3141             case SUSP:
3142             case STBY:
3143                 break;
3144 #endif
3145
3146             case DBG:
3147 #ifndef SC_DISABLE_DDBKEY
3148 #ifdef DDB
3149                 Debugger("manual escape to debugger");
3150 #else
3151                 kprintf("No debugger in kernel\n");
3152 #endif
3153 #else /* SC_DISABLE_DDBKEY */
3154                 /* do nothing */
3155 #endif /* SC_DISABLE_DDBKEY */
3156                 break;
3157
3158             case PNC:
3159                 if (enable_panic_key)
3160                         panic("Forced by the panic key");
3161                 break;
3162
3163             case NEXT:
3164                 this_scr = scp->index;
3165                 for (i = (this_scr - sc->first_vty + 1)%sc->vtys;
3166                         sc->first_vty + i != this_scr; 
3167                         i = (i + 1)%sc->vtys) {
3168                     struct tty *tp = VIRTUAL_TTY(sc, sc->first_vty + i);
3169                     if (ISTTYOPEN(tp)) {
3170                         sc_switch_scr(scp->sc, sc->first_vty + i);
3171                         break;
3172                     }
3173                 }
3174                 break;
3175
3176             case PREV:
3177                 this_scr = scp->index;
3178                 for (i = (this_scr - sc->first_vty + sc->vtys - 1)%sc->vtys;
3179                         sc->first_vty + i != this_scr;
3180                         i = (i + sc->vtys - 1)%sc->vtys) {
3181                     struct tty *tp = VIRTUAL_TTY(sc, sc->first_vty + i);
3182                     if (ISTTYOPEN(tp)) {
3183                         sc_switch_scr(scp->sc, sc->first_vty + i);
3184                         break;
3185                     }
3186                 }
3187                 break;
3188
3189             default:
3190                 if (KEYCHAR(c) >= F_SCR && KEYCHAR(c) <= L_SCR) {
3191                     sc_switch_scr(scp->sc, sc->first_vty + KEYCHAR(c) - F_SCR);
3192                     break;
3193                 }
3194                 /* assert(c & FKEY) */
3195                 if (!(sc->flags & SC_SCRN_BLANKED))
3196                     return c;
3197                 break;
3198             }
3199             /* goto next_code */
3200         } else {
3201             /* regular keys (maybe MKEY is set) */
3202             if (!(sc->flags & SC_SCRN_BLANKED))
3203                 return c;
3204         }
3205     }
3206
3207     goto next_code;
3208 }
3209
3210 int
3211 scmmap(struct dev_mmap_args *ap)
3212 {
3213     scr_stat *scp;
3214
3215     scp = SC_STAT(ap->a_head.a_dev);
3216     if (scp != scp->sc->cur_scp)
3217         return EINVAL;
3218     ap->a_result = (*vidsw[scp->sc->adapter]->mmap)(scp->sc->adp, ap->a_offset,
3219                                                     ap->a_nprot);
3220     return(0);
3221 }
3222
3223 static int
3224 save_kbd_state(scr_stat *scp)
3225 {
3226     int state;
3227     int error;
3228
3229     error = kbd_ioctl(scp->sc->kbd, KDGKBSTATE, (caddr_t)&state);
3230     if (error == ENOIOCTL)
3231         error = ENODEV;
3232     if (error == 0) {
3233         scp->status &= ~LOCK_MASK;
3234         scp->status |= state;
3235     }
3236     return error;
3237 }
3238
3239 static int
3240 update_kbd_state(scr_stat *scp, int new_bits, int mask)
3241 {
3242     int state;
3243     int error;
3244
3245     if (mask != LOCK_MASK) {
3246         error = kbd_ioctl(scp->sc->kbd, KDGKBSTATE, (caddr_t)&state);
3247         if (error == ENOIOCTL)
3248             error = ENODEV;
3249         if (error)
3250             return error;
3251         state &= ~mask;
3252         state |= new_bits & mask;
3253     } else {
3254         state = new_bits & LOCK_MASK;
3255     }
3256     error = kbd_ioctl(scp->sc->kbd, KDSKBSTATE, (caddr_t)&state);
3257     if (error == ENOIOCTL)
3258         error = ENODEV;
3259     return error;
3260 }
3261
3262 static int
3263 update_kbd_leds(scr_stat *scp, int which)
3264 {
3265     int error;
3266
3267     which &= LOCK_MASK;
3268     error = kbd_ioctl(scp->sc->kbd, KDSETLED, (caddr_t)&which);
3269     if (error == ENOIOCTL)
3270         error = ENODEV;
3271     return error;
3272 }
3273
3274 int
3275 set_mode(scr_stat *scp)
3276 {
3277     video_info_t info;
3278
3279     /* reject unsupported mode */
3280     if ((*vidsw[scp->sc->adapter]->get_info)(scp->sc->adp, scp->mode, &info))
3281         return 1;
3282
3283     /* if this vty is not currently showing, do nothing */
3284     if (scp != scp->sc->cur_scp)
3285         return 0;
3286
3287     /* setup video hardware for the given mode */
3288     (*vidsw[scp->sc->adapter]->set_mode)(scp->sc->adp, scp->mode);
3289     scp->rndr->init(scp);
3290     sc_vtb_init(&scp->scr, VTB_FRAMEBUFFER, scp->xsize, scp->ysize,
3291                 (void *)scp->sc->adp->va_window, FALSE);
3292
3293 #ifndef SC_NO_FONT_LOADING
3294     /* load appropriate font */
3295     if (!(scp->status & GRAPHICS_MODE)) {
3296         if (!(scp->status & PIXEL_MODE) && ISFONTAVAIL(scp->sc->adp->va_flags)) {
3297             if (scp->font_size < 14) {
3298                 if (scp->sc->fonts_loaded & FONT_8)
3299                     sc_load_font(scp, 0, 8, scp->sc->font_8, 0, 256);
3300             } else if (scp->font_size >= 16) {
3301                 if (scp->sc->fonts_loaded & FONT_16)
3302                     sc_load_font(scp, 0, 16, scp->sc->font_16, 0, 256);
3303             } else {
3304                 if (scp->sc->fonts_loaded & FONT_14)
3305                     sc_load_font(scp, 0, 14, scp->sc->font_14, 0, 256);
3306             }
3307             /*
3308              * FONT KLUDGE:
3309              * This is an interim kludge to display correct font.
3310              * Always use the font page #0 on the video plane 2.
3311              * Somehow we cannot show the font in other font pages on
3312              * some video cards... XXX
3313              */ 
3314             sc_show_font(scp, 0);
3315         }
3316         mark_all(scp);
3317     }
3318 #endif /* !SC_NO_FONT_LOADING */
3319
3320     sc_set_border(scp, scp->border);
3321     sc_set_cursor_image(scp);
3322
3323     return 0;
3324 }
3325
3326 void
3327 refresh_ega_palette(scr_stat *scp)
3328 {
3329     uint32_t r, g, b;
3330     int reg;
3331     int rsize, gsize, bsize;
3332     int rfld, gfld, bfld;
3333     int i;
3334
3335     rsize = scp->sc->adp->va_info.vi_pixel_fsizes[0];
3336     gsize = scp->sc->adp->va_info.vi_pixel_fsizes[1];
3337     bsize = scp->sc->adp->va_info.vi_pixel_fsizes[2];
3338     rfld = scp->sc->adp->va_info.vi_pixel_fields[0];
3339     gfld = scp->sc->adp->va_info.vi_pixel_fields[1];
3340     bfld = scp->sc->adp->va_info.vi_pixel_fields[2];
3341
3342     for (i = 0; i < 16; i++) {
3343         reg = scp->sc->adp->va_palette_regs[i];
3344
3345         r = scp->sc->palette[reg * 3] >> (8 - rsize);
3346         g = scp->sc->palette[reg * 3 + 1] >> (8 - gsize);
3347         b = scp->sc->palette[reg * 3 + 2] >> (8 - bsize);
3348
3349         scp->ega_palette[i] = (r << rfld) + (g << gfld) + (b << bfld);
3350     }
3351 }
3352
3353 void
3354 sc_set_border(scr_stat *scp, int color)
3355 {
3356     ++scp->sc->videoio_in_progress;
3357     (*scp->rndr->draw_border)(scp, color);
3358     --scp->sc->videoio_in_progress;
3359 }
3360
3361 #ifndef SC_NO_FONT_LOADING
3362 void
3363 sc_load_font(scr_stat *scp, int page, int size, u_char *buf,
3364              int base, int count)
3365 {
3366     sc_softc_t *sc;
3367
3368     sc = scp->sc;
3369     sc->font_loading_in_progress = TRUE;
3370     (*vidsw[sc->adapter]->load_font)(sc->adp, page, size, buf, base, count);
3371     sc->font_loading_in_progress = FALSE;
3372 }
3373
3374 void
3375 sc_save_font(scr_stat *scp, int page, int size, u_char *buf,
3376              int base, int count)
3377 {
3378     sc_softc_t *sc;
3379
3380     sc = scp->sc;
3381     sc->font_loading_in_progress = TRUE;
3382     (*vidsw[sc->adapter]->save_font)(sc->adp, page, size, buf, base, count);
3383     sc->font_loading_in_progress = FALSE;
3384 }
3385
3386 void
3387 sc_show_font(scr_stat *scp, int page)
3388 {
3389     (*vidsw[scp->sc->adapter]->show_font)(scp->sc->adp, page);
3390 }
3391 #endif /* !SC_NO_FONT_LOADING */
3392
3393 void
3394 sc_paste(scr_stat *scp, u_char *p, int count) 
3395 {
3396     struct tty *tp;
3397     u_char *rmap;
3398
3399     if (scp->status & MOUSE_VISIBLE) {
3400         tp = VIRTUAL_TTY(scp->sc, scp->sc->cur_scp->index);
3401         if (!ISTTYOPEN(tp))
3402             return;
3403         rmap = scp->sc->scr_rmap;
3404         for (; count > 0; --count)
3405             (*linesw[tp->t_line].l_rint)(rmap[*p++], tp);
3406     }
3407 }
3408
3409 void
3410 sc_bell(scr_stat *scp, int pitch, int duration)
3411 {
3412     if (cold || shutdown_in_progress)
3413         return;
3414
3415     if (scp != scp->sc->cur_scp && (scp->sc->flags & SC_QUIET_BELL))
3416         return;
3417
3418     if (scp->sc->flags & SC_VISUAL_BELL) {
3419         if (scp->sc->blink_in_progress)
3420             return;
3421         scp->sc->blink_in_progress = 3;
3422         if (scp != scp->sc->cur_scp)
3423             scp->sc->blink_in_progress += 2;
3424         blink_screen(scp->sc->cur_scp);
3425     } else if (duration != 0 && pitch != 0) {
3426         if (scp != scp->sc->cur_scp)
3427             pitch *= 2;
3428         sysbeep(pitch, duration);
3429     }
3430 }
3431
3432 static void
3433 blink_screen(void *arg)
3434 {
3435     scr_stat *scp = arg;
3436     struct tty *tp;
3437
3438     if (ISGRAPHSC(scp) || (scp->sc->blink_in_progress <= 1)) {
3439         scp->sc->blink_in_progress = 0;
3440         mark_all(scp);
3441         tp = VIRTUAL_TTY(scp->sc, scp->index);
3442         if (ISTTYOPEN(tp))
3443             scstart(tp);
3444         if (scp->sc->delayed_next_scr)
3445             sc_switch_scr(scp->sc, scp->sc->delayed_next_scr - 1);
3446     }
3447     else {
3448         (*scp->rndr->draw)(scp, 0, scp->xsize*scp->ysize, 
3449                            scp->sc->blink_in_progress & 1);
3450         scp->sc->blink_in_progress--;
3451         callout_reset(&scp->blink_screen_ch, hz / 10, blink_screen, scp);
3452     }
3453 }