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