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