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