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