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