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