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