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