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