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