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