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