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