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