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