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