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