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