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