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