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