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