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