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