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