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