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