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