xref: /dragonfly/sys/dev/misc/syscons/syscons.c (revision 655933d6)
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(__x86_64__)
1375 	curthread->td_lwp->lwp_md.md_regs->tf_rflags |= PSL_IOPL;
1376 #endif
1377 	lwkt_reltoken(&vga_token);
1378 	return 0;
1379 
1380     case KDDISABIO:     	/* disallow io operations (default) */
1381 #if defined(__x86_64__)
1382 	curthread->td_lwp->lwp_md.md_regs->tf_rflags &= ~PSL_IOPL;
1383 #endif
1384         lwkt_reltoken(&vga_token);
1385 	return 0;
1386 
1387     case KDSKBSTATE:    	/* set keyboard state (locks) */
1388 	if (*(int *)data & ~LOCK_MASK) {
1389 	    lwkt_reltoken(&vga_token);
1390 	    return EINVAL;
1391 	}
1392 	syscons_lock();
1393 	scp->status &= ~LOCK_MASK;
1394 	scp->status |= *(int *)data;
1395 	syscons_unlock();
1396 	if (scp == sc->cur_scp)
1397 	    update_kbd_state(scp, scp->status, LOCK_MASK, FALSE);
1398 	lwkt_reltoken(&vga_token);
1399 	return 0;
1400 
1401     case KDGKBSTATE:    	/* get keyboard state (locks) */
1402 	if (scp == sc->cur_scp)
1403 	    save_kbd_state(scp, FALSE);
1404 	*(int *)data = scp->status & LOCK_MASK;
1405 	lwkt_reltoken(&vga_token);
1406 	return 0;
1407 
1408     case KDGETREPEAT:      	/* get keyboard repeat & delay rates */
1409     case KDSETREPEAT:      	/* set keyboard repeat & delay rates (new) */
1410 	error = kbd_ioctl(sc->kbd, cmd, data);
1411 	if (error == ENOIOCTL)
1412 	    error = ENODEV;
1413 	lwkt_reltoken(&vga_token);
1414 	return error;
1415 
1416     case KDSKBMODE:     	/* set keyboard mode */
1417 	switch (*(int *)data) {
1418 	case K_XLATE:   	/* switch to XLT ascii mode */
1419 	case K_RAW: 		/* switch to RAW scancode mode */
1420 	case K_CODE: 		/* switch to CODE mode */
1421 	    scp->kbd_mode = *(int *)data;
1422 	    if (scp == sc->cur_scp)
1423 		kbd_ioctl(sc->kbd, cmd, data);
1424             lwkt_reltoken(&vga_token);
1425 	    return 0;
1426 	default:
1427 	    lwkt_reltoken(&vga_token);
1428 	    return EINVAL;
1429 	}
1430 	/* NOT REACHED */
1431 
1432     case KDGKBMODE:     	/* get keyboard mode */
1433 	*(int *)data = scp->kbd_mode;
1434 	lwkt_reltoken(&vga_token);
1435 	return 0;
1436 
1437     case KDGKBINFO:
1438 	error = kbd_ioctl(sc->kbd, cmd, data);
1439 	if (error == ENOIOCTL)
1440 	    error = ENODEV;
1441 	lwkt_reltoken(&vga_token);
1442 	return error;
1443 
1444     case KDMKTONE:      	/* sound the bell */
1445 	syscons_lock();
1446 	if (*(int*)data)
1447 	    sc_bell(scp, (*(int*)data)&0xffff,
1448 		    (((*(int*)data)>>16)&0xffff)*hz/1000);
1449 	else
1450 	    sc_bell(scp, scp->bell_pitch, scp->bell_duration);
1451 	syscons_unlock();
1452 	lwkt_reltoken(&vga_token);
1453 	return 0;
1454 
1455     case KIOCSOUND:     	/* make tone (*data) hz */
1456 	syscons_lock();
1457 	if (scp == sc->cur_scp) {
1458 	    if (*(int *)data) {
1459 		error = sc_tone(*(int *)data);
1460 	    } else {
1461 		error = sc_tone(0);
1462 	    }
1463 	} else {
1464 	    error = 0;
1465 	}
1466 	syscons_unlock();
1467 	lwkt_reltoken(&vga_token);
1468 	return error;
1469 
1470     case KDGKBTYPE:     	/* get keyboard type */
1471 	error = kbd_ioctl(sc->kbd, cmd, data);
1472 	if (error == ENOIOCTL) {
1473 	    /* always return something? XXX */
1474 	    *(int *)data = 0;
1475 	}
1476 	lwkt_reltoken(&vga_token);
1477 	return 0;
1478 
1479     case KDSETLED:      	/* set keyboard LED status */
1480 	if (*(int *)data & ~LED_MASK) {	/* FIXME: LOCK_MASK? */
1481 	    lwkt_reltoken(&vga_token);
1482 	    return EINVAL;
1483 	}
1484 	syscons_lock();
1485 	scp->status &= ~LED_MASK;
1486 	scp->status |= *(int *)data;
1487 	syscons_unlock();
1488 	if (scp == sc->cur_scp)
1489 	    update_kbd_leds(scp, scp->status);
1490 	lwkt_reltoken(&vga_token);
1491 	return 0;
1492 
1493     case KDGETLED:      	/* get keyboard LED status */
1494 	if (scp == sc->cur_scp)
1495 	    save_kbd_state(scp, FALSE);
1496 	*(int *)data = scp->status & LED_MASK;
1497 	lwkt_reltoken(&vga_token);
1498 	return 0;
1499 
1500 	case KBADDKBD:              /* add/remove keyboard to/from mux */
1501 	case KBRELKBD:
1502 		error = kbd_ioctl(sc->kbd, cmd, data);
1503 		if (error == ENOIOCTL)
1504 			error = ENODEV;
1505 		lwkt_reltoken(&vga_token);
1506 		return error;
1507 
1508     case CONS_SETKBD: 		/* set the new keyboard */
1509 	{
1510 	    keyboard_t *newkbd;
1511 
1512 	    newkbd = kbd_get_keyboard(*(int *)data);
1513 	    if (newkbd == NULL) {
1514 		lwkt_reltoken(&vga_token);
1515 		return EINVAL;
1516 	    }
1517 	    error = 0;
1518 	    if (sc->kbd != newkbd) {
1519 		i = kbd_allocate(newkbd->kb_name, newkbd->kb_unit,
1520 				 (void *)&sc->keyboard, sckbdevent, sc);
1521 		/* i == newkbd->kb_index */
1522 		if (i >= 0) {
1523 		    if (sc->kbd != NULL) {
1524 			save_kbd_state(sc->cur_scp, FALSE);
1525 			kbd_release(sc->kbd, (void *)&sc->keyboard);
1526 		    }
1527 		    syscons_lock();
1528 		    sc->kbd = kbd_get_keyboard(i); /* sc->kbd == newkbd */
1529 		    sc->keyboard = i;
1530 		    syscons_unlock();
1531 		    kbd_ioctl(sc->kbd, KDSKBMODE,
1532 			      (caddr_t)&sc->cur_scp->kbd_mode);
1533 		    update_kbd_state(sc->cur_scp, sc->cur_scp->status,
1534 			LOCK_MASK, FALSE);
1535 		} else {
1536 		    error = EPERM;	/* XXX */
1537 		}
1538 	    }
1539 	    lwkt_reltoken(&vga_token);
1540 	    return error;
1541 	}
1542 
1543     case CONS_RELKBD: 		/* release the current keyboard */
1544 	error = 0;
1545 	if (sc->kbd != NULL) {
1546 	    save_kbd_state(sc->cur_scp, FALSE);
1547 	    error = kbd_release(sc->kbd, (void *)&sc->keyboard);
1548 	    if (error == 0) {
1549 		syscons_lock();
1550 		sc->kbd = NULL;
1551 		sc->keyboard = -1;
1552 		syscons_unlock();
1553 	    }
1554 	}
1555 	lwkt_reltoken(&vga_token);
1556 	return error;
1557 
1558     case CONS_GETTERM:		/* get the current terminal emulator info */
1559 	{
1560 	    sc_term_sw_t *sw;
1561 
1562 	    if (((term_info_t *)data)->ti_index == 0) {
1563 		sw = scp->tsw;
1564 	    } else {
1565 		sw = sc_term_match_by_number(((term_info_t *)data)->ti_index);
1566 	    }
1567 	    if (sw != NULL) {
1568 		strncpy(((term_info_t *)data)->ti_name, sw->te_name,
1569 			sizeof(((term_info_t *)data)->ti_name));
1570 		strncpy(((term_info_t *)data)->ti_desc, sw->te_desc,
1571 			sizeof(((term_info_t *)data)->ti_desc));
1572 		((term_info_t *)data)->ti_flags = 0;
1573 		lwkt_reltoken(&vga_token);
1574 		return 0;
1575 	    } else {
1576 		((term_info_t *)data)->ti_name[0] = '\0';
1577 		((term_info_t *)data)->ti_desc[0] = '\0';
1578 		((term_info_t *)data)->ti_flags = 0;
1579 		lwkt_reltoken(&vga_token);
1580 		return EINVAL;
1581 	    }
1582 	}
1583 
1584     case CONS_SETTERM:		/* set the current terminal emulator */
1585 	syscons_lock();
1586 	error = sc_init_emulator(scp, ((term_info_t *)data)->ti_name);
1587 	/* FIXME: what if scp == sc_console! XXX */
1588 	syscons_unlock();
1589 	lwkt_reltoken(&vga_token);
1590 	return error;
1591 
1592     case GIO_SCRNMAP:   	/* get output translation table */
1593 	bcopy(&sc->scr_map, data, sizeof(sc->scr_map));
1594 	lwkt_reltoken(&vga_token);
1595 	return 0;
1596 
1597     case PIO_SCRNMAP:   	/* set output translation table */
1598 	bcopy(data, &sc->scr_map, sizeof(sc->scr_map));
1599 	for (i=0; i<sizeof(sc->scr_map); i++) {
1600 	    sc->scr_rmap[sc->scr_map[i]] = i;
1601 	}
1602 	lwkt_reltoken(&vga_token);
1603 	return 0;
1604 
1605     case GIO_KEYMAP:		/* get keyboard translation table */
1606     case PIO_KEYMAP:		/* set keyboard translation table */
1607     case GIO_DEADKEYMAP:	/* get accent key translation table */
1608     case PIO_DEADKEYMAP:	/* set accent key translation table */
1609     case GETFKEY:		/* get function key string */
1610     case SETFKEY:		/* set function key string */
1611 	error = kbd_ioctl(sc->kbd, cmd, data);
1612 	if (error == ENOIOCTL)
1613 	    error = ENODEV;
1614 	lwkt_reltoken(&vga_token);
1615 	return error;
1616 
1617 #ifndef SC_NO_FONT_LOADING
1618 
1619     case PIO_FONT8x8:   	/* set 8x8 dot font */
1620 	if (sc->fbi == NULL && !ISFONTAVAIL(sc->adp->va_flags)) {
1621 	    lwkt_reltoken(&vga_token);
1622 	    return ENXIO;
1623 	}
1624 	syscons_lock();
1625 	bcopy(data, sc->font_8, 8*256);
1626 	sc->fonts_loaded |= FONT_8;
1627 	/*
1628 	 * FONT KLUDGE
1629 	 * Always use the font page #0. XXX
1630 	 * Don't load if the current font size is not 8x8.
1631 	 */
1632 	if (sc->fbi == NULL
1633 	    && ISTEXTSC(sc->cur_scp) && (sc->cur_scp->font_height < 14)) {
1634 	    sc_load_font(sc->cur_scp, 0, 8, sc->font_8, 0, 256);
1635 	}
1636 	syscons_unlock();
1637 	lwkt_reltoken(&vga_token);
1638 	return 0;
1639 
1640     case GIO_FONT8x8:   	/* get 8x8 dot font */
1641 	if (sc->fbi == NULL && !ISFONTAVAIL(sc->adp->va_flags)) {
1642 	    lwkt_reltoken(&vga_token);
1643 	    return ENXIO;
1644 	}
1645 	if (sc->fonts_loaded & FONT_8) {
1646 	    bcopy(sc->font_8, data, 8*256);
1647 	    lwkt_reltoken(&vga_token);
1648 	    return 0;
1649 	}
1650 	else {
1651 	    lwkt_reltoken(&vga_token);
1652 	    return ENXIO;
1653 	}
1654 
1655     case PIO_FONT8x14:  	/* set 8x14 dot font */
1656 	if (sc->fbi == NULL && !ISFONTAVAIL(sc->adp->va_flags)) {
1657 	    lwkt_reltoken(&vga_token);
1658 	    return ENXIO;
1659 	}
1660 	syscons_lock();
1661 	bcopy(data, sc->font_14, 14*256);
1662 	sc->fonts_loaded |= FONT_14;
1663 	/*
1664 	 * FONT KLUDGE
1665 	 * Always use the font page #0. XXX
1666 	 * Don't load if the current font size is not 8x14.
1667 	 */
1668 	if (sc->fbi == NULL
1669 	    && ISTEXTSC(sc->cur_scp)
1670 	    && (sc->cur_scp->font_height >= 14)
1671 	    && (sc->cur_scp->font_height < 16)) {
1672 	    sc_load_font(sc->cur_scp, 0, 14, sc->font_14, 0, 256);
1673 	}
1674 	syscons_unlock();
1675 	lwkt_reltoken(&vga_token);
1676 	return 0;
1677 
1678     case GIO_FONT8x14:  	/* get 8x14 dot font */
1679 	if (sc->fbi == NULL && !ISFONTAVAIL(sc->adp->va_flags)) {
1680 	    lwkt_reltoken(&vga_token);
1681 	    return ENXIO;
1682 	}
1683 	if (sc->fonts_loaded & FONT_14) {
1684 	    bcopy(sc->font_14, data, 14*256);
1685 	    lwkt_reltoken(&vga_token);
1686 	    return 0;
1687 	}
1688 	else {
1689 	    lwkt_reltoken(&vga_token);
1690 	    return ENXIO;
1691         }
1692 
1693     case PIO_FONT8x16:  	/* set 8x16 dot font */
1694 	if (sc->fbi == NULL && !ISFONTAVAIL(sc->adp->va_flags)) {
1695 	    lwkt_reltoken(&vga_token);
1696 	    return ENXIO;
1697 	}
1698 	syscons_lock();
1699 	bcopy(data, sc->font_16, 16*256);
1700 	sc->fonts_loaded |= FONT_16;
1701 	/*
1702 	 * FONT KLUDGE
1703 	 * Always use the font page #0. XXX
1704 	 * Don't load if the current font size is not 8x16.
1705 	 */
1706 	if (sc->fbi == NULL
1707 	    && ISTEXTSC(sc->cur_scp) && (sc->cur_scp->font_height >= 16))  {
1708 	    sc_load_font(sc->cur_scp, 0, 16, sc->font_16, 0, 256);
1709 	}
1710 	syscons_unlock();
1711 	lwkt_reltoken(&vga_token);
1712 	return 0;
1713 
1714     case GIO_FONT8x16:  	/* get 8x16 dot font */
1715 	if (sc->fbi == NULL && !ISFONTAVAIL(sc->adp->va_flags)) {
1716 	    lwkt_reltoken(&vga_token);
1717 	    return ENXIO;
1718 	}
1719 	if (sc->fonts_loaded & FONT_16) {
1720 	    bcopy(sc->font_16, data, 16*256);
1721 	    lwkt_reltoken(&vga_token);
1722 	    return 0;
1723 	}
1724 	else {
1725 	    lwkt_reltoken(&vga_token);
1726 	    return ENXIO;
1727         }
1728 
1729 #endif /* SC_NO_FONT_LOADING */
1730 
1731     default:
1732 	break;
1733     }
1734 
1735     lwkt_gettoken(&tp->t_token);
1736     error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, ap->a_cred);
1737     if (error != ENOIOCTL) {
1738 	lwkt_reltoken(&tp->t_token);
1739         lwkt_reltoken(&vga_token);
1740 
1741 	return(error);
1742     }
1743 
1744     error = ttioctl(tp, cmd, data, flag);
1745     if (error != ENOIOCTL) {
1746 	lwkt_reltoken(&tp->t_token);
1747         lwkt_reltoken(&vga_token);
1748 
1749 	return(error);
1750     }
1751 
1752     lwkt_reltoken(&tp->t_token);
1753     lwkt_reltoken(&vga_token);
1754 
1755     return(ENOTTY);
1756 }
1757 
1758 static void
1759 scstart(struct tty *tp)
1760 {
1761     struct clist *rbp;
1762     int len;
1763     u_char buf[PCBURST];
1764     scr_stat *scp = SC_STAT(tp->t_dev);
1765 
1766     syscons_lock();
1767     if (scp->status & SLKED ||
1768 	(scp == scp->sc->cur_scp && scp->sc->blink_in_progress))
1769     {
1770 	syscons_unlock();
1771 	return;
1772     }
1773     if (!(tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP))) {
1774 	tp->t_state |= TS_BUSY;
1775 	rbp = &tp->t_outq;
1776 	while (rbp->c_cc) {
1777 	    len = clist_qtob(rbp, buf, PCBURST);
1778 	    sc_puts(scp, buf, len);
1779 	}
1780 	tp->t_state &= ~TS_BUSY;
1781 	syscons_unlock();
1782 	ttwwakeup(tp);
1783     } else {
1784 	syscons_unlock();
1785     }
1786 }
1787 
1788 static void
1789 sccnprobe(struct consdev *cp)
1790 {
1791     int unit;
1792     int flags;
1793 
1794     cp->cn_pri = sc_get_cons_priority(&unit, &flags);
1795 
1796     /* a video card is always required */
1797     if (probe_efi_fb(1) != 0 && !scvidprobe(unit, flags, TRUE))
1798 	cp->cn_pri = CN_DEAD;
1799 
1800     /* syscons will become console even when there is no keyboard */
1801     sckbdprobe(unit, flags, TRUE);
1802 
1803     if (cp->cn_pri == CN_DEAD) {
1804 	return;
1805     }
1806 
1807     /* initialize required fields */
1808     cp->cn_probegood = 1;
1809 }
1810 
1811 static void
1812 sccninit(struct consdev *cp)
1813 {
1814     int unit;
1815     int flags;
1816 
1817     sc_get_cons_priority(&unit, &flags);
1818     scinit(unit, flags | SC_KERNEL_CONSOLE);
1819     sc_console_unit = unit;
1820     sc_console = sc_get_softc(unit, SC_KERNEL_CONSOLE)->console_scp;
1821 }
1822 
1823 static void
1824 sccninit_fini(struct consdev *cp)
1825 {
1826 	if (cctl_dev == NULL)
1827 		kprintf("sccninit_fini: WARNING: cctl_dev is NULL!\n");
1828 	cp->cn_dev = cctl_dev;
1829 }
1830 
1831 /*
1832  * This is called when the console is switched away from syscons to
1833  * a late-configuring device (such as a PCIe serial port).  Since
1834  * late-configuring devices basically didn't exist until now, this
1835  * routine was never called, and SURPRISE!  It doesn't work... causes
1836  * syscons to implode due to all the funny console-not-console structure
1837  * selection syscons does.
1838  *
1839  * Make it a NOP.  Just leave the console designation intact, even
1840  * though it is no longer a console.
1841  */
1842 static void
1843 sccnterm(struct consdev *cp)
1844 {
1845 #if 0
1846     /* we are not the kernel console any more, release everything */
1847 
1848     if (sc_console_unit < 0)
1849 	return;			/* shouldn't happen */
1850 
1851 #if 0 /* XXX */
1852     syscons_lock();
1853     sc_clear_screen(sc_console);
1854     sccnupdate(sc_console);
1855     syscons_unlock();
1856 #endif
1857     scterm(sc_console_unit, SC_KERNEL_CONSOLE);
1858     sc_console_unit = -1;
1859     sc_console = NULL;
1860 #endif
1861 }
1862 
1863 /*
1864  * Console path - cannot block!
1865  */
1866 static void
1867 sccnputc(void *private, int c)
1868 {
1869     u_char buf[1];
1870     scr_stat *scp = sc_console;
1871     void *save;
1872 #ifndef SC_NO_HISTORY
1873 #if 0
1874     struct tty *tp;
1875 #endif
1876 #endif /* !SC_NO_HISTORY */
1877 
1878     /* assert(sc_console != NULL) */
1879 
1880     if (syscons_lock_nonblock() != 0)
1881 	return;
1882 #ifndef SC_NO_HISTORY
1883     if (scp == scp->sc->cur_scp && scp->status & SLKED) {
1884 	scp->status &= ~SLKED;
1885 #if 0
1886 	/* This can block, illegal in the console path */
1887 	update_kbd_state(scp, scp->status, SLKED, TRUE);
1888 #endif
1889 	if (scp->status & BUFFER_SAVED) {
1890 	    if (!sc_hist_restore(scp))
1891 		sc_remove_cutmarking(scp);
1892 	    scp->status &= ~BUFFER_SAVED;
1893 	    scp->status |= CURSOR_ENABLED;
1894 	    sc_draw_cursor_image(scp);
1895 	}
1896 #if 0
1897 	tp = VIRTUAL_TTY(scp->sc, scp->index);
1898 	/* This can block, illegal in the console path */
1899 	if (ISTTYOPEN(tp)) {
1900 	    scstart(tp);
1901 	}
1902 #endif
1903     }
1904 #endif /* !SC_NO_HISTORY */
1905 
1906     save = scp->ts;
1907     if (kernel_console_ts != NULL)
1908 	scp->ts = kernel_console_ts;
1909     buf[0] = c;
1910     sc_puts(scp, buf, 1);
1911     scp->ts = save;
1912 
1913     sccnupdate(scp);
1914     syscons_unlock();
1915 }
1916 
1917 /*
1918  * Console path - cannot block!
1919  */
1920 static int
1921 sccngetc(void *private)
1922 {
1923     return sccngetch(0);
1924 }
1925 
1926 /*
1927  * Console path - cannot block!
1928  */
1929 static int
1930 sccncheckc(void *private)
1931 {
1932     return sccngetch(SCGETC_NONBLOCK);
1933 }
1934 
1935 /*
1936  * Set polling mode (also disables the tty feed), use when
1937  * polling for console key input.
1938  */
1939 static void
1940 sccnpoll(void *private, int on)
1941 {
1942     scr_stat *scp;
1943 
1944     syscons_lock();
1945     sc_touch_scrn_saver();
1946     scp = sc_console->sc->cur_scp;	/* XXX */
1947     syscons_unlock();
1948     if (scp->sc->kbd)
1949 	    kbd_poll(scp->sc->kbd, on);
1950 }
1951 
1952 static void
1953 sccndbctl(void *private, int on)
1954 {
1955     /* assert(sc_console_unit >= 0) */
1956     /* try to switch to the kernel console screen */
1957     if (on && debugger == 0) {
1958 	/*
1959 	 * TRY to make sure the screen saver is stopped,
1960 	 * and the screen is updated before switching to
1961 	 * the vty0.
1962 	 */
1963 	scrn_timer(NULL);
1964 	if (!cold
1965 	    && sc_console->sc->cur_scp->smode.mode == VT_AUTO
1966 	    && sc_console->smode.mode == VT_AUTO) {
1967 	    sc_console->sc->cur_scp->status |= MOUSE_HIDDEN;
1968 	    syscons_lock();
1969 	    sc_switch_scr(sc_console->sc, sc_console->index);
1970 	    syscons_unlock();
1971 	}
1972     }
1973     if (on)
1974 	++debugger;
1975     else
1976 	--debugger;
1977 }
1978 
1979 /*
1980  * Console path - cannot block!
1981  */
1982 static int
1983 sccngetch(int flags)
1984 {
1985     static struct fkeytab fkey;
1986     static int fkeycp;
1987     scr_stat *scp;
1988     u_char *p;
1989     int cur_mode;
1990     int c;
1991 
1992     syscons_lock();
1993     /* assert(sc_console != NULL) */
1994 
1995     /*
1996      * Stop the screen saver and update the screen if necessary.
1997      * What if we have been running in the screen saver code... XXX
1998      */
1999     sc_touch_scrn_saver();
2000     scp = sc_console->sc->cur_scp;	/* XXX */
2001     sccnupdate(scp);
2002     syscons_unlock();
2003 
2004     if (fkeycp < fkey.len) {
2005 	return fkey.str[fkeycp++];
2006     }
2007 
2008     if (scp->sc->kbd == NULL) {
2009 	return -1;
2010     }
2011 
2012     /*
2013      * Make sure the keyboard is accessible even when the kbd device
2014      * driver is disabled.
2015      */
2016     crit_enter();
2017     kbd_enable(scp->sc->kbd);
2018 
2019     /* we shall always use the keyboard in the XLATE mode here */
2020     cur_mode = scp->kbd_mode;
2021     scp->kbd_mode = K_XLATE;
2022     kbd_ioctl(scp->sc->kbd, KDSKBMODE, (caddr_t)&scp->kbd_mode);
2023 
2024     c = scgetc(scp->sc, SCGETC_CN | flags);
2025 
2026     scp->kbd_mode = cur_mode;
2027     kbd_ioctl(scp->sc->kbd, KDSKBMODE, (caddr_t)&scp->kbd_mode);
2028     kbd_disable(scp->sc->kbd);
2029     crit_exit();
2030 
2031     switch (KEYFLAGS(c)) {
2032     case 0:	/* normal char */
2033 	return KEYCHAR(c);
2034     case FKEY:	/* function key */
2035 	p = kbd_get_fkeystr(scp->sc->kbd, KEYCHAR(c), (size_t *)&fkeycp);
2036 	fkey.len = fkeycp;
2037 	if ((p != NULL) && (fkey.len > 0)) {
2038 	    bcopy(p, fkey.str, fkey.len);
2039 	    fkeycp = 1;
2040 	    return fkey.str[0];
2041 	}
2042 	return c;	/* XXX */
2043     case NOKEY:
2044 	if (flags & SCGETC_NONBLOCK)
2045 		return c;
2046 	/* fall through */
2047     case ERRKEY:
2048     default:
2049 	return -1;
2050     }
2051     /* NOT REACHED */
2052 }
2053 
2054 static void
2055 sccnupdate(scr_stat *scp)
2056 {
2057     int ddb_active;
2058 
2059 #ifdef DDB
2060     ddb_active = db_active;
2061 #else
2062     ddb_active = 0;
2063 #endif
2064 
2065     /* this is a cut-down version of scrn_timer()... */
2066 
2067     /*
2068      * Don't update if videoio is in progress.  However, if we are paniced
2069      * or in the debugger it is possible that the variables might be stuck,
2070      * so ignore it in such cases.
2071      */
2072     if (scp->sc->font_loading_in_progress || scp->sc->videoio_in_progress) {
2073 	if (panicstr == NULL && ddb_active == 0 && shutdown_in_progress == 0)
2074 		return;
2075     }
2076 
2077     if (debugger > 0 || panicstr || ddb_active || shutdown_in_progress) {
2078 	sc_touch_scrn_saver();
2079     } else if (scp != scp->sc->cur_scp) {
2080 	return;
2081     }
2082 
2083     if (!run_scrn_saver)
2084 	scp->sc->flags &= ~SC_SCRN_IDLE;
2085 #if NSPLASH > 0
2086     /*
2087      * This is a hard path, we cannot call stop_scrn_saver() here.
2088      */
2089     if ((saver_mode != CONS_LKM_SAVER) || !(scp->sc->flags & SC_SCRN_IDLE))
2090 	if (scp->sc->flags & SC_SCRN_BLANKED) {
2091 	    sc_touch_scrn_saver();
2092             /*stop_scrn_saver(scp->sc, current_saver);*/
2093 	}
2094 #endif /* NSPLASH */
2095 
2096     if (scp != scp->sc->cur_scp || scp->sc->blink_in_progress
2097 	|| scp->sc->switch_in_progress) {
2098 	return;
2099     }
2100 
2101     /*
2102      * FIXME: unlike scrn_timer(), we call scrn_update() from here even
2103      * when write_in_progress is non-zero.  XXX
2104      */
2105     if (!ISGRAPHSC(scp) && !(scp->sc->flags & SC_SCRN_BLANKED))
2106 	scrn_update(scp, TRUE, SCRN_ASYNCOK);
2107 }
2108 
2109 static void
2110 scrn_timer(void *arg)
2111 {
2112     static int kbd_interval = 0;
2113     struct timeval tv;
2114     sc_softc_t *sc;
2115     scr_stat *scp;
2116     int again;
2117 
2118     /*
2119      * Setup depending on who called us
2120      */
2121     again = (arg != NULL);
2122     if (arg != NULL) {
2123 	sc = (sc_softc_t *)arg;
2124     } else if (sc_console != NULL) {
2125 	sc = sc_console->sc;
2126     } else {
2127 	return;
2128     }
2129 
2130     /*
2131      * Don't do anything when we are performing some I/O operations.
2132      * (These are initiated by the frontend?)
2133      */
2134     if (sc->font_loading_in_progress || sc->videoio_in_progress) {
2135 	if (again)
2136 	    callout_reset(&sc->scrn_timer_ch, hz / 10, scrn_timer, sc);
2137 	return;
2138     }
2139 
2140     /*
2141      * Try to allocate a keyboard automatically
2142      */
2143     if ((sc->kbd == NULL) && (sc->config & SC_AUTODETECT_KBD)) {
2144 	if (++kbd_interval >= 25) {
2145 	    sc->keyboard = sc_allocate_keyboard(sc, -1);
2146 	    if (sc->keyboard >= 0) {
2147 		sc->kbd = kbd_get_keyboard(sc->keyboard);
2148 		kbd_ioctl(sc->kbd, KDSKBMODE,
2149 			  (caddr_t)&sc->cur_scp->kbd_mode);
2150 		update_kbd_state(sc->cur_scp, sc->cur_scp->status,
2151 		    LOCK_MASK, FALSE);
2152 	    }
2153 	    kbd_interval = 0;
2154 	}
2155     }
2156 
2157     /*
2158      * Should we stop the screen saver?  We need the syscons_lock
2159      * for most of this stuff.
2160      */
2161     getmicrouptime(&tv);
2162 
2163     if (syscons_lock_nonblock() != 0) {
2164 	/* failed to get the lock */
2165 	if (again)
2166 	    callout_reset(&sc->scrn_timer_ch, hz / 10, scrn_timer, sc);
2167 	return;
2168     }
2169     /* successful lock */
2170 
2171     if (debugger > 0 || panicstr || shutdown_in_progress)
2172 	sc_touch_scrn_saver();
2173     if (run_scrn_saver) {
2174 	if (tv.tv_sec > sc->scrn_time_stamp + scrn_blank_time)
2175 	    sc->flags |= SC_SCRN_IDLE;
2176 	else
2177 	    sc->flags &= ~SC_SCRN_IDLE;
2178     } else {
2179 	sc->scrn_time_stamp = tv.tv_sec;
2180 	sc->flags &= ~SC_SCRN_IDLE;
2181 	if (scrn_blank_time > 0)
2182 	    run_scrn_saver = TRUE;
2183     }
2184 #if NSPLASH > 0
2185     if ((saver_mode != CONS_LKM_SAVER) || !(sc->flags & SC_SCRN_IDLE)) {
2186 	if ((sc->flags & SC_SCRN_BLANKED) && !ISGRAPHSC(sc->cur_scp))
2187             stop_scrn_saver(sc, current_saver);
2188     }
2189 #endif /* NSPLASH */
2190 
2191     /* should we just return ? */
2192     if (sc->blink_in_progress || sc->switch_in_progress ||
2193 	sc->write_in_progress)
2194     {
2195 	syscons_unlock();
2196 	if (again)
2197 	    callout_reset(&sc->scrn_timer_ch, hz / 10, scrn_timer, sc);
2198 	return;
2199     }
2200 
2201     /* Update the screen */
2202     scp = sc->cur_scp;		/* cur_scp may have changed... */
2203     if (!ISGRAPHSC(scp) && !(sc->flags & SC_SCRN_BLANKED))
2204 	scrn_update(scp, TRUE, SCRN_ASYNCOK);
2205 
2206 #if NSPLASH > 0
2207     /* should we activate the screen saver? */
2208     if ((saver_mode == CONS_LKM_SAVER) && (sc->flags & SC_SCRN_IDLE))
2209 	if (!ISGRAPHSC(scp) || (sc->flags & SC_SCRN_BLANKED))
2210 	    (*current_saver)(sc, TRUE);
2211 #endif /* NSPLASH */
2212 
2213     syscons_unlock();
2214     if (again)
2215 	callout_reset(&sc->scrn_timer_ch, hz / 25, scrn_timer, sc);
2216 }
2217 
2218 static int
2219 and_region(int *s1, int *e1, int s2, int e2)
2220 {
2221     if (*e1 < s2 || e2 < *s1)
2222 	return FALSE;
2223     *s1 = imax(*s1, s2);
2224     *e1 = imin(*e1, e2);
2225     return TRUE;
2226 }
2227 
2228 /*
2229  * Refresh modified frame buffer range.  Also used to
2230  * scroll (entire FB is marked modified).
2231  *
2232  * This function is allowed to run without the syscons_lock,
2233  * so scp fields can change unexpected.  We cache most values
2234  * that we care about and silently discard illegal ranges.
2235  */
2236 static void
2237 scrn_update(scr_stat *scp, int show_cursor, int flags)
2238 {
2239     int start;
2240     int end;
2241     int cpos;
2242     int copos;
2243     int s;
2244     int e;
2245     int ddb_active;
2246 
2247 #ifdef DDB
2248     ddb_active = db_active;
2249 #else
2250     ddb_active = 0;
2251 #endif
2252 
2253     /*
2254      * Try to run large screen updates as an async operation, which will
2255      * call this function again from a thread with BULKUNLOCK set, allowing
2256      * interrupts during the update which tends to make the system behave
2257      * better (no sound glitches, etc).
2258      */
2259     if ((flags & SCRN_ASYNCOK) && syscons_async && scp->asynctd &&
2260 	(scp->end - scp->start) > 16 &&
2261 	panicstr == NULL && ddb_active == 0 && shutdown_in_progress == 0) {
2262 	scp->show_cursor = show_cursor;
2263 	scp->queue_update_td = 1;
2264 	wakeup(&scp->asynctd);
2265 	return;
2266     }
2267     if (flags & SCRN_BULKUNLOCK)
2268 	syscons_lock();
2269 
2270     /*
2271      * Synchronous operation or called from
2272      */
2273 
2274     /* assert(scp == scp->sc->cur_scp) */
2275     atomic_add_int(&scp->sc->videoio_in_progress, 1);
2276 
2277     cpos = scp->cursor_pos;
2278     copos = scp->cursor_oldpos;
2279 
2280 #ifndef SC_NO_CUTPASTE
2281     /* remove the previous mouse pointer image if necessary */
2282     if (scp->status & MOUSE_VISIBLE) {
2283 	s = scp->mouse_pos;
2284 	e = scp->mouse_pos + scp->xsize + 1;
2285 	if ((scp->status & (MOUSE_MOVED | MOUSE_HIDDEN))
2286 	    || and_region(&s, &e, scp->start, scp->end)
2287 	    || ((scp->status & CURSOR_ENABLED) &&
2288 		(cpos != copos) &&
2289 		(and_region(&s, &e, cpos, cpos)
2290 		 || and_region(&s, &e, copos, copos)))) {
2291 	    sc_remove_mouse_image(scp);
2292 	    if (scp->end >= scp->xsize*scp->ysize)
2293 		scp->end = scp->xsize*scp->ysize - 1;
2294 	}
2295     }
2296 #endif /* !SC_NO_CUTPASTE */
2297 
2298     /*
2299      * WARNING: Don't add debugging kprintf()s with syscons locked.
2300      *		Or at all.
2301      */
2302     if (scp->end >= scp->xsize*scp->ysize) {
2303 	scp->end = scp->xsize*scp->ysize - 1;
2304     }
2305     if (scp->start < 0) {
2306 	scp->start = 0;
2307     }
2308 
2309     /*
2310      * Main update, extract update range and reset
2311      * ASAP.
2312      */
2313     start = scp->start;
2314     end = scp->end;
2315     scp->end = 0;
2316     scp->start = scp->xsize * scp->ysize - 1;
2317 
2318     if (start <= end)  {
2319 	if (flags & SCRN_BULKUNLOCK) {
2320 	    atomic_add_int(&scp->sc->videoio_in_progress, -1);
2321 	    syscons_unlock();
2322 	}
2323 	(*scp->rndr->draw)(scp, start, end - start + 1, FALSE);
2324 	if (flags & SCRN_BULKUNLOCK) {
2325 	    syscons_lock();
2326 	    atomic_add_int(&scp->sc->videoio_in_progress, 1);
2327 	}
2328 
2329 	/*
2330 	 * Handle cut sequence
2331 	 */
2332 	s = scp->mouse_cut_start;
2333 	e = scp->mouse_cut_end;
2334 	cpu_ccfence();		/* allowed to race */
2335 
2336 	if (e >= 0) {
2337 	    if (s > e) {
2338 		int r = s;
2339 		s = e;
2340 		e = r;
2341 	    }
2342 	    /* does the cut-mark region overlap with the update region? */
2343 	    if (and_region(&s, &e, start, end)) {
2344 		if (flags & SCRN_BULKUNLOCK) {
2345 		    atomic_add_int(&scp->sc->videoio_in_progress, -1);
2346 		    syscons_unlock();
2347 		}
2348 		(*scp->rndr->draw)(scp, s, e - s + 1, TRUE);
2349 		if (flags & SCRN_BULKUNLOCK) {
2350 		    syscons_lock();
2351 		    atomic_add_int(&scp->sc->videoio_in_progress, 1);
2352 		}
2353 	    }
2354 	}
2355     }
2356 
2357     /* we are not to show the cursor and the mouse pointer... */
2358     if (!show_cursor)
2359 	goto cleanup;
2360 
2361     /* update cursor image */
2362     if (scp->status & CURSOR_ENABLED) {
2363 	s = start;
2364 	e = end;
2365         /* did cursor move since last time ? */
2366         if (cpos != copos) {
2367             /* do we need to remove old cursor image ? */
2368             if (!and_region(&s, &e, copos, copos))
2369                 sc_remove_cursor_image(scp);
2370             sc_draw_cursor_image(scp);
2371         } else {
2372             if (s <= e && and_region(&s, &e, cpos, cpos)) {
2373 		/* cursor didn't move, but has been overwritten */
2374 		sc_draw_cursor_image(scp);
2375 	    } else if (scp->sc->flags & SC_BLINK_CURSOR) {
2376 		/* if it's a blinking cursor, update it */
2377 		(*scp->rndr->blink_cursor)(scp, cpos,
2378 					   sc_inside_cutmark(scp, cpos));
2379 	    }
2380         }
2381     }
2382 
2383 #ifndef SC_NO_CUTPASTE
2384     /* update "pseudo" mouse pointer image */
2385     if (scp->sc->flags & SC_MOUSE_ENABLED) {
2386 	if (!(scp->status & (MOUSE_VISIBLE | MOUSE_HIDDEN))) {
2387 	    scp->status &= ~MOUSE_MOVED;
2388 	    sc_draw_mouse_image(scp);
2389 	}
2390     }
2391 #endif /* SC_NO_CUTPASTE */
2392 
2393     /*
2394      * Cleanup
2395      */
2396 cleanup:
2397     atomic_add_int(&scp->sc->videoio_in_progress, -1);
2398     if (flags & SCRN_BULKUNLOCK)
2399 	syscons_unlock();
2400 }
2401 
2402 /*
2403  * Thread handles potentially expensive screen updates.   The function is
2404  * expected to operate safely without locks.
2405  */
2406 static void
2407 scrn_update_thread(void *arg)
2408 {
2409 	scr_stat *scp = arg;
2410 	for (;;) {
2411 		if (scp->queue_update_td == 0) {
2412 			tsleep_interlock(&scp->asynctd, 0);
2413 			if (scp->queue_update_td == 0)
2414 				tsleep(&scp->asynctd, PINTERLOCKED, "wait", 0);
2415 		}
2416 		scp->queue_update_td = 0;
2417 		lockmgr(&sc_asynctd_lk, LK_EXCLUSIVE);
2418 		atomic_add_int(&scp->sc->videoio_in_progress, 1);
2419 		scrn_update(scp, scp->show_cursor, SCRN_BULKUNLOCK);
2420 		atomic_add_int(&scp->sc->videoio_in_progress, -1);
2421 		lockmgr(&sc_asynctd_lk, LK_RELEASE);
2422 	}
2423 }
2424 
2425 static void
2426 sc_fb_set_par(void *context, int pending)
2427 {
2428 	sc_softc_t *sc = context;
2429 
2430 	lwkt_gettoken(&vga_token);
2431 	if (sc->fbi != NULL && sc->fbi->fbops.fb_set_par != NULL)
2432 	    sc->fbi->fbops.fb_set_par(sc->fbi);
2433 	lwkt_reltoken(&vga_token);
2434 }
2435 
2436 #if NSPLASH > 0
2437 static void
2438 sc_fb_blank(void *context, int pending)
2439 {
2440 	sc_softc_t *sc = context;
2441 
2442 	lwkt_gettoken(&vga_token);
2443 	if (sc->fbi != NULL && sc->fbi->fbops.fb_blank != NULL) {
2444 		/* 0 == FB_BLANK_UNBLANK and 4 == FB_BLANK_POWERDOWN */
2445 		if (sc->flags & SC_SCRN_BLANKED) {
2446 			sc->fbi->fbops.fb_blank(4, sc->fbi);
2447 			sc->fb_blanked = TRUE;
2448 			if (sc->unit == sc_console_unit)
2449 				cons_unavail = TRUE;
2450 		} else {
2451 			sc->fbi->fbops.fb_blank(0, sc->fbi);
2452 			sc->fb_blanked = FALSE;
2453 			if (sc->unit == sc_console_unit &&
2454 			    sc->cur_scp->smode.mode == VT_AUTO)
2455 				cons_unavail = FALSE;
2456 		}
2457 	}
2458 	lwkt_reltoken(&vga_token);
2459 }
2460 
2461 static void
2462 scframebuffer_saver(sc_softc_t *sc, int show)
2463 {
2464 	scr_stat *scp = sc->cur_scp;
2465 
2466 	if (panicstr)
2467 		return;
2468 
2469 	/*
2470 	 * Gets called on every screen update while screensaver is active,
2471 	 * so we need to check the SC_SCRN_BLANKED flag ourselves.
2472 	 */
2473 	if ((sc->flags & SC_SCRN_BLANKED) && show)
2474 		return;
2475 
2476 	taskqueue_cancel(taskqueue_thread[0], sc->fb_blank_task, NULL);
2477 	crit_enter();
2478 	if (show) {
2479 		scp->status |= SAVER_RUNNING;
2480 		sc->flags |= SC_SCRN_BLANKED;
2481 		++scrn_blanked;
2482 	} else {
2483 		scp->status &= ~SAVER_RUNNING;
2484 		sc->flags &= ~SC_SCRN_BLANKED;
2485 		--scrn_blanked;
2486 	}
2487 	crit_exit();
2488 	taskqueue_enqueue(taskqueue_thread[0], sc->fb_blank_task);
2489 }
2490 
2491 static int
2492 scsplash_callback(int event, void *arg)
2493 {
2494     sc_softc_t *sc;
2495     int error;
2496 
2497     sc = (sc_softc_t *)arg;
2498 
2499     switch (event) {
2500     case SPLASH_INIT:
2501 	if (add_scrn_saver(scsplash_saver) == 0) {
2502 	    sc->flags &= ~SC_SAVER_FAILED;
2503 	    run_scrn_saver = TRUE;
2504 	    if (cold) {
2505 		scsplash_stick(TRUE);
2506 		(*current_saver)(sc, TRUE);
2507 	    }
2508 	}
2509 	return 0;
2510 
2511     case SPLASH_TERM:
2512 	if (current_saver == scsplash_saver) {
2513 	    scsplash_stick(FALSE);
2514 	    error = remove_scrn_saver(scsplash_saver);
2515 	    if (error) {
2516 		return error;
2517             }
2518 	}
2519 	return 0;
2520 
2521     default:
2522 	return EINVAL;
2523     }
2524 }
2525 
2526 static void
2527 scsplash_saver(sc_softc_t *sc, int show)
2528 {
2529     static int busy = FALSE;
2530     scr_stat *scp;
2531 
2532     if (busy)
2533 	return;
2534     busy = TRUE;
2535 
2536     scp = sc->cur_scp;
2537     if (show) {
2538 	if (!(sc->flags & SC_SAVER_FAILED)) {
2539 	    if (!(sc->flags & SC_SCRN_BLANKED))
2540 		set_scrn_saver_mode(scp, -1, NULL, 0);
2541 	    switch (splash(sc->adp, TRUE)) {
2542 	    case 0:		/* succeeded */
2543 		break;
2544 	    case EAGAIN:	/* try later */
2545 		restore_scrn_saver_mode(scp, FALSE);
2546 		sc_touch_scrn_saver();		/* XXX */
2547 		break;
2548 	    default:
2549 		sc->flags |= SC_SAVER_FAILED;
2550 		scsplash_stick(FALSE);
2551 		restore_scrn_saver_mode(scp, TRUE);
2552 		kprintf("scsplash_saver(): failed to put up the image\n");
2553 		break;
2554 	    }
2555 	}
2556     } else if (!sticky_splash) {
2557 	if ((sc->flags & SC_SCRN_BLANKED) && (splash(sc->adp, FALSE) == 0))
2558 	    restore_scrn_saver_mode(scp, TRUE);
2559     }
2560     busy = FALSE;
2561 }
2562 
2563 static int
2564 add_scrn_saver(void (*this_saver)(sc_softc_t *, int))
2565 {
2566 #if 0
2567     int error;
2568 
2569     if (current_saver != none_saver) {
2570 	error = remove_scrn_saver(current_saver);
2571 	if (error)
2572 	    return error;
2573     }
2574 #endif
2575     if (current_saver != none_saver) {
2576 	return EBUSY;
2577     }
2578 
2579     run_scrn_saver = FALSE;
2580     saver_mode = CONS_LKM_SAVER;
2581     current_saver = this_saver;
2582     return 0;
2583 }
2584 
2585 static int
2586 remove_scrn_saver(void (*this_saver)(sc_softc_t *, int))
2587 {
2588     if (current_saver != this_saver)
2589 	return EINVAL;
2590 
2591 #if 0
2592     /*
2593      * In order to prevent `current_saver' from being called by
2594      * the timeout routine `scrn_timer()' while we manipulate
2595      * the saver list, we shall set `current_saver' to `none_saver'
2596      * before stopping the current saver, rather than blocking by `splXX()'.
2597      */
2598     current_saver = none_saver;
2599     if (scrn_blanked)
2600         stop_scrn_saver(this_saver);
2601 #endif
2602     /* unblank all blanked screens */
2603     wait_scrn_saver_stop(NULL, FALSE);
2604     if (scrn_blanked) {
2605 	return EBUSY;
2606     }
2607 
2608     current_saver = none_saver;
2609     return 0;
2610 }
2611 
2612 static int
2613 set_scrn_saver_mode(scr_stat *scp, int mode, u_char *pal, int border)
2614 {
2615 
2616     /* assert(scp == scp->sc->cur_scp) */
2617     crit_enter();
2618     if (!ISGRAPHSC(scp))
2619 	sc_remove_cursor_image(scp);
2620     scp->splash_save_mode = scp->mode;
2621     scp->splash_save_status = scp->status & (GRAPHICS_MODE | PIXEL_MODE);
2622     scp->status &= ~(GRAPHICS_MODE | PIXEL_MODE);
2623     scp->status |= (UNKNOWN_MODE | SAVER_RUNNING);
2624     scp->sc->flags |= SC_SCRN_BLANKED;
2625     ++scrn_blanked;
2626     crit_exit();
2627     if (mode < 0) {
2628 	return 0;
2629     }
2630     scp->mode = mode;
2631     if (set_mode(scp) == 0) {
2632 	if (scp->sc->fbi == NULL &&
2633 	    scp->sc->adp->va_info.vi_flags & V_INFO_GRAPHICS) {
2634 	    scp->status |= GRAPHICS_MODE;
2635 	}
2636 	if (scp->sc->fbi == NULL && pal != NULL)
2637 	    load_palette(scp->sc->adp, pal);
2638 	sc_set_border(scp, border);
2639 	return 0;
2640     } else {
2641 	crit_enter();
2642 	scp->mode = scp->splash_save_mode;
2643 	scp->status &= ~(UNKNOWN_MODE | SAVER_RUNNING);
2644 	scp->status |= scp->splash_save_status;
2645 	crit_exit();
2646 	return 1;
2647     }
2648     /* NOTREACHED */
2649 }
2650 
2651 static int
2652 restore_scrn_saver_mode(scr_stat *scp, int changemode)
2653 {
2654     int mode;
2655     int status;
2656 
2657     /* assert(scp == scp->sc->cur_scp) */
2658     crit_enter();
2659     mode = scp->mode;
2660     status = scp->status;
2661     scp->mode = scp->splash_save_mode;
2662     scp->status &= ~(UNKNOWN_MODE | SAVER_RUNNING);
2663     scp->status |= scp->splash_save_status;
2664     scp->sc->flags &= ~SC_SCRN_BLANKED;
2665     if (!changemode) {
2666 	if (!ISGRAPHSC(scp))
2667 	    sc_draw_cursor_image(scp);
2668 	--scrn_blanked;
2669 	crit_exit();
2670 	return 0;
2671     }
2672     if (set_mode(scp) == 0) {
2673 	if (scp->sc->fbi == NULL)
2674 	    load_palette(scp->sc->adp, scp->sc->palette);
2675 	--scrn_blanked;
2676 	crit_exit();
2677 	return 0;
2678     } else {
2679 	scp->mode = mode;
2680 	scp->status = status;
2681 	crit_exit();
2682 	return 1;
2683     }
2684     /* NOTREACHED */
2685 }
2686 
2687 static void
2688 stop_scrn_saver(sc_softc_t *sc, void (*saver)(sc_softc_t *, int))
2689 {
2690     (*saver)(sc, FALSE);
2691     run_scrn_saver = FALSE;
2692     /* the screen saver may have chosen not to stop after all... */
2693     if (sc->flags & SC_SCRN_BLANKED) {
2694 	return;
2695     }
2696 
2697     mark_all(sc->cur_scp);
2698     if (sc->delayed_next_scr)
2699 	sc_switch_scr(sc, sc->delayed_next_scr - 1);
2700     wakeup(&scrn_blanked);
2701 }
2702 
2703 static int
2704 wait_scrn_saver_stop(sc_softc_t *sc, int need_unlock)
2705 {
2706     int error = 0;
2707 
2708     while (scrn_blanked > 0) {
2709 	run_scrn_saver = FALSE;
2710 	if (sc && !(sc->flags & SC_SCRN_BLANKED)) {
2711 	    error = 0;
2712 	    break;
2713 	}
2714 	if (need_unlock) {
2715 	    tsleep_interlock(&scrn_blanked, PCATCH);
2716 	    syscons_unlock();
2717 	    error = tsleep(&scrn_blanked, PCATCH | PINTERLOCKED, "scrsav", 0);
2718 	    syscons_lock();
2719 	} else {
2720 	    error = tsleep(&scrn_blanked, PCATCH, "scrsav", 0);
2721 	}
2722 	/* May return ERESTART */
2723 	if (error)
2724 		break;
2725     }
2726     run_scrn_saver = FALSE;
2727     return error;
2728 }
2729 #endif /* NSPLASH */
2730 
2731 void
2732 sc_start_scrn_saver(sc_softc_t *sc)
2733 {
2734 #if NSPLASH > 0
2735     (*current_saver)(sc, TRUE);
2736 #endif
2737 }
2738 
2739 void
2740 sc_stop_scrn_saver(sc_softc_t *sc)
2741 {
2742 #if NSPLASH > 0
2743     if (sc->flags & SC_SCRN_BLANKED)
2744 	stop_scrn_saver(sc, current_saver);
2745 #endif
2746 }
2747 
2748 void
2749 sc_touch_scrn_saver(void)
2750 {
2751     scsplash_stick(FALSE);
2752     run_scrn_saver = FALSE;
2753 }
2754 
2755 int
2756 sc_switch_scr(sc_softc_t *sc, u_int next_scr)
2757 {
2758     scr_stat *cur_scp;
2759     struct tty *tp;
2760 
2761     DPRINTF(5, ("sc0: sc_switch_scr() %d ", next_scr + 1));
2762 
2763     /* prevent switch if previously requested */
2764     if (sc->flags & SC_SCRN_VTYLOCK) {
2765 	    sc_bell(sc->cur_scp, sc->cur_scp->bell_pitch,
2766 		sc->cur_scp->bell_duration);
2767 	    return EPERM;
2768     }
2769 
2770     /* delay switch if the screen is blanked or being updated */
2771     if ((sc->flags & SC_SCRN_BLANKED) || sc->write_in_progress
2772 	|| sc->blink_in_progress || sc->videoio_in_progress) {
2773 	sc->delayed_next_scr = next_scr + 1;
2774 	sc_touch_scrn_saver();
2775 	DPRINTF(5, ("switch delayed\n"));
2776 	return 0;
2777     }
2778 
2779     cur_scp = sc->cur_scp;
2780 
2781     /*
2782      * we are in the middle of the vty switching process...
2783      *
2784      * This may be in the console path, be very careful.  pfindn() is
2785      * still going to use a spinlock but it no longer uses tokens so
2786      * we should be ok.
2787      */
2788     if (sc->switch_in_progress &&
2789 	(cur_scp->smode.mode == VT_PROCESS) &&
2790 	cur_scp->proc) {
2791 	if (cur_scp->proc != pfindn(cur_scp->pid)) {
2792 	    /*
2793 	     * The controlling process has died!!.  Do some clean up.
2794 	     * NOTE:`cur_scp->proc' and `cur_scp->smode.mode'
2795 	     * are not reset here yet; they will be cleared later.
2796 	     */
2797 	    DPRINTF(5, ("cur_scp controlling process %d died, ", cur_scp->pid));
2798 	    if (cur_scp->status & SWITCH_WAIT_REL) {
2799 		/*
2800 		 * Force the previous switch to finish, but return now
2801 		 * with error.
2802 		 *
2803 		 */
2804 		DPRINTF(5, ("reset WAIT_REL, "));
2805 		finish_vt_rel(cur_scp, TRUE);
2806 		DPRINTF(5, ("finishing previous switch\n"));
2807 		return EINVAL;
2808 	    } else if (cur_scp->status & SWITCH_WAIT_ACQ) {
2809 		/* let's assume screen switch has been completed. */
2810 		DPRINTF(5, ("reset WAIT_ACQ, "));
2811 		finish_vt_acq(cur_scp);
2812 	    } else {
2813 		/*
2814 	 	 * We are in between screen release and acquisition, and
2815 		 * reached here via scgetc() or scrn_timer() which has
2816 		 * interrupted exchange_scr(). Don't do anything stupid.
2817 		 */
2818 		DPRINTF(5, ("waiting nothing, "));
2819 	    }
2820 	} else {
2821 	    /*
2822 	     * The controlling process is alive, but not responding...
2823 	     * It is either buggy or it may be just taking time.
2824 	     * The following code is a gross kludge to cope with this
2825 	     * problem for which there is no clean solution. XXX
2826 	     */
2827 	    if (cur_scp->status & SWITCH_WAIT_REL) {
2828 		switch (sc->switch_in_progress++) {
2829 		case 1:
2830 		    break;
2831 		case 2:
2832 		    DPRINTF(5, ("sending relsig again, "));
2833 		    signal_vt_rel(cur_scp);
2834 		    break;
2835 		case 3:
2836 		    break;
2837 		case 4:
2838 		default:
2839 		    /*
2840 		     * Act as if the controlling program returned
2841 		     * VT_FALSE.
2842 		     *
2843 		     */
2844 		    DPRINTF(5, ("force reset WAIT_REL, "));
2845 		    finish_vt_rel(cur_scp, FALSE);
2846 		    DPRINTF(5, ("act as if VT_FALSE was seen\n"));
2847 		    return EINVAL;
2848 		}
2849 	    } else if (cur_scp->status & SWITCH_WAIT_ACQ) {
2850 		switch (sc->switch_in_progress++) {
2851 		case 1:
2852 		    break;
2853 		case 2:
2854 		    DPRINTF(5, ("sending acqsig again, "));
2855 		    signal_vt_acq(cur_scp);
2856 		    break;
2857 		case 3:
2858 		    break;
2859 		case 4:
2860 		default:
2861 		     /* clear the flag and finish the previous switch */
2862 		    DPRINTF(5, ("force reset WAIT_ACQ, "));
2863 		    finish_vt_acq(cur_scp);
2864 		    break;
2865 		}
2866 	    }
2867 	}
2868     }
2869 
2870     /*
2871      * Return error if an invalid argument is given, or vty switch
2872      * is still in progress.
2873      */
2874     if ((next_scr < sc->first_vty) || (next_scr >= sc->first_vty + sc->vtys)
2875 	|| sc->switch_in_progress) {
2876 	sc_bell(cur_scp, bios_value.bell_pitch, BELL_DURATION);
2877 	DPRINTF(5, ("error 1\n"));
2878 	return EINVAL;
2879     }
2880 
2881     /*
2882      * Don't allow switching away from the graphics mode vty
2883      * if the switch mode is VT_AUTO, unless the next vty is the same
2884      * as the current or the current vty has been closed (but showing).
2885      */
2886     tp = VIRTUAL_TTY(sc, cur_scp->index);
2887     if ((cur_scp->index != next_scr)
2888 	&& ISTTYOPEN(tp)
2889 	&& (cur_scp->smode.mode == VT_AUTO)
2890 	&& ISGRAPHSC(cur_scp)) {
2891 	sc_bell(cur_scp, bios_value.bell_pitch, BELL_DURATION);
2892 	DPRINTF(5, ("error, graphics mode\n"));
2893 	return EINVAL;
2894     }
2895 
2896     /*
2897      * Is the wanted vty open? Don't allow switching to a closed vty.
2898      * If we are in DDB, don't switch to a vty in the VT_PROCESS mode.
2899      * Note that we always allow the user to switch to the kernel
2900      * console even if it is closed.
2901      */
2902     if ((sc_console == NULL) || (next_scr != sc_console->index)) {
2903 	tp = VIRTUAL_TTY(sc, next_scr);
2904 	if (!ISTTYOPEN(tp)) {
2905 	    sc_bell(cur_scp, bios_value.bell_pitch, BELL_DURATION);
2906 	    DPRINTF(5, ("error 2, requested vty isn't open!\n"));
2907 	    return EINVAL;
2908 	}
2909 	if ((debugger > 0) && (SC_STAT(tp->t_dev)->smode.mode == VT_PROCESS)) {
2910 	    DPRINTF(5, ("error 3, requested vty is in the VT_PROCESS mode\n"));
2911 	    return EINVAL;
2912 	}
2913     }
2914 
2915     /* this is the start of vty switching process... */
2916     ++sc->switch_in_progress;
2917     sc->delayed_next_scr = 0;
2918     sc->old_scp = cur_scp;
2919     sc->new_scp = SC_STAT(SC_DEV(sc, next_scr));
2920     if (sc->new_scp == sc->old_scp) {
2921 	sc->switch_in_progress = 0;
2922 	wakeup((caddr_t)&sc->new_scp->smode);
2923 	DPRINTF(5, ("switch done (new == old)\n"));
2924 	return 0;
2925     }
2926 
2927     /* has controlling process died? */
2928     vt_proc_alive(sc->old_scp);
2929     vt_proc_alive(sc->new_scp);
2930 
2931     /* wait for the controlling process to release the screen, if necessary */
2932     if (signal_vt_rel(sc->old_scp)) {
2933 	return 0;
2934     }
2935 
2936     /* go set up the new vty screen */
2937     exchange_scr(sc);
2938 
2939     /* wake up processes waiting for this vty */
2940     wakeup((caddr_t)&sc->cur_scp->smode);
2941 
2942     /* wait for the controlling process to acknowledge, if necessary */
2943     if (signal_vt_acq(sc->cur_scp)) {
2944 	return 0;
2945     }
2946 
2947     sc->switch_in_progress = 0;
2948     if (sc->unit == sc_console_unit && !sc->fb_blanked)
2949 	cons_unavail = FALSE;
2950     DPRINTF(5, ("switch done\n"));
2951 
2952     return 0;
2953 }
2954 
2955 static void
2956 do_switch_scr(sc_softc_t *sc)
2957 {
2958     lwkt_gettoken(&vga_token);
2959     vt_proc_alive(sc->new_scp);
2960 
2961     exchange_scr(sc);
2962     /* sc->cur_scp == sc->new_scp */
2963     wakeup((caddr_t)&sc->cur_scp->smode);
2964 
2965     /* wait for the controlling process to acknowledge, if necessary */
2966     if (!signal_vt_acq(sc->cur_scp)) {
2967 	sc->switch_in_progress = 0;
2968 	if (sc->unit == sc_console_unit && !sc->fb_blanked)
2969 	    cons_unavail = FALSE;
2970     }
2971     lwkt_reltoken(&vga_token);
2972 }
2973 
2974 static int
2975 vt_proc_alive(scr_stat *scp)
2976 {
2977     lwkt_gettoken(&vga_token);
2978     if (scp->proc) {
2979 	if (scp->proc == pfindn(scp->pid)) {
2980 	    lwkt_reltoken(&vga_token);
2981 	    return TRUE;
2982 	}
2983 	scp->proc = NULL;
2984 	scp->smode.mode = VT_AUTO;
2985 	DPRINTF(5, ("vt controlling process %d died\n", scp->pid));
2986     }
2987     lwkt_reltoken(&vga_token);
2988     return FALSE;
2989 }
2990 
2991 static int
2992 signal_vt_rel(scr_stat *scp)
2993 {
2994     struct proc *p;
2995 
2996     lwkt_gettoken(&vga_token);
2997     if (scp->smode.mode != VT_PROCESS) {
2998         lwkt_reltoken(&vga_token);
2999 	return FALSE;
3000     }
3001     scp->status |= SWITCH_WAIT_REL;
3002     p = scp->proc;
3003     PHOLD(p);
3004     ksignal(p, scp->smode.relsig);
3005     PRELE(p);
3006     DPRINTF(5, ("sending relsig to %d\n", scp->pid));
3007     lwkt_reltoken(&vga_token);
3008 
3009     return TRUE;
3010 }
3011 
3012 static int
3013 signal_vt_acq(scr_stat *scp)
3014 {
3015     struct proc *p;
3016 
3017     lwkt_gettoken(&vga_token);
3018     if (scp->smode.mode != VT_PROCESS) {
3019         lwkt_reltoken(&vga_token);
3020 	return FALSE;
3021     }
3022     if (scp->sc->unit == sc_console_unit)
3023 	cons_unavail = TRUE;
3024     scp->status |= SWITCH_WAIT_ACQ;
3025     p = scp->proc;
3026     PHOLD(p);
3027     ksignal(p, scp->smode.acqsig);
3028     PRELE(p);
3029     DPRINTF(5, ("sending acqsig to %d\n", scp->pid));
3030     lwkt_reltoken(&vga_token);
3031 
3032     return TRUE;
3033 }
3034 
3035 static int
3036 finish_vt_rel(scr_stat *scp, int release)
3037 {
3038     lwkt_gettoken(&vga_token);
3039     if (scp == scp->sc->old_scp && scp->status & SWITCH_WAIT_REL) {
3040 	scp->status &= ~SWITCH_WAIT_REL;
3041 	if (release)
3042 	    do_switch_scr(scp->sc);
3043 	else
3044 	    scp->sc->switch_in_progress = 0;
3045 	lwkt_reltoken(&vga_token);
3046 	return 0;
3047     }
3048     lwkt_reltoken(&vga_token);
3049     return EINVAL;
3050 }
3051 
3052 static int
3053 finish_vt_acq(scr_stat *scp)
3054 {
3055     lwkt_gettoken(&vga_token);
3056     if (scp == scp->sc->new_scp && scp->status & SWITCH_WAIT_ACQ) {
3057 	scp->status &= ~SWITCH_WAIT_ACQ;
3058 	scp->sc->switch_in_progress = 0;
3059 	lwkt_reltoken(&vga_token);
3060 	return 0;
3061     }
3062     lwkt_reltoken(&vga_token);
3063     return EINVAL;
3064 }
3065 
3066 static void
3067 exchange_scr(sc_softc_t *sc)
3068 {
3069     scr_stat *scp;
3070 
3071     lwkt_gettoken(&vga_token);
3072     /* save the current state of video and keyboard */
3073     sc_move_cursor(sc->old_scp, sc->old_scp->xpos, sc->old_scp->ypos);
3074     if (!ISGRAPHSC(sc->old_scp))
3075 	sc_remove_cursor_image(sc->old_scp);
3076     if (sc->old_scp->kbd_mode == K_XLATE)
3077 	save_kbd_state(sc->old_scp, TRUE);
3078 
3079     /* set up the video for the new screen */
3080     scp = sc->cur_scp = sc->new_scp;
3081     if (sc->old_scp->mode != scp->mode || ISUNKNOWNSC(sc->old_scp))
3082 	set_mode(scp);
3083     else if (sc->adp != NULL)
3084 	sc_vtb_init(&scp->scr, VTB_FRAMEBUFFER, scp->xsize, scp->ysize,
3085 		    (void *)sc->adp->va_window, FALSE);
3086     scp->status |= MOUSE_HIDDEN;
3087     sc_update_render(scp);     /* Switch to kms renderer if necessary */
3088     sc_move_cursor(scp, scp->xpos, scp->ypos);
3089     if (!ISGRAPHSC(scp))
3090 	sc_set_cursor_image(scp);
3091     if (sc->fbi == NULL && ISGRAPHSC(sc->old_scp))
3092 	load_palette(sc->adp, sc->palette);
3093     if (!ISGRAPHSC(scp) || sc->fbi == NULL)
3094 	sc_set_border(scp, scp->border);
3095 
3096     /* set up the keyboard for the new screen */
3097     if (sc->old_scp->kbd_mode != scp->kbd_mode)
3098 	kbd_ioctl(sc->kbd, KDSKBMODE, (caddr_t)&scp->kbd_mode);
3099     update_kbd_state(scp, scp->status, LOCK_MASK, TRUE);
3100 
3101     mark_all(scp);
3102 
3103     /*
3104      * Restore DRM framebuffer console mode if necessary.
3105      * Especially avoid modesetting when switching to a vt which is in
3106      * graphics mode, because the fb_set_par() from the taskqueue thread
3107      * might race with the modesetting ioctl from the userland application.
3108      */
3109     if (!ISTEXTSC(sc->old_scp) &&
3110 	sc->fbi != NULL && sc->fbi->fbops.fb_set_par != NULL &&
3111 	sc->fb_set_par_task != NULL) {
3112 	taskqueue_enqueue(taskqueue_thread[0], sc->fb_set_par_task);
3113     }
3114 
3115     lwkt_reltoken(&vga_token);
3116 }
3117 
3118 static void
3119 sc_puts(scr_stat *scp, u_char *buf, int len)
3120 {
3121 #if NSPLASH > 0
3122     /* make screensaver happy */
3123     if (!sticky_splash && scp == scp->sc->cur_scp)
3124 	run_scrn_saver = FALSE;
3125 #endif
3126 
3127     if (scp->tsw)
3128 	(*scp->tsw->te_puts)(scp, buf, len);
3129 
3130     if (scp->sc->delayed_next_scr)
3131 	sc_switch_scr(scp->sc, scp->sc->delayed_next_scr - 1);
3132 
3133 }
3134 
3135 void
3136 sc_draw_cursor_image(scr_stat *scp)
3137 {
3138     /* assert(scp == scp->sc->cur_scp); */
3139     atomic_add_int(&scp->sc->videoio_in_progress, 1);
3140     (*scp->rndr->draw_cursor)(scp, scp->cursor_pos,
3141 			      scp->sc->flags & SC_BLINK_CURSOR, TRUE,
3142 			      sc_inside_cutmark(scp, scp->cursor_pos));
3143     scp->cursor_oldpos = scp->cursor_pos;
3144     atomic_add_int(&scp->sc->videoio_in_progress, -1);
3145 }
3146 
3147 void
3148 sc_remove_cursor_image(scr_stat *scp)
3149 {
3150     /* assert(scp == scp->sc->cur_scp); */
3151     atomic_add_int(&scp->sc->videoio_in_progress, 1);
3152     (*scp->rndr->draw_cursor)(scp, scp->cursor_oldpos,
3153 			      scp->sc->flags & SC_BLINK_CURSOR, FALSE,
3154 			      sc_inside_cutmark(scp, scp->cursor_oldpos));
3155     atomic_add_int(&scp->sc->videoio_in_progress, -1);
3156 }
3157 
3158 static void
3159 update_cursor_image(scr_stat *scp)
3160 {
3161     int blink;
3162 
3163     if (scp->sc->flags & SC_CHAR_CURSOR) {
3164 	scp->cursor_base = imax(0, scp->sc->cursor_base);
3165 	scp->cursor_height = imin(scp->sc->cursor_height, scp->font_height);
3166     } else {
3167 	scp->cursor_base = 0;
3168 	scp->cursor_height = scp->font_height;
3169     }
3170     blink = scp->sc->flags & SC_BLINK_CURSOR;
3171 
3172     /* assert(scp == scp->sc->cur_scp); */
3173     atomic_add_int(&scp->sc->videoio_in_progress, 1);
3174     (*scp->rndr->draw_cursor)(scp, scp->cursor_oldpos, blink, FALSE,
3175 			      sc_inside_cutmark(scp, scp->cursor_pos));
3176     (*scp->rndr->set_cursor)(scp, scp->cursor_base, scp->cursor_height, blink);
3177     (*scp->rndr->draw_cursor)(scp, scp->cursor_pos, blink, TRUE,
3178 			      sc_inside_cutmark(scp, scp->cursor_pos));
3179     atomic_add_int(&scp->sc->videoio_in_progress, -1);
3180 }
3181 
3182 void
3183 sc_set_cursor_image(scr_stat *scp)
3184 {
3185     if (scp->sc->flags & SC_CHAR_CURSOR) {
3186 	scp->cursor_base = imax(0, scp->sc->cursor_base);
3187 	scp->cursor_height = imin(scp->sc->cursor_height, scp->font_height);
3188     } else {
3189 	scp->cursor_base = 0;
3190 	scp->cursor_height = scp->font_height;
3191     }
3192 
3193     /* assert(scp == scp->sc->cur_scp); */
3194     atomic_add_int(&scp->sc->videoio_in_progress, 1);
3195     (*scp->rndr->set_cursor)(scp, scp->cursor_base, scp->cursor_height,
3196 			     scp->sc->flags & SC_BLINK_CURSOR);
3197     atomic_add_int(&scp->sc->videoio_in_progress, -1);
3198 }
3199 
3200 static void
3201 scinit(int unit, int flags)
3202 {
3203     /*
3204      * When syscons is being initialized as the kernel console, malloc()
3205      * is not yet functional, because various kernel structures has not been
3206      * fully initialized yet.  Therefore, we need to declare the following
3207      * static buffers for the console.  This is less than ideal,
3208      * but is necessry evil for the time being.  XXX
3209      */
3210     static scr_stat main_console;
3211     static u_short sc_buffer[2*ROW*2*COL];	/* XXX */
3212 #ifndef SC_NO_FONT_LOADING
3213     static u_char font_8[256*8];
3214     static u_char font_14[256*14];
3215     static u_char font_16[256*16];
3216 #endif
3217 
3218     sc_softc_t *sc;
3219     scr_stat *scp;
3220     video_adapter_t *adp;
3221     char tbuf[MAKEDEV_MINNBUF];
3222     int col;
3223     int row;
3224     int i;
3225 
3226     /* one time initialization */
3227     if (init_done == COLD)
3228 	sc_get_bios_values(&bios_value);
3229     init_done = WARM;
3230 
3231     /*
3232      * Allocate resources.  Even if we are being called for the second
3233      * time, we must allocate them again, because they might have
3234      * disappeared...
3235      */
3236     sc = sc_get_softc(unit, flags & SC_KERNEL_CONSOLE);
3237     adp = NULL;
3238     if (flags & SC_EFI_FB) {
3239 	/* Don't replace already registered drm framebuffer here */
3240 	if (sc->fbi == NULL) {
3241 	    sc->fbi = &efi_fb_info;
3242 	    sc->fbi_generation++;
3243 	}
3244     } else if (sc->adapter >= 0) {
3245 	vid_release(sc->adp, (void *)&sc->adapter);
3246 	adp = sc->adp;
3247     }
3248     sc->adp = NULL;
3249     if (sc->keyboard >= 0) {
3250 	DPRINTF(5, ("sc%d: releasing kbd%d\n", unit, sc->keyboard));
3251 	i = kbd_release(sc->kbd, (void *)&sc->keyboard);
3252 	DPRINTF(5, ("sc%d: kbd_release returned %d\n", unit, i));
3253 	if (sc->kbd != NULL) {
3254 	    DPRINTF(5, ("sc%d: kbd != NULL!, index:%d, unit:%d, flags:0x%x\n",
3255 		unit, sc->kbd->kb_index, sc->kbd->kb_unit, sc->kbd->kb_flags));
3256 	}
3257 	sc->kbd = NULL;
3258     }
3259     if (!(flags & SC_EFI_FB)) {
3260 	sc->adapter = vid_allocate("*", unit, (void *)&sc->adapter);
3261 	sc->adp = vid_get_adapter(sc->adapter);
3262 	/* assert((sc->adapter >= 0) && (sc->adp != NULL)) */
3263     }
3264     sc->keyboard = sc_allocate_keyboard(sc, unit);
3265     DPRINTF(1, ("sc%d: keyboard %d\n", unit, sc->keyboard));
3266     sc->kbd = kbd_get_keyboard(sc->keyboard);
3267     if (sc->kbd != NULL) {
3268 	DPRINTF(1, ("sc%d: kbd index:%d, unit:%d, flags:0x%x\n",
3269 		unit, sc->kbd->kb_index, sc->kbd->kb_unit, sc->kbd->kb_flags));
3270     }
3271 
3272     if (!(sc->flags & SC_INIT_DONE) || (adp != sc->adp)) {
3273 
3274 	if (sc->fbi != NULL)
3275 		sc->initial_mode = 0;
3276 	else
3277 		sc->initial_mode = sc->adp->va_initial_mode;
3278 
3279 #ifndef SC_NO_FONT_LOADING
3280 	if (flags & SC_KERNEL_CONSOLE) {
3281 	    sc->font_8 = font_8;
3282 	    sc->font_14 = font_14;
3283 	    sc->font_16 = font_16;
3284 	} else if (sc->font_8 == NULL) {
3285 	    /* assert(sc_malloc) */
3286 	    sc->font_8 = kmalloc(sizeof(font_8), M_SYSCONS, M_WAITOK);
3287 	    sc->font_14 = kmalloc(sizeof(font_14), M_SYSCONS, M_WAITOK);
3288 	    sc->font_16 = kmalloc(sizeof(font_16), M_SYSCONS, M_WAITOK);
3289 	}
3290 #endif
3291 
3292 	if (sc->fbi != NULL) {
3293 	    col = 0;
3294 	    row = 0;
3295 	} else {
3296 	    lwkt_gettoken(&vga_token);
3297 	    /* extract the hw cursor location and hide the cursor for now */
3298 	    (*vidsw[sc->adapter]->read_hw_cursor)(sc->adp, &col, &row);
3299 	    (*vidsw[sc->adapter]->set_hw_cursor)(sc->adp, -1, -1);
3300 	    lwkt_reltoken(&vga_token);
3301 	}
3302 
3303 	/* set up the first console */
3304 	sc->first_vty = unit*MAXCONS;
3305 	sc->vtys = MAXCONS;		/* XXX: should be configurable */
3306 	if (flags & SC_KERNEL_CONSOLE) {
3307 	    scp = &main_console;
3308 	    sc->console_scp = scp;
3309 	    init_scp(sc, sc->first_vty, scp);
3310 	    sc_vtb_init(&scp->vtb, VTB_MEMORY, scp->xsize, scp->ysize,
3311 			(void *)sc_buffer, FALSE);
3312 	    if (sc_init_emulator(scp, SC_DFLT_TERM))
3313 		sc_init_emulator(scp, "*");
3314 	    (*scp->tsw->te_default_attr)(scp,
3315 					 kernel_default.std_color,
3316 					 kernel_default.rev_color);
3317 	} else {
3318 	    /* assert(sc_malloc) */
3319 	    sc->dev = kmalloc(sizeof(cdev_t)*sc->vtys, M_SYSCONS, M_WAITOK | M_ZERO);
3320 
3321 	    sc->dev[0] = make_dev(&sc_ops, unit*MAXCONS, UID_ROOT,
3322 				  GID_WHEEL, 0600, "ttyv%s",
3323 				  makedev_unit_b32(tbuf, unit * MAXCONS));
3324 
3325 	    ttymalloc(&sc->dev[0]->si_tty);
3326 	    scp = alloc_scp(sc, sc->first_vty);
3327 	    sc->dev[0]->si_drv1 = scp;
3328 	}
3329 	sc->cur_scp = scp;
3330 
3331 	/* copy screen to temporary buffer */
3332 	if (scp->sc->fbi == NULL) {
3333 	    sc_vtb_init(&scp->scr, VTB_FRAMEBUFFER, scp->xsize, scp->ysize,
3334 			(void *)scp->sc->adp->va_window, FALSE);
3335 	    if (ISTEXTSC(scp))
3336 		sc_vtb_copy(&scp->scr, 0, &scp->vtb, 0, scp->xsize*scp->ysize);
3337 	}
3338 
3339 	/* move cursors to the initial positions */
3340 	if (col >= scp->xsize)
3341 	    col = 0;
3342 	if (row >= scp->ysize)
3343 	    row = scp->ysize - 1;
3344 	scp->xpos = col;
3345 	scp->ypos = row;
3346 	if (sc->fbi != NULL) {
3347 	    scp->cursor_pos = 0;
3348 	    sc->cursor_base = 0;
3349 	    sc->cursor_height = scp->font_height;
3350 	} else {
3351 	    scp->cursor_pos = scp->cursor_oldpos = row*scp->xsize + col;
3352 	    if (bios_value.cursor_end < scp->font_height)
3353 		sc->cursor_base = scp->font_height - bios_value.cursor_end - 1;
3354 	    else
3355 		sc->cursor_base = 0;
3356 	    i = bios_value.cursor_end - bios_value.cursor_start + 1;
3357 	    sc->cursor_height = imin(i, scp->font_height);
3358 	}
3359 #ifndef SC_NO_SYSMOUSE
3360 	sc_mouse_move(scp, scp->xpixel/2, scp->ypixel/2);
3361 #endif
3362 	if (!ISGRAPHSC(scp)) {
3363     	    sc_set_cursor_image(scp);
3364     	    sc_draw_cursor_image(scp);
3365 	    /* If framebuffer vaddr is still 0, we can't draw the border yet */
3366 	    if (scp->sc->fbi != NULL && scp->sc->fbi->vaddr != 0) {
3367 		sc_filled_border = TRUE;
3368 		sc_set_border(scp, scp->border);
3369 	    }
3370 	}
3371 
3372 	/* save font and palette */
3373 #ifndef SC_NO_FONT_LOADING
3374 	sc->fonts_loaded = 0;
3375 #ifdef SC_DFLT_FONT
3376 	bcopy(dflt_font_8, sc->font_8, sizeof(dflt_font_8));
3377 	bcopy(dflt_font_14, sc->font_14, sizeof(dflt_font_14));
3378 	bcopy(dflt_font_16, sc->font_16, sizeof(dflt_font_16));
3379 	sc->fonts_loaded = FONT_16 | FONT_14 | FONT_8;
3380 #endif /* SC_DFLT_FONT */
3381 	if (sc->adp != NULL && ISFONTAVAIL(sc->adp->va_flags)) {
3382 #ifdef SC_DFLT_FONT
3383 	    if (scp->font_height < 14) {
3384 		sc_load_font(scp, 0, 8, sc->font_8, 0, 256);
3385 	    } else if (scp->font_height >= 16) {
3386 		sc_load_font(scp, 0, 16, sc->font_16, 0, 256);
3387 	    } else {
3388 		sc_load_font(scp, 0, 14, sc->font_14, 0, 256);
3389 	    }
3390 #else /* !SC_DFLT_FONT */
3391 	    if (scp->font_height < 14) {
3392 		sc_save_font(scp, 0, 8, sc->font_8, 0, 256);
3393 		sc->fonts_loaded = FONT_8;
3394 	    } else if (scp->font_height >= 16) {
3395 		sc_save_font(scp, 0, 16, sc->font_16, 0, 256);
3396 		sc->fonts_loaded = FONT_16;
3397 	    } else {
3398 		sc_save_font(scp, 0, 14, sc->font_14, 0, 256);
3399 		sc->fonts_loaded = FONT_14;
3400 	    }
3401 #endif /* SC_DFLT_FONT */
3402 	    /* FONT KLUDGE: always use the font page #0. XXX */
3403 	    sc_show_font(scp, 0);
3404 	}
3405 #endif /* !SC_NO_FONT_LOADING */
3406 
3407 	if (!(flags & SC_EFI_FB))
3408 	    save_palette(sc->adp, sc->palette);
3409 
3410 #if NSPLASH > 0
3411 	if (!(sc->flags & SC_SPLASH_SCRN) && (flags & SC_KERNEL_CONSOLE)) {
3412 	    /* we are ready to put up the splash image! */
3413 	    splash_init(sc->adp, scsplash_callback, sc);
3414 	    sc->flags |= SC_SPLASH_SCRN;
3415 	}
3416 #endif /* NSPLASH */
3417     }
3418 
3419     /* the rest is not necessary, if we have done it once */
3420     if (sc->flags & SC_INIT_DONE) {
3421 	return;
3422     }
3423 
3424     /* initialize mapscrn arrays to a one to one map */
3425     for (i = 0; i < sizeof(sc->scr_map); i++)
3426 	sc->scr_map[i] = sc->scr_rmap[i] = i;
3427 
3428     sc->flags |= SC_INIT_DONE;
3429 }
3430 
3431 #if 0
3432 static void
3433 scterm(int unit, int flags)
3434 {
3435     sc_softc_t *sc;
3436     scr_stat *scp;
3437 
3438     sc = sc_get_softc(unit, flags & SC_KERNEL_CONSOLE);
3439     if (sc == NULL)
3440 	return;			/* shouldn't happen */
3441 
3442     lwkt_gettoken(&vga_token);
3443 #if NSPLASH > 0
3444     /* this console is no longer available for the splash screen */
3445     if (sc->flags & SC_SPLASH_SCRN) {
3446 	splash_term(sc->adp);
3447 	sc->flags &= ~SC_SPLASH_SCRN;
3448     }
3449 #endif /* NSPLASH */
3450 
3451 #if 0 /* XXX */
3452     /* move the hardware cursor to the upper-left corner */
3453     (*vidsw[sc->adapter]->set_hw_cursor)(sc->adp, 0, 0);
3454 #endif
3455 
3456     /* release the keyboard and the video card */
3457     if (sc->keyboard >= 0)
3458 	kbd_release(sc->kbd, &sc->keyboard);
3459     if (sc->adapter >= 0)
3460 	vid_release(sc->adp, &sc->adapter);
3461 
3462     /*
3463      * Stop the terminal emulator, if any.  If operating on the
3464      * kernel console sc->dev may not be setup yet.
3465      */
3466     if (flags & SC_KERNEL_CONSOLE)
3467 	scp = sc->console_scp;
3468     else
3469 	scp = SC_STAT(sc->dev[0]);
3470     if (scp->tsw)
3471 	(*scp->tsw->te_term)(scp, &scp->ts);
3472     if (scp->ts != NULL)
3473 	kfree(scp->ts, M_SYSCONS);
3474 
3475     /* clear the structure */
3476     if (!(flags & SC_KERNEL_CONSOLE)) {
3477 	/* XXX: We need delete_dev() for this */
3478 	kfree(sc->dev, M_SYSCONS);
3479 #if 0
3480 	/* XXX: We need a ttyunregister for this */
3481 	/* XXX: do not race tty token access */
3482 	kfree(sc->tty, M_SYSCONS);
3483 #endif
3484 #ifndef SC_NO_FONT_LOADING
3485 	kfree(sc->font_8, M_SYSCONS);
3486 	kfree(sc->font_14, M_SYSCONS);
3487 	kfree(sc->font_16, M_SYSCONS);
3488 #endif
3489 	/* XXX vtb, history */
3490     }
3491     bzero(sc, sizeof(*sc));
3492     sc->keyboard = -1;
3493     sc->adapter = -1;
3494     lwkt_reltoken(&vga_token);
3495 }
3496 #endif
3497 
3498 static void
3499 scshutdown(void *arg, int howto)
3500 {
3501     /* assert(sc_console != NULL) */
3502 
3503     lwkt_gettoken(&vga_token);
3504     syscons_lock();
3505     sc_touch_scrn_saver();
3506     if (!cold && sc_console
3507 	&& sc_console->sc->cur_scp->smode.mode == VT_AUTO
3508 	&& sc_console->smode.mode == VT_AUTO) {
3509 	sc_switch_scr(sc_console->sc, sc_console->index);
3510     }
3511     shutdown_in_progress = TRUE;
3512     syscons_unlock();
3513     lwkt_reltoken(&vga_token);
3514 }
3515 
3516 int
3517 sc_clean_up(scr_stat *scp, int need_unlock)
3518 {
3519 #if NSPLASH > 0
3520     int error;
3521 #endif /* NSPLASH */
3522 
3523     lwkt_gettoken(&vga_token);
3524     if (scp->sc->flags & SC_SCRN_BLANKED) {
3525 	sc_touch_scrn_saver();
3526 #if NSPLASH > 0
3527 	if ((error = wait_scrn_saver_stop(scp->sc, need_unlock))) {
3528 	    lwkt_reltoken(&vga_token);
3529 	    return error;
3530 	}
3531 #endif /* NSPLASH */
3532     }
3533     scp->status |= MOUSE_HIDDEN;
3534     sc_remove_mouse_image(scp);
3535     sc_remove_cutmarking(scp);
3536     lwkt_reltoken(&vga_token);
3537     return 0;
3538 }
3539 
3540 void
3541 sc_alloc_scr_buffer(scr_stat *scp, int wait, int discard)
3542 {
3543     sc_vtb_t new;
3544     sc_vtb_t old;
3545 
3546     lwkt_gettoken(&vga_token);
3547     old = scp->vtb;
3548     sc_vtb_init(&new, VTB_MEMORY, scp->xsize, scp->ysize, NULL, wait);
3549     if (!discard && (old.vtb_flags & VTB_VALID)) {
3550 	/* retain the current cursor position and buffer contants */
3551 	scp->cursor_oldpos = scp->cursor_pos;
3552 	/*
3553 	 * This works only if the old buffer has the same size as or larger
3554 	 * than the new one. XXX
3555 	 */
3556 	sc_vtb_copy(&old, 0, &new, 0, scp->xsize*scp->ysize);
3557 	scp->vtb = new;
3558     } else {
3559 	scp->vtb = new;
3560 	sc_vtb_destroy(&old);
3561     }
3562 
3563 #ifndef SC_NO_SYSMOUSE
3564     /* move the mouse cursor at the center of the screen */
3565     sc_mouse_move(scp, scp->xpixel / 2, scp->ypixel / 2);
3566 #endif
3567     lwkt_reltoken(&vga_token);
3568 }
3569 
3570 static scr_stat *
3571 alloc_scp(sc_softc_t *sc, int vty)
3572 {
3573     scr_stat *scp;
3574 
3575     /* assert(sc_malloc) */
3576 
3577     scp = kmalloc(sizeof(scr_stat), M_SYSCONS, M_WAITOK);
3578     init_scp(sc, vty, scp);
3579 
3580     sc_alloc_scr_buffer(scp, TRUE, TRUE);
3581     if (sc_init_emulator(scp, SC_DFLT_TERM))
3582 	sc_init_emulator(scp, "*");
3583 
3584 #ifndef SC_NO_CUTPASTE
3585     sc_alloc_cut_buffer(scp, TRUE);
3586 #endif
3587 
3588 #ifndef SC_NO_HISTORY
3589     sc_alloc_history_buffer(scp, 0, 0, TRUE);
3590 #endif
3591     return scp;
3592 }
3593 
3594 /*
3595  * NOTE: Must be called with vga_token held.
3596  */
3597 static void
3598 init_scp(sc_softc_t *sc, int vty, scr_stat *scp)
3599 {
3600     video_info_t info;
3601 
3602     bzero(scp, sizeof(*scp));
3603 
3604     scp->index = vty;
3605     scp->sc = sc;
3606     scp->status = 0;
3607     scp->mode = sc->initial_mode;
3608     scp->fbi_generation = sc->fbi_generation;
3609     callout_init_lk(&scp->blink_screen_ch, &syscons_blink_lk);
3610     if (scp->sc->fbi == NULL) {
3611 	lwkt_gettoken(&vga_token);
3612 	(*vidsw[sc->adapter]->get_info)(sc->adp, scp->mode, &info);
3613 	lwkt_reltoken(&vga_token);
3614     }
3615     if (scp->sc->fbi != NULL) {
3616 	scp->xpixel = sc->fbi->width;
3617 	scp->ypixel = sc->fbi->height;
3618 	scp->font_width = 8;
3619 	scp->font_height = 16;
3620 
3621 	/* The first vty uses a statically allocated 160x50 buffer */
3622 	if (vty == sc->first_vty)
3623 		sc_font_scale(scp, 2*COL, 2*ROW);
3624 	else
3625 		sc_font_scale(scp, 0, 0);
3626 
3627 #ifndef SC_NO_FONT_LOADING
3628 	scp->font = sc->font_16;
3629 #else
3630 	scp->font = NULL;
3631 #endif
3632     } else if (info.vi_flags & V_INFO_GRAPHICS) {
3633 	scp->status |= GRAPHICS_MODE;
3634 	scp->xpixel = info.vi_width;
3635 	scp->ypixel = info.vi_height;
3636 	scp->xsize = info.vi_width/8;
3637 	scp->ysize = info.vi_height/info.vi_cheight;
3638 	scp->font_height = 0;
3639 	scp->font_width = 0;
3640 	scp->font = NULL;
3641     } else {
3642 	scp->xsize = info.vi_width;
3643 	scp->ysize = info.vi_height;
3644 	scp->xpixel = scp->xsize*8;
3645 	scp->ypixel = scp->ysize*info.vi_cheight;
3646 	scp->font_width = 8;
3647 	if (info.vi_cheight < 14) {
3648 	    scp->font_height = 8;
3649 #ifndef SC_NO_FONT_LOADING
3650 	    scp->font = sc->font_8;
3651 #else
3652 	    scp->font = NULL;
3653 #endif
3654 	} else if (info.vi_cheight >= 16) {
3655 	    scp->font_height = 16;
3656 #ifndef SC_NO_FONT_LOADING
3657 	    scp->font = sc->font_16;
3658 #else
3659 	    scp->font = NULL;
3660 #endif
3661 	} else {
3662 	    scp->font_height = 14;
3663 #ifndef SC_NO_FONT_LOADING
3664 	    scp->font = sc->font_14;
3665 #else
3666 	    scp->font = NULL;
3667 #endif
3668 	}
3669     }
3670     scp->xoff = scp->yoff = 0;
3671     scp->xpos = scp->ypos = 0;
3672     sc_vtb_init(&scp->vtb, VTB_MEMORY, 0, 0, NULL, FALSE);
3673     sc_vtb_init(&scp->scr, VTB_FRAMEBUFFER, 0, 0, NULL, FALSE);
3674     scp->start = scp->xsize * scp->ysize - 1;
3675     scp->end = 0;
3676     scp->tsw = NULL;
3677     scp->ts = NULL;
3678     scp->rndr = NULL;
3679     scp->border = SC_BORDER_COLOR;
3680     scp->cursor_base = sc->cursor_base;
3681     scp->cursor_height = imin(sc->cursor_height, scp->font_height);
3682     scp->mouse_cut_start = scp->xsize * scp->ysize;
3683     scp->mouse_cut_end = -1;
3684     scp->mouse_signal = 0;
3685     scp->mouse_pid = 0;
3686     scp->mouse_proc = NULL;
3687     scp->kbd_mode = K_XLATE;
3688     scp->bell_pitch = bios_value.bell_pitch;
3689     scp->bell_duration = BELL_DURATION;
3690     scp->status |= (bios_value.shift_state & NLKED);
3691     scp->status |= CURSOR_ENABLED | MOUSE_HIDDEN;
3692     scp->pid = 0;
3693     scp->proc = NULL;
3694     scp->smode.mode = VT_AUTO;
3695     scp->history = NULL;
3696     scp->history_pos = 0;
3697     scp->history_size = 0;
3698 }
3699 
3700 int
3701 sc_init_emulator(scr_stat *scp, char *name)
3702 {
3703     sc_term_sw_t *sw;
3704     sc_rndr_sw_t *rndr;
3705     void *p;
3706     int error;
3707 
3708     if (name == NULL)	/* if no name is given, use the current emulator */
3709 	sw = scp->tsw;
3710     else		/* ...otherwise find the named emulator */
3711 	sw = sc_term_match(name);
3712     if (sw == NULL) {
3713 	return EINVAL;
3714     }
3715 
3716     rndr = NULL;
3717     if (strcmp(sw->te_renderer, "*") != 0) {
3718 	rndr = sc_render_match(scp, sw->te_renderer, scp->model);
3719     }
3720     if (rndr == NULL && scp->sc->fbi != NULL) {
3721 	rndr = sc_render_match(scp, "kms", scp->model);
3722     }
3723     if (rndr == NULL) {
3724 	rndr = sc_render_match(scp, scp->sc->adp->va_name, scp->model);
3725 	if (rndr == NULL) {
3726 	    return ENODEV;
3727 	}
3728     }
3729 
3730     if (sw == scp->tsw) {
3731 	error = (*sw->te_init)(scp, &scp->ts, SC_TE_WARM_INIT);
3732 	scp->rndr = rndr;
3733 	sc_clear_screen(scp);
3734 	/* assert(error == 0); */
3735 	return error;
3736     }
3737 
3738     if (sc_malloc && (sw->te_size > 0))
3739 	p = kmalloc(sw->te_size, M_SYSCONS, M_NOWAIT);
3740     else
3741 	p = NULL;
3742     error = (*sw->te_init)(scp, &p, SC_TE_COLD_INIT);
3743     if (error) {
3744 	return error;
3745     }
3746 
3747     if (scp->tsw)
3748 	(*scp->tsw->te_term)(scp, &scp->ts);
3749     if (scp->ts != NULL)
3750 	kfree(scp->ts, M_SYSCONS);
3751     scp->tsw = sw;
3752     scp->ts = p;
3753     scp->rndr = rndr;
3754 
3755     /* XXX */
3756     (*sw->te_default_attr)(scp, user_default.std_color, user_default.rev_color);
3757     sc_clear_screen(scp);
3758 
3759     return 0;
3760 }
3761 
3762 /*
3763  * scgetc(flags) - get character from keyboard.
3764  * If flags & SCGETC_CN, then avoid harmful side effects.
3765  * If flags & SCGETC_NONBLOCK, then wait until a key is pressed, else
3766  * return NOKEY if there is nothing there.
3767  */
3768 static u_int
3769 scgetc(sc_softc_t *sc, u_int flags)
3770 {
3771     scr_stat *scp;
3772 #ifndef SC_NO_HISTORY
3773     struct tty *tp;
3774 #endif
3775     u_int c;
3776     int this_scr;
3777     int f;
3778     int i;
3779 
3780     lwkt_gettoken(&vga_token);
3781     if (sc->kbd == NULL) {
3782         lwkt_reltoken(&vga_token);
3783 	return NOKEY;
3784     }
3785 
3786 next_code:
3787 #if 1
3788     /* I don't like this, but... XXX */
3789     if (flags & SCGETC_CN) {
3790 	syscons_lock();
3791 	sccnupdate(sc->cur_scp);
3792 	syscons_unlock();
3793     }
3794 #endif
3795     scp = sc->cur_scp;
3796     /* first see if there is something in the keyboard port */
3797     for (;;) {
3798 	c = kbd_read_char(sc->kbd, !(flags & SCGETC_NONBLOCK));
3799 	if (c == ERRKEY) {
3800 	    if (!(flags & SCGETC_CN))
3801 		sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3802 	} else if (c == NOKEY) {
3803 	    lwkt_reltoken(&vga_token);
3804 	    return c;
3805 	} else {
3806 	    break;
3807 	}
3808     }
3809 
3810     /* make screensaver happy */
3811     if (!(c & RELKEY))
3812 	sc_touch_scrn_saver();
3813 
3814     if (!(flags & SCGETC_CN))
3815 	/* do the /dev/random device a favour */
3816 	add_keyboard_randomness(c);
3817 
3818     if (scp->kbd_mode != K_XLATE) {
3819         lwkt_reltoken(&vga_token);
3820 	return KEYCHAR(c);
3821     }
3822 
3823     /* if scroll-lock pressed allow history browsing */
3824     if (!ISGRAPHSC(scp) && scp->history && scp->status & SLKED) {
3825 
3826 	scp->status &= ~CURSOR_ENABLED;
3827 	sc_remove_cursor_image(scp);
3828 
3829 #ifndef SC_NO_HISTORY
3830 	if (!(scp->status & BUFFER_SAVED)) {
3831 	    scp->status |= BUFFER_SAVED;
3832 	    sc_hist_save(scp);
3833 	}
3834 	switch (c) {
3835 	/* FIXME: key codes */
3836 	case SPCLKEY | FKEY | F(49):  /* home key */
3837 	    sc_remove_cutmarking(scp);
3838 	    sc_hist_home(scp);
3839 	    goto next_code;
3840 
3841 	case SPCLKEY | FKEY | F(57):  /* end key */
3842 	    sc_remove_cutmarking(scp);
3843 	    sc_hist_end(scp);
3844 	    goto next_code;
3845 
3846 	case SPCLKEY | FKEY | F(50):  /* up arrow key */
3847 	    sc_remove_cutmarking(scp);
3848 	    if (sc_hist_up_line(scp))
3849 		if (!(flags & SCGETC_CN))
3850 		    sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3851 	    goto next_code;
3852 
3853 	case SPCLKEY | FKEY | F(58):  /* down arrow key */
3854 	    sc_remove_cutmarking(scp);
3855 	    if (sc_hist_down_line(scp))
3856 		if (!(flags & SCGETC_CN))
3857 		    sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3858 	    goto next_code;
3859 
3860 	case SPCLKEY | FKEY | F(51):  /* page up key */
3861 	    sc_remove_cutmarking(scp);
3862 	    for (i=0; i<scp->ysize; i++) {
3863 		if (sc_hist_up_line(scp)) {
3864 		    if (!(flags & SCGETC_CN))
3865 			sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3866 		    break;
3867 		}
3868 	    }
3869 	    goto next_code;
3870 
3871 	case SPCLKEY | FKEY | F(59):  /* page down key */
3872 	    sc_remove_cutmarking(scp);
3873 	    for (i=0; i<scp->ysize; i++) {
3874 		if (sc_hist_down_line(scp)) {
3875 		    if (!(flags & SCGETC_CN))
3876 			sc_bell(scp, bios_value.bell_pitch, BELL_DURATION);
3877 		    break;
3878 		}
3879 	    }
3880 	    goto next_code;
3881 	}
3882 #endif /* SC_NO_HISTORY */
3883     }
3884 
3885     /*
3886      * Process and consume special keys here.  Return a plain char code
3887      * or a char code with the META flag or a function key code.
3888      */
3889     if (c & RELKEY) {
3890 	/* key released */
3891 	/* goto next_code */
3892     } else {
3893 	/* key pressed */
3894 	if (c & SPCLKEY) {
3895 	    c &= ~SPCLKEY;
3896 	    switch (KEYCHAR(c)) {
3897 	    /* LOCKING KEYS */
3898 	    case NLK: case CLK: case ALK:
3899 		break;
3900 	    case SLK:
3901 		kbd_ioctl(sc->kbd, KDGKBSTATE, (caddr_t)&f);
3902 		if (f & SLKED) {
3903 		    scp->status |= SLKED;
3904 		} else {
3905 		    if (scp->status & SLKED) {
3906 			scp->status &= ~SLKED;
3907 #ifndef SC_NO_HISTORY
3908 			if (scp->status & BUFFER_SAVED) {
3909 			    if (!sc_hist_restore(scp))
3910 				sc_remove_cutmarking(scp);
3911 			    scp->status &= ~BUFFER_SAVED;
3912 			    scp->status |= CURSOR_ENABLED;
3913 			    sc_draw_cursor_image(scp);
3914 			}
3915 			tp = VIRTUAL_TTY(sc, scp->index);
3916 			if (ISTTYOPEN(tp))
3917 			    scstart(tp);
3918 #endif
3919 		    }
3920 		}
3921 		break;
3922 
3923 	    /* NON-LOCKING KEYS */
3924 	    case NOP:
3925 	    case LSH:  case RSH:  case LCTR: case RCTR:
3926 	    case LALT: case RALT: case ASH:  case META:
3927 		break;
3928 
3929 	    case BTAB:
3930 		if (!(sc->flags & SC_SCRN_BLANKED)) {
3931                     lwkt_reltoken(&vga_token);
3932 		    return c;
3933 		}
3934 		break;
3935 
3936 	    case SPSC:
3937 #if NSPLASH > 0
3938 		/* force activatation/deactivation of the screen saver */
3939 		if (!(sc->flags & SC_SCRN_BLANKED)) {
3940 		    run_scrn_saver = TRUE;
3941 		    sc->scrn_time_stamp -= scrn_blank_time;
3942 		}
3943 		if (cold) {
3944 		    /*
3945 		     * While devices are being probed, the screen saver need
3946 		     * to be invoked explictly. XXX
3947 		     */
3948 		    if (sc->flags & SC_SCRN_BLANKED) {
3949 			scsplash_stick(FALSE);
3950 			stop_scrn_saver(sc, current_saver);
3951 		    } else {
3952 			if (!ISGRAPHSC(scp)) {
3953 			    scsplash_stick(TRUE);
3954 			    (*current_saver)(sc, TRUE);
3955 			}
3956 		    }
3957 		}
3958 #endif /* NSPLASH */
3959 		break;
3960 
3961 	    case RBT:
3962 #ifndef SC_DISABLE_REBOOT
3963 		shutdown_nice(0);
3964 #endif
3965 		break;
3966 
3967 	    case HALT:
3968 #ifndef SC_DISABLE_REBOOT
3969 		shutdown_nice(RB_HALT);
3970 #endif
3971 		break;
3972 
3973 	    case PDWN:
3974 #ifndef SC_DISABLE_REBOOT
3975 		shutdown_nice(RB_HALT|RB_POWEROFF);
3976 #endif
3977 		break;
3978 
3979 	    case SUSP:
3980 	    case STBY:
3981 		break;
3982 
3983 	    case DBG:
3984 #ifndef SC_DISABLE_DDBKEY
3985 #ifdef DDB
3986 		lwkt_reltoken(&vga_token);
3987 		Debugger("manual escape to debugger");
3988 		lwkt_gettoken(&vga_token);
3989 #else
3990 		kprintf("No debugger in kernel\n");
3991 #endif
3992 #else /* SC_DISABLE_DDBKEY */
3993 		/* do nothing */
3994 #endif /* SC_DISABLE_DDBKEY */
3995 		break;
3996 
3997 	    case PNC:
3998 		if (enable_panic_key)
3999 			panic("Forced by the panic key");
4000 		break;
4001 
4002 	    case NEXT:
4003 		this_scr = scp->index;
4004 		for (i = (this_scr - sc->first_vty + 1)%sc->vtys;
4005 			sc->first_vty + i != this_scr;
4006 			i = (i + 1)%sc->vtys) {
4007 		    struct tty *tp = VIRTUAL_TTY(sc, sc->first_vty + i);
4008 		    if (ISTTYOPEN(tp)) {
4009 			syscons_lock();
4010 			sc_switch_scr(scp->sc, sc->first_vty + i);
4011 			syscons_unlock();
4012 			break;
4013 		    }
4014 		}
4015 		break;
4016 
4017 	    case PREV:
4018 		this_scr = scp->index;
4019 		for (i = (this_scr - sc->first_vty + sc->vtys - 1)%sc->vtys;
4020 			sc->first_vty + i != this_scr;
4021 			i = (i + sc->vtys - 1)%sc->vtys) {
4022 		    struct tty *tp = VIRTUAL_TTY(sc, sc->first_vty + i);
4023 		    if (ISTTYOPEN(tp)) {
4024 			syscons_lock();
4025 			sc_switch_scr(scp->sc, sc->first_vty + i);
4026 			syscons_unlock();
4027 			break;
4028 		    }
4029 		}
4030 		break;
4031 
4032 	    default:
4033 		if (KEYCHAR(c) >= F_SCR && KEYCHAR(c) <= L_SCR) {
4034 		    syscons_lock();
4035 		    sc_switch_scr(scp->sc, sc->first_vty + KEYCHAR(c) - F_SCR);
4036 		    syscons_unlock();
4037 		    break;
4038 		}
4039 		/* assert(c & FKEY) */
4040 		if (!(sc->flags & SC_SCRN_BLANKED)) {
4041 		    lwkt_reltoken(&vga_token);
4042 		    return c;
4043 		}
4044 		break;
4045 	    }
4046 	    /* goto next_code */
4047 	} else {
4048 	    /* regular keys (maybe MKEY is set) */
4049 	    if (!(sc->flags & SC_SCRN_BLANKED)) {
4050 		lwkt_reltoken(&vga_token);
4051 		return c;
4052 	    }
4053 	}
4054     }
4055 
4056     goto next_code;
4057 }
4058 
4059 static int
4060 scmmap(struct dev_mmap_args *ap)
4061 {
4062     scr_stat *scp;
4063 
4064     lwkt_gettoken(&vga_token);
4065     scp = SC_STAT(ap->a_head.a_dev);
4066     if (scp != scp->sc->cur_scp) {
4067         lwkt_reltoken(&vga_token);
4068 	return EINVAL;
4069     }
4070     if (scp->sc->fbi != NULL) {
4071 	size_t sz =
4072 	    roundup(scp->sc->fbi->height * scp->sc->fbi->stride, PAGE_SIZE);
4073 	if (ap->a_offset > sz - PAGE_SIZE) {
4074 	    lwkt_reltoken(&vga_token);
4075 	    return EINVAL;
4076 	} else {
4077 	    ap->a_result = atop(scp->sc->fbi->paddr + ap->a_offset);
4078 	}
4079     } else {
4080 	ap->a_result = (*vidsw[scp->sc->adapter]->mmap)(scp->sc->adp,
4081 							ap->a_offset,
4082 							ap->a_nprot);
4083     }
4084     lwkt_reltoken(&vga_token);
4085     return(0);
4086 }
4087 
4088 static int
4089 save_kbd_state(scr_stat *scp, int unlock)
4090 {
4091     int state;
4092     int error;
4093 
4094     WANT_UNLOCK(unlock);
4095     error = kbd_ioctl(scp->sc->kbd, KDGKBSTATE, (caddr_t)&state);
4096     WANT_LOCK(unlock);
4097 
4098     if (error == ENOIOCTL)
4099 	error = ENODEV;
4100     if (error == 0) {
4101 	scp->status &= ~LOCK_MASK;
4102 	scp->status |= state;
4103     }
4104     return error;
4105 }
4106 
4107 static int
4108 update_kbd_state(scr_stat *scp, int new_bits, int mask, int unlock)
4109 {
4110     int state;
4111     int error;
4112 
4113     if (mask != LOCK_MASK) {
4114 	WANT_UNLOCK(unlock);
4115 	error = kbd_ioctl(scp->sc->kbd, KDGKBSTATE, (caddr_t)&state);
4116 	WANT_LOCK(unlock);
4117 
4118 	if (error == ENOIOCTL)
4119 	    error = ENODEV;
4120 	if (error) {
4121 	    return error;
4122 	}
4123 	state &= ~mask;
4124 	state |= new_bits & mask;
4125     } else {
4126 	state = new_bits & LOCK_MASK;
4127     }
4128     WANT_UNLOCK(unlock);
4129     error = kbd_ioctl(scp->sc->kbd, KDSKBSTATE, (caddr_t)&state);
4130     WANT_LOCK(unlock);
4131     if (error == ENOIOCTL)
4132 	error = ENODEV;
4133     return error;
4134 }
4135 
4136 static int
4137 update_kbd_leds(scr_stat *scp, int which)
4138 {
4139     int error;
4140 
4141     which &= LOCK_MASK;
4142     error = kbd_ioctl(scp->sc->kbd, KDSETLED, (caddr_t)&which);
4143     if (error == ENOIOCTL)
4144 	error = ENODEV;
4145     return error;
4146 }
4147 
4148 int
4149 set_mode(scr_stat *scp)
4150 {
4151     video_info_t info;
4152 
4153     lwkt_gettoken(&vga_token);
4154     /* reject unsupported mode */
4155     if (scp->sc->fbi == NULL && (*vidsw[scp->sc->adapter]->get_info)(scp->sc->adp, scp->mode, &info)) {
4156         lwkt_reltoken(&vga_token);
4157 	return 1;
4158     }
4159 
4160     /* if this vty is not currently showing, do nothing */
4161     if (scp != scp->sc->cur_scp) {
4162         lwkt_reltoken(&vga_token);
4163 	return 0;
4164     }
4165 
4166     /* setup video hardware for the given mode */
4167     if (scp->sc->fbi == NULL) {
4168 	(*vidsw[scp->sc->adapter]->set_mode)(scp->sc->adp, scp->mode);
4169 	sc_vtb_init(&scp->scr, VTB_FRAMEBUFFER, scp->xsize, scp->ysize,
4170 		    (void *)scp->sc->adp->va_window, FALSE);
4171     } else {
4172 	goto done;
4173     }
4174 
4175 #ifndef SC_NO_FONT_LOADING
4176     /* load appropriate font */
4177     if (!(scp->status & GRAPHICS_MODE)) {
4178 	if (!(scp->status & PIXEL_MODE) && ISFONTAVAIL(scp->sc->adp->va_flags)) {
4179 	    if (scp->font_height < 14) {
4180 		if (scp->sc->fonts_loaded & FONT_8)
4181 		    sc_load_font(scp, 0, 8, scp->sc->font_8, 0, 256);
4182 	    } else if (scp->font_height >= 16) {
4183 		if (scp->sc->fonts_loaded & FONT_16)
4184 		    sc_load_font(scp, 0, 16, scp->sc->font_16, 0, 256);
4185 	    } else {
4186 		if (scp->sc->fonts_loaded & FONT_14)
4187 		    sc_load_font(scp, 0, 14, scp->sc->font_14, 0, 256);
4188 	    }
4189 	    /*
4190 	     * FONT KLUDGE:
4191 	     * This is an interim kludge to display correct font.
4192 	     * Always use the font page #0 on the video plane 2.
4193 	     * Somehow we cannot show the font in other font pages on
4194 	     * some video cards... XXX
4195 	     */
4196 	    sc_show_font(scp, 0);
4197 	}
4198 	mark_all(scp);
4199     }
4200 #endif /* !SC_NO_FONT_LOADING */
4201 
4202     sc_set_border(scp, scp->border);
4203     sc_set_cursor_image(scp);
4204 
4205 done:
4206     lwkt_reltoken(&vga_token);
4207     return 0;
4208 }
4209 
4210 void
4211 refresh_ega_palette(scr_stat *scp)
4212 {
4213     uint32_t r, g, b;
4214     int reg;
4215     int rsize, gsize, bsize;
4216     int rfld, gfld, bfld;
4217     int i;
4218 
4219     rsize = scp->sc->adp->va_info.vi_pixel_fsizes[0];
4220     gsize = scp->sc->adp->va_info.vi_pixel_fsizes[1];
4221     bsize = scp->sc->adp->va_info.vi_pixel_fsizes[2];
4222     rfld = scp->sc->adp->va_info.vi_pixel_fields[0];
4223     gfld = scp->sc->adp->va_info.vi_pixel_fields[1];
4224     bfld = scp->sc->adp->va_info.vi_pixel_fields[2];
4225 
4226     for (i = 0; i < 16; i++) {
4227 	reg = scp->sc->adp->va_palette_regs[i];
4228 
4229 	r = scp->sc->palette[reg * 3] >> (8 - rsize);
4230 	g = scp->sc->palette[reg * 3 + 1] >> (8 - gsize);
4231 	b = scp->sc->palette[reg * 3 + 2] >> (8 - bsize);
4232 
4233 	scp->ega_palette[i] = (r << rfld) + (g << gfld) + (b << bfld);
4234     }
4235 }
4236 
4237 void
4238 sc_set_border(scr_stat *scp, int color)
4239 {
4240     atomic_add_int(&scp->sc->videoio_in_progress, 1);
4241     (*scp->rndr->draw_border)(scp, color);
4242     atomic_add_int(&scp->sc->videoio_in_progress, -1);
4243 }
4244 
4245 #ifndef SC_NO_FONT_LOADING
4246 void
4247 sc_load_font(scr_stat *scp, int page, int size, u_char *buf,
4248 	     int base, int count)
4249 {
4250     sc_softc_t *sc;
4251 
4252     sc = scp->sc;
4253     sc->font_loading_in_progress = TRUE;
4254     (*vidsw[sc->adapter]->load_font)(sc->adp, page, size, buf, base, count);
4255     sc->font_loading_in_progress = FALSE;
4256 }
4257 
4258 void
4259 sc_save_font(scr_stat *scp, int page, int size, u_char *buf,
4260 	     int base, int count)
4261 {
4262     sc_softc_t *sc;
4263 
4264     sc = scp->sc;
4265     sc->font_loading_in_progress = TRUE;
4266     (*vidsw[sc->adapter]->save_font)(sc->adp, page, size, buf, base, count);
4267     sc->font_loading_in_progress = FALSE;
4268 }
4269 
4270 void
4271 sc_show_font(scr_stat *scp, int page)
4272 {
4273     (*vidsw[scp->sc->adapter]->show_font)(scp->sc->adp, page);
4274 }
4275 #endif /* !SC_NO_FONT_LOADING */
4276 
4277 void
4278 sc_paste(scr_stat *scp, u_char *p, int count)
4279 {
4280     struct tty *tp;
4281     u_char *rmap;
4282 
4283     /*
4284      * Holy hell, don't try to inject a paste buffer if the keyboard
4285      * is not in ascii mode!
4286      */
4287     if (scp->kbd_mode != K_XLATE)
4288 	return;
4289 
4290     lwkt_gettoken(&vga_token);
4291     if (scp->status & MOUSE_VISIBLE) {
4292 	tp = VIRTUAL_TTY(scp->sc, scp->sc->cur_scp->index);
4293 	lwkt_gettoken(&tp->t_token);
4294 	if (!ISTTYOPEN(tp)) {
4295 	    lwkt_reltoken(&tp->t_token);
4296 	    lwkt_reltoken(&vga_token);
4297 	    return;
4298 	}
4299 	rmap = scp->sc->scr_rmap;
4300 	for (; count > 0; --count)
4301 	    (*linesw[tp->t_line].l_rint)(rmap[*p++], tp);
4302 	lwkt_reltoken(&tp->t_token);
4303     }
4304     lwkt_reltoken(&vga_token);
4305 }
4306 
4307 void
4308 sc_bell(scr_stat *scp, int pitch, int duration)
4309 {
4310     if (cold || shutdown_in_progress)
4311 	return;
4312 
4313     if (scp != scp->sc->cur_scp && (scp->sc->flags & SC_QUIET_BELL)) {
4314 	return;
4315     }
4316 
4317     if (scp->sc->flags & SC_VISUAL_BELL) {
4318 	if (scp->sc->blink_in_progress) {
4319 	    return;
4320 	}
4321 	scp->sc->blink_in_progress = 3;
4322 	if (scp != scp->sc->cur_scp)
4323 	    scp->sc->blink_in_progress += 2;
4324 	lockmgr(&syscons_blink_lk, LK_EXCLUSIVE);
4325 	sc_blink_screen(scp->sc->cur_scp);
4326 	lockmgr(&syscons_blink_lk, LK_RELEASE);
4327     } else if (duration != 0 && pitch != 0) {
4328 	if (scp != scp->sc->cur_scp)
4329 	    pitch *= 2;
4330 	sysbeep(pitch, duration);
4331     }
4332 }
4333 
4334 /*
4335  * Blink the screen, called with the syscons_mtx and syscons_blink_lk
4336  * held.  Can be called directly or via the callout.
4337  */
4338 static void
4339 sc_blink_screen(scr_stat *scp)
4340 {
4341     if (ISGRAPHSC(scp) || (scp->sc->blink_in_progress <= 1)) {
4342 	scp->sc->blink_in_progress = 0;
4343 	mark_all(scp);
4344 	if (scp->sc->delayed_next_scr)
4345 	    sc_switch_scr(scp->sc, scp->sc->delayed_next_scr - 1);
4346     } else {
4347 	(*scp->rndr->draw)(scp, 0, scp->xsize*scp->ysize,
4348 			   scp->sc->blink_in_progress & 1);
4349 	scp->sc->blink_in_progress--;
4350 	callout_reset(&scp->blink_screen_ch, hz / 10,
4351 		      blink_screen_callout, scp);
4352     }
4353 }
4354 
4355 /*
4356  * Screen blink callout.  Note that there is a lock order
4357  * reversal between syscons_blink_lk and the syscons lock.
4358  * Acquire the syscons lock non-blocking.
4359  */
4360 static void
4361 blink_screen_callout(void *arg)
4362 {
4363     scr_stat *scp = arg;
4364 
4365     if (syscons_lock_nonblock() == 0) {
4366 	sc_blink_screen(scp);
4367 	syscons_unlock();
4368     } else {
4369 	callout_reset(&scp->blink_screen_ch, hz / 10,
4370 		      blink_screen_callout, scp);
4371     }
4372 }
4373 
4374 /*
4375  * Allocate active keyboard. Try to allocate "kbdmux" keyboard first, and,
4376  * if found, add all non-busy keyboards to "kbdmux". Otherwise look for
4377  * any keyboard.
4378  */
4379 
4380 static int
4381 sc_allocate_keyboard(sc_softc_t *sc, int unit)
4382 {
4383 	int		 idx0, idx;
4384 	keyboard_t	*k0, *k;
4385 	keyboard_info_t	 ki;
4386 
4387 	idx0 = kbd_allocate("kbdmux", -1, (void *)&sc->keyboard, sckbdevent, sc);
4388 	if (idx0 != -1) {
4389 		k0 = kbd_get_keyboard(idx0);
4390 
4391 		for (idx = kbd_find_keyboard2("*", -1, 0, 0);
4392 		     idx != -1;
4393 		     idx = kbd_find_keyboard2("*", -1, idx + 1, 0)) {
4394 			k = kbd_get_keyboard(idx);
4395 
4396 			if (idx == idx0 || KBD_IS_BUSY(k))
4397 				continue;
4398 
4399 			bzero(&ki, sizeof(ki));
4400 			strcpy(ki.kb_name, k->kb_name);
4401 			ki.kb_unit = k->kb_unit;
4402 
4403 			kbd_ioctl(k0, KBADDKBD, (caddr_t) &ki);
4404 		}
4405 	} else
4406 		idx0 = kbd_allocate("*", unit, (void *)&sc->keyboard, sckbdevent, sc);
4407 
4408 	return (idx0);
4409 }
4410