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