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