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