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