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