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