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