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