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