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