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