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