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