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