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