syscons.c revision 29875
1/*-
2 * Copyright (c) 1992-1997 S�ren Schmidt
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software withough specific prior written permission
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 *  $Id: syscons.c,v 1.232 1997/09/14 03:19:27 peter Exp $
29 */
30
31#include "sc.h"
32#include "apm.h"
33#include "opt_ddb.h"
34#include "opt_syscons.h"
35
36#if NSC > 0
37#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/conf.h>
40#include <sys/proc.h>
41#include <sys/signalvar.h>
42#include <sys/tty.h>
43#include <sys/kernel.h>
44#include <sys/malloc.h>
45#ifdef	DEVFS
46#include <sys/devfsext.h>
47#endif
48
49#include <machine/clock.h>
50#include <machine/cons.h>
51#include <machine/console.h>
52#include <machine/md_var.h>
53#include <machine/psl.h>
54#include <machine/frame.h>
55#include <machine/pc/display.h>
56#include <machine/apm_bios.h>
57#include <machine/random.h>
58
59#include <vm/vm.h>
60#include <vm/vm_param.h>
61#include <vm/pmap.h>
62
63#include <i386/isa/isa.h>
64#include <i386/isa/isa_device.h>
65#include <i386/isa/timerreg.h>
66#include <i386/isa/kbdtables.h>
67#include <i386/isa/kbdio.h>
68#include <i386/isa/syscons.h>
69
70#if !defined(MAXCONS)
71#define MAXCONS 16
72#endif
73
74#define COLD 0
75#define WARM 1
76
77/* XXX use sc_bcopy where video memory is concerned */
78#define sc_bcopy generic_bcopy
79extern void generic_bcopy(const void *, void *, size_t);
80
81static default_attr user_default = {
82    (FG_LIGHTGREY | BG_BLACK) << 8,
83    (FG_BLACK | BG_LIGHTGREY) << 8
84};
85
86static default_attr kernel_default = {
87    (FG_WHITE | BG_BLACK) << 8,
88    (FG_BLACK | BG_LIGHTGREY) << 8
89};
90
91static  scr_stat    	main_console;
92static  scr_stat    	*console[MAXCONS];
93#ifdef DEVFS
94static	void		*sc_devfs_token[MAXCONS];
95#endif
96	scr_stat    	*cur_console;
97static  scr_stat    	*new_scp, *old_scp;
98static  term_stat   	kernel_console;
99static  default_attr    *current_default;
100static  int     	flags = 0;
101static  int		sc_port = IO_KBD;
102static  KBDC		sc_kbdc = NULL;
103static  char        	init_done = COLD;
104static  u_short		sc_buffer[ROW*COL];
105static  char        	switch_in_progress = FALSE;
106static  char        	write_in_progress = FALSE;
107static  char        	blink_in_progress = FALSE;
108static  int        	blinkrate = 0;
109	u_int       	crtc_addr = MONO_BASE;
110	char		crtc_type = KD_MONO;
111	char        	crtc_vga = FALSE;
112static  u_char      	shfts = 0, ctls = 0, alts = 0, agrs = 0, metas = 0;
113static  u_char      	nlkcnt = 0, clkcnt = 0, slkcnt = 0, alkcnt = 0;
114static  const u_int     n_fkey_tab = sizeof(fkey_tab) / sizeof(*fkey_tab);
115static  int     	delayed_next_scr = FALSE;
116static  long        	scrn_blank_time = 0;    /* screen saver timeout value */
117	int     	scrn_blanked = 0;       /* screen saver active flag */
118static  long       	scrn_time_stamp;
119	u_char      	scr_map[256];
120	u_char      	scr_rmap[256];
121	char        	*video_mode_ptr = NULL;
122	int     	fonts_loaded = 0
123#ifdef STD8X16FONT
124	| FONT_16
125#endif
126	;
127
128	char        	font_8[256*8];
129	char		font_14[256*14];
130#ifdef STD8X16FONT
131extern
132#endif
133	unsigned char	font_16[256*16];
134	char        	palette[256*3];
135static  char		vgaregs[64];
136static	char 		*cut_buffer;
137static  u_short 	mouse_and_mask[16] = {
138				0xc000, 0xe000, 0xf000, 0xf800,
139				0xfc00, 0xfe00, 0xff00, 0xff80,
140				0xfe00, 0x1e00, 0x1f00, 0x0f00,
141				0x0f00, 0x0000, 0x0000, 0x0000
142			};
143static  u_short 	mouse_or_mask[16] = {
144				0x0000, 0x4000, 0x6000, 0x7000,
145				0x7800, 0x7c00, 0x7e00, 0x6800,
146				0x0c00, 0x0c00, 0x0600, 0x0600,
147				0x0000, 0x0000, 0x0000, 0x0000
148			};
149
150static void    		none_saver(int blank) { }
151static void    		(*current_saver)(int blank) = none_saver;
152int  			(*sc_user_ioctl)(dev_t dev, int cmd, caddr_t data,
153					 int flag, struct proc *p) = NULL;
154
155/* OS specific stuff */
156#ifdef not_yet_done
157#define VIRTUAL_TTY(x)  (sccons[x] = ttymalloc(sccons[x]))
158struct  CONSOLE_TTY 	(sccons[MAXCONS] = ttymalloc(sccons[MAXCONS]))
159struct  MOUSE_TTY 	(sccons[MAXCONS+1] = ttymalloc(sccons[MAXCONS+1]))
160struct  tty         	*sccons[MAXCONS+2];
161#else
162#define VIRTUAL_TTY(x)  &sccons[x]
163#define CONSOLE_TTY 	&sccons[MAXCONS]
164#define MOUSE_TTY 	&sccons[MAXCONS+1]
165static struct tty     	sccons[MAXCONS+2];
166#endif
167#define SC_MOUSE 	128
168#define SC_CONSOLE	255
169#define MONO_BUF    	pa_to_va(0xB0000)
170#define CGA_BUF     	pa_to_va(0xB8000)
171u_short         	*Crtat;
172static const int	nsccons = MAXCONS+2;
173
174#define WRAPHIST(scp, pointer, offset)\
175    ((scp->history) + ((((pointer) - (scp->history)) + (scp->history_size)\
176    + (offset)) % (scp->history_size)))
177#define ISSIGVALID(sig)	((sig) > 0 && (sig) < NSIG)
178
179/* this should really be in `rtc.h' */
180#define RTC_EQUIPMENT		0x14
181
182/* prototypes */
183static int scattach(struct isa_device *dev);
184static int scparam(struct tty *tp, struct termios *t);
185static int scprobe(struct isa_device *dev);
186static int scvidprobe(int unit, int flags);
187static int sckbdprobe(int unit, int flags);
188static void scstart(struct tty *tp);
189static void scmousestart(struct tty *tp);
190static void scinit(void);
191static u_int scgetc(u_int flags);
192#define SCGETC_CN	1
193#define SCGETC_NONBLOCK	2
194static scr_stat *get_scr_stat(dev_t dev);
195static scr_stat *alloc_scp(void);
196static void init_scp(scr_stat *scp);
197static int get_scr_num(void);
198static timeout_t scrn_timer;
199static void stop_scrn_saver(void (*saver)(int));
200static void clear_screen(scr_stat *scp);
201static int switch_scr(scr_stat *scp, u_int next_scr);
202static void exchange_scr(void);
203static inline void move_crsr(scr_stat *scp, int x, int y);
204static void scan_esc(scr_stat *scp, u_char c);
205static void draw_cursor_image(scr_stat *scp);
206static void remove_cursor_image(scr_stat *scp);
207static void ansi_put(scr_stat *scp, u_char *buf, int len);
208static u_char *get_fstr(u_int c, u_int *len);
209static void history_to_screen(scr_stat *scp);
210static int history_up_line(scr_stat *scp);
211static int history_down_line(scr_stat *scp);
212static int mask2attr(struct term_stat *term);
213static void set_keyboard(int command, int data);
214static void update_leds(int which);
215static void set_vgaregs(char *modetable);
216static void read_vgaregs(char *buf);
217static int comp_vgaregs(u_char *buf1, u_char *buf2);
218static void dump_vgaregs(u_char *buf);
219static void set_font_mode(void);
220static void set_normal_mode(void);
221static void set_destructive_cursor(scr_stat *scp);
222static void set_mouse_pos(scr_stat *scp);
223static void mouse_cut_start(scr_stat *scp);
224static void mouse_cut_end(scr_stat *scp);
225static void mouse_paste(scr_stat *scp);
226static void draw_mouse_image(scr_stat *scp);
227static void remove_mouse_image(scr_stat *scp);
228static void draw_cutmarking(scr_stat *scp);
229static void remove_cutmarking(scr_stat *scp);
230static void save_palette(void);
231static void do_bell(scr_stat *scp, int pitch, int duration);
232static timeout_t blink_screen;
233#ifdef SC_SPLASH_SCREEN
234static void toggle_splash_screen(scr_stat *scp);
235#endif
236
237struct  isa_driver scdriver = {
238    scprobe, scattach, "sc", 1
239};
240
241static	d_open_t	scopen;
242static	d_close_t	scclose;
243static	d_read_t	scread;
244static	d_write_t	scwrite;
245static	d_ioctl_t	scioctl;
246static	d_devtotty_t	scdevtotty;
247static	d_mmap_t	scmmap;
248
249#define CDEV_MAJOR 12
250static	struct cdevsw	scdevsw = {
251	scopen,		scclose,	scread,		scwrite,
252	scioctl,	nullstop,	noreset,	scdevtotty,
253	ttpoll,		scmmap,		nostrategy,	"sc",	NULL,	-1 };
254
255/*
256 * These functions need to be before calls to them so they can be inlined.
257 */
258static inline void
259draw_cursor_image(scr_stat *scp)
260{
261    u_short cursor_image, *ptr = Crtat + (scp->cursor_pos - scp->scr_buf);
262    u_short prev_image;
263
264    /* do we have a destructive cursor ? */
265    if (flags & CHAR_CURSOR) {
266	prev_image = scp->cursor_saveunder;
267	cursor_image = *ptr & 0x00ff;
268	if (cursor_image == DEAD_CHAR)
269	    cursor_image = prev_image & 0x00ff;
270	cursor_image |= *(scp->cursor_pos) & 0xff00;
271	scp->cursor_saveunder = cursor_image;
272	/* update the cursor bitmap if the char under the cursor has changed */
273	if (prev_image != cursor_image)
274	    set_destructive_cursor(scp);
275	/* modify cursor_image */
276	if (!(flags & BLINK_CURSOR)||((flags & BLINK_CURSOR)&&(blinkrate & 4))){
277	    /*
278	     * When the mouse pointer is at the same position as the cursor,
279	     * the cursor bitmap needs to be updated even if the char under
280	     * the cursor hasn't changed, because the mouse pionter may
281	     * have moved by a few dots within the cursor cel.
282	     */
283	    if ((prev_image == cursor_image)
284		    && (cursor_image != *(scp->cursor_pos)))
285	        set_destructive_cursor(scp);
286	    cursor_image &= 0xff00;
287	    cursor_image |= DEAD_CHAR;
288	}
289    }
290    else {
291	cursor_image = (*(ptr) & 0x00ff) | *(scp->cursor_pos) & 0xff00;
292	scp->cursor_saveunder = cursor_image;
293	if (!(flags & BLINK_CURSOR)||((flags & BLINK_CURSOR)&&(blinkrate & 4))){
294	    if ((cursor_image & 0x7000) == 0x7000) {
295		cursor_image &= 0x8fff;
296		if(!(cursor_image & 0x0700))
297		    cursor_image |= 0x0700;
298	    } else {
299		cursor_image |= 0x7000;
300		if ((cursor_image & 0x0700) == 0x0700)
301		    cursor_image &= 0xf0ff;
302	    }
303	}
304    }
305    *ptr = cursor_image;
306}
307
308static inline void
309remove_cursor_image(scr_stat *scp)
310{
311    *(Crtat + (scp->cursor_oldpos - scp->scr_buf)) = scp->cursor_saveunder;
312}
313
314static inline void
315move_crsr(scr_stat *scp, int x, int y)
316{
317    if (x < 0)
318	x = 0;
319    if (y < 0)
320	y = 0;
321    if (x >= scp->xsize)
322	x = scp->xsize-1;
323    if (y >= scp->ysize)
324	y = scp->ysize-1;
325    scp->xpos = x;
326    scp->ypos = y;
327    scp->cursor_pos = scp->scr_buf + scp->ypos * scp->xsize + scp->xpos;
328}
329
330static int
331scprobe(struct isa_device *dev)
332{
333    if (!scvidprobe(dev->id_unit, dev->id_flags)) {
334	if (bootverbose)
335	    printf("sc%d: no video adapter is found.\n", dev->id_unit);
336	return (0);
337    }
338
339    sc_port = dev->id_iobase;
340    if (sckbdprobe(dev->id_unit, dev->id_flags))
341	return (IO_KBDSIZE);
342    else
343        return ((dev->id_flags & DETECT_KBD) ? 0 : IO_KBDSIZE);
344}
345
346/* probe video adapters, return TRUE if found */
347static int
348scvidprobe(int unit, int flags)
349{
350    /*
351     * XXX don't try to `printf' anything here, the console may not have
352     * been configured yet.
353     */
354    u_short volatile *cp;
355    u_short was;
356    u_long  pa;
357    u_long  segoff;
358
359    /* do this test only once */
360    if (init_done != COLD)
361	return (Crtat != 0);
362
363    /*
364     * Finish defaulting crtc variables for a mono screen.  Crtat is a
365     * bogus common variable so that it can be shared with pcvt, so it
366     * can't be statically initialized.  XXX.
367     */
368    Crtat = (u_short *)MONO_BUF;
369    crtc_type = KD_MONO;
370    /* If CGA memory seems to work, switch to color.  */
371    cp = (u_short *)CGA_BUF;
372    was = *cp;
373    *cp = (u_short) 0xA55A;
374    if (*cp == 0xA55A) {
375	Crtat = (u_short *)CGA_BUF;
376	crtc_addr = COLOR_BASE;
377	crtc_type = KD_CGA;
378    } else {
379        cp = Crtat;
380	was = *cp;
381	*cp = (u_short) 0xA55A;
382	if (*cp != 0xA55A) {
383	    /* no screen at all, bail out */
384	    Crtat = 0;
385	    return FALSE;
386	}
387    }
388    *cp = was;
389
390    /*
391     * Check rtc and BIOS date area.
392     * XXX: don't use BIOSDATA_EQUIPMENT, it is not a dead copy
393     * of RTC_EQUIPMENT. The bit 4 and 5 of the ETC_EQUIPMENT are
394     * zeros for EGA and VGA. However, the EGA/VGA BIOS will set
395     * these bits in BIOSDATA_EQUIPMENT according to the monitor
396     * type detected.
397     */
398    switch ((rtcin(RTC_EQUIPMENT) >> 4) & 3) {	/* bit 4 and 5 */
399    case 0: /* EGA/VGA, or nothing */
400	crtc_type = KD_EGA;
401	/* the color adapter may be in the 40x25 mode... XXX */
402	break;
403    case 1: /* CGA 40x25 */
404	/* switch to the 80x25 mode? XXX */
405	/* FALL THROUGH */
406    case 2: /* CGA 80x25 */
407	/* `crtc_type' has already been set... */
408	/* crtc_type = KD_CGA; */
409	break;
410    case 3: /* MDA */
411	/* `crtc_type' has already been set... */
412	/* crtc_type = KD_MONO; */
413	break;
414    }
415
416    /* is this a VGA or higher ? */
417    outb(crtc_addr, 7);
418    if (inb(crtc_addr) == 7) {
419
420        crtc_type = KD_VGA;
421	crtc_vga = TRUE;
422	read_vgaregs(vgaregs);
423
424	/* Get the BIOS video mode pointer */
425	segoff = *(u_long *)pa_to_va(0x4a8);
426	pa = (((segoff & 0xffff0000) >> 12) + (segoff & 0xffff));
427	if (ISMAPPED(pa, sizeof(u_long))) {
428	    segoff = *(u_long *)pa_to_va(pa);
429	    pa = (((segoff & 0xffff0000) >> 12) + (segoff & 0xffff));
430	    if (ISMAPPED(pa, 64))
431		video_mode_ptr = (char *)pa_to_va(pa);
432	}
433    }
434
435    return TRUE;
436}
437
438/* probe the keyboard, return TRUE if found */
439static int
440sckbdprobe(int unit, int flags)
441{
442    int codeset;
443    int c = -1;
444    int m;
445
446    sc_kbdc = kbdc_open(sc_port);
447
448    if (!kbdc_lock(sc_kbdc, TRUE)) {
449	/* driver error? */
450	printf("sc%d: unable to lock the controller.\n", unit);
451        return ((flags & DETECT_KBD) ? FALSE : TRUE);
452    }
453
454    /* discard anything left after UserConfig */
455    empty_both_buffers(sc_kbdc, 10);
456
457    /* save the current keyboard controller command byte */
458    m = kbdc_get_device_mask(sc_kbdc) & ~KBD_KBD_CONTROL_BITS;
459    c = get_controller_command_byte(sc_kbdc);
460    if (c == -1) {
461	/* CONTROLLER ERROR */
462	printf("sc%d: unable to get the current command byte value.\n", unit);
463	goto fail;
464    }
465    if (bootverbose)
466	printf("sc%d: the current keyboard controller command byte %04x\n",
467	    unit, c);
468#if 0
469    /* override the keyboard lock switch */
470    c |= KBD_OVERRIDE_KBD_LOCK;
471#endif
472
473    /*
474     * The keyboard may have been screwed up by the boot block.
475     * We may just be able to recover from error by testing the controller
476     * and the keyboard port. The controller command byte needs to be saved
477     * before this recovery operation, as some controllers seem to set
478     * the command byte to particular values.
479     */
480    test_controller(sc_kbdc);
481    test_kbd_port(sc_kbdc);
482
483    /* enable the keyboard port, but disable the keyboard intr. */
484    if (!set_controller_command_byte(sc_kbdc,
485            KBD_KBD_CONTROL_BITS,
486            KBD_ENABLE_KBD_PORT | KBD_DISABLE_KBD_INT)) {
487	/* CONTROLLER ERROR
488	 * there is very little we can do...
489	 */
490	printf("sc%d: unable to set the command byte.\n", unit);
491	goto fail;
492     }
493
494     /*
495      * Check if we have an XT keyboard before we attempt to reset it.
496      * The procedure assumes that the keyboard and the controller have
497      * been set up properly by BIOS and have not been messed up
498      * during the boot process.
499      */
500     codeset = -1;
501     if (flags & XT_KEYBD)
502	 /* the user says there is a XT keyboard */
503	 codeset = 1;
504#ifdef DETECT_XT_KEYBOARD
505     else if ((c & KBD_TRANSLATION) == 0) {
506	 /* SET_SCANCODE_SET is not always supported; ignore error */
507	 if (send_kbd_command_and_data(sc_kbdc, KBDC_SET_SCANCODE_SET, 0)
508		 == KBD_ACK)
509	     codeset = read_kbd_data(sc_kbdc);
510     }
511     if (bootverbose)
512         printf("sc%d: keyboard scancode set %d\n", unit, codeset);
513#endif /* DETECT_XT_KEYBOARD */
514
515    if (flags & KBD_NORESET) {
516        write_kbd_command(sc_kbdc, KBDC_ECHO);
517        if (read_kbd_data(sc_kbdc) != KBD_ECHO) {
518            empty_both_buffers(sc_kbdc, 10);
519            test_controller(sc_kbdc);
520            test_kbd_port(sc_kbdc);
521            if (bootverbose)
522                printf("sc%d: failed to get response from the keyboard.\n",
523		    unit);
524	    goto fail;
525	}
526    } else {
527        /* reset keyboard hardware */
528        if (!reset_kbd(sc_kbdc)) {
529            /* KEYBOARD ERROR
530             * Keyboard reset may fail either because the keyboard doen't
531             * exist, or because the keyboard doesn't pass the self-test,
532             * or the keyboard controller on the motherboard and the keyboard
533             * somehow fail to shake hands. It is just possible, particularly
534             * in the last case, that the keyoard controller may be left
535             * in a hung state. test_controller() and test_kbd_port() appear
536             * to bring the keyboard controller back (I don't know why and
537             * how, though.)
538             */
539            empty_both_buffers(sc_kbdc, 10);
540            test_controller(sc_kbdc);
541            test_kbd_port(sc_kbdc);
542            /* We could disable the keyboard port and interrupt... but,
543             * the keyboard may still exist (see above).
544             */
545            if (bootverbose)
546                printf("sc%d: failed to reset the keyboard.\n", unit);
547            goto fail;
548        }
549    }
550
551    /*
552     * Allow us to set the XT_KEYBD flag in UserConfig so that keyboards
553     * such as those on the IBM ThinkPad laptop computers can be used
554     * with the standard console driver.
555     */
556    if (codeset == 1) {
557	if (send_kbd_command_and_data(
558	        sc_kbdc, KBDC_SET_SCANCODE_SET, codeset) == KBD_ACK) {
559	    /* XT kbd doesn't need scan code translation */
560	    c &= ~KBD_TRANSLATION;
561	} else {
562	    /* KEYBOARD ERROR
563	     * The XT kbd isn't usable unless the proper scan code set
564	     * is selected.
565	     */
566	    printf("sc%d: unable to set the XT keyboard mode.\n", unit);
567	    goto fail;
568	}
569    }
570    /* enable the keyboard port and intr. */
571    if (!set_controller_command_byte(sc_kbdc,
572            KBD_KBD_CONTROL_BITS | KBD_TRANSLATION | KBD_OVERRIDE_KBD_LOCK,
573	    (c & (KBD_TRANSLATION | KBD_OVERRIDE_KBD_LOCK))
574	        | KBD_ENABLE_KBD_PORT | KBD_ENABLE_KBD_INT)) {
575	/* CONTROLLER ERROR
576	 * This is serious; we are left with the disabled keyboard intr.
577	 */
578	printf("sc%d: unable to enable the keyboard port and intr.\n", unit);
579	goto fail;
580    }
581
582succeed:
583    kbdc_set_device_mask(sc_kbdc, m | KBD_KBD_CONTROL_BITS),
584    kbdc_lock(sc_kbdc, FALSE);
585    return TRUE;
586
587fail:
588    if (c != -1)
589        /* try to restore the command byte as before, if possible */
590        set_controller_command_byte(sc_kbdc, 0xff, c);
591    kbdc_set_device_mask(sc_kbdc,
592        (flags & DETECT_KBD) ? m : m | KBD_KBD_CONTROL_BITS);
593    kbdc_lock(sc_kbdc, FALSE);
594    return FALSE;
595}
596
597#if NAPM > 0
598static int
599scresume(void *dummy)
600{
601	shfts = ctls = alts = agrs = metas = 0;
602	return 0;
603}
604#endif
605
606static int
607scattach(struct isa_device *dev)
608{
609    scr_stat *scp;
610    dev_t cdev = makedev(CDEV_MAJOR, 0);
611#ifdef DEVFS
612    int vc;
613#endif
614
615    scinit();
616    flags = dev->id_flags;
617    if (!crtc_vga)
618	flags &= ~CHAR_CURSOR;
619
620    scp = console[0];
621
622    if (crtc_vga) {
623    	cut_buffer = (char *)malloc(scp->xsize*scp->ysize, M_DEVBUF, M_NOWAIT);
624    }
625
626    scp->scr_buf = (u_short *)malloc(scp->xsize*scp->ysize*sizeof(u_short),
627				     M_DEVBUF, M_NOWAIT);
628
629    /* copy temporary buffer to final buffer */
630    bcopy(sc_buffer, scp->scr_buf, scp->xsize * scp->ysize * sizeof(u_short));
631
632    scp->cursor_pos = scp->cursor_oldpos =
633	scp->scr_buf + scp->xpos + scp->ypos * scp->xsize;
634    scp->mouse_pos = scp->mouse_oldpos =
635	scp->scr_buf + ((scp->mouse_ypos/scp->font_size)*scp->xsize +
636	    		scp->mouse_xpos/8);
637
638    /* initialize history buffer & pointers */
639    scp->history_head = scp->history_pos = scp->history =
640	(u_short *)malloc(scp->history_size*sizeof(u_short),
641			  M_DEVBUF, M_NOWAIT);
642    bzero(scp->history_head, scp->history_size*sizeof(u_short));
643
644    /* initialize cursor stuff */
645    if (!(scp->status & UNKNOWN_MODE))
646    	draw_cursor_image(scp);
647
648    /* get screen update going */
649    scrn_timer(NULL);
650
651    update_leds(scp->status);
652
653    if (bootverbose) {
654        printf("sc%d: BIOS video mode:%d\n",
655	    dev->id_unit, *(u_char *)pa_to_va(0x449));
656        printf("sc%d: VGA registers upon power-up\n", dev->id_unit);
657        dump_vgaregs(vgaregs);
658        printf("sc%d: video mode:%d\n", dev->id_unit, scp->mode);
659        if (video_mode_ptr != NULL) {
660            printf("sc%d: VGA registers for mode:%d\n",
661		dev->id_unit, scp->mode);
662            dump_vgaregs(video_mode_ptr + (64*scp->mode));
663        }
664    }
665
666    printf("sc%d: ", dev->id_unit);
667    switch(crtc_type) {
668    case KD_VGA:
669	if (crtc_addr == MONO_BASE)
670	    printf("VGA mono");
671	else
672	    printf("VGA color");
673	break;
674    case KD_EGA:
675	if (crtc_addr == MONO_BASE)
676	    printf("EGA mono");
677	else
678	    printf("EGA color");
679	break;
680    case KD_CGA:
681	printf("CGA");
682	break;
683    case KD_MONO:
684    case KD_HERCULES:
685    default:
686	printf("MDA/hercules");
687	break;
688    }
689    printf(" <%d virtual consoles, flags=0x%x>\n", MAXCONS, flags);
690
691#if NAPM > 0
692    scp->r_hook.ah_fun = scresume;
693    scp->r_hook.ah_arg = NULL;
694    scp->r_hook.ah_name = "system keyboard";
695    scp->r_hook.ah_order = APM_MID_ORDER;
696    apm_hook_establish(APM_HOOK_RESUME , &scp->r_hook);
697#endif
698
699    cdevsw_add(&cdev, &scdevsw, NULL);
700
701#ifdef DEVFS
702    for (vc = 0; vc < MAXCONS; vc++)
703        sc_devfs_token[vc] = devfs_add_devswf(&scdevsw, vc, DV_CHR, UID_ROOT,
704					      GID_WHEEL, 0600, "ttyv%n", vc);
705#endif
706    return 0;
707}
708
709struct tty
710*scdevtotty(dev_t dev)
711{
712    int unit = minor(dev);
713
714    if (init_done == COLD)
715	return(NULL);
716    if (unit == SC_CONSOLE)
717	return CONSOLE_TTY;
718    if (unit == SC_MOUSE)
719	return MOUSE_TTY;
720    if (unit >= MAXCONS || unit < 0)
721	return(NULL);
722    return VIRTUAL_TTY(unit);
723}
724
725int
726scopen(dev_t dev, int flag, int mode, struct proc *p)
727{
728    struct tty *tp = scdevtotty(dev);
729
730    if (!tp)
731	return(ENXIO);
732
733    tp->t_oproc = (minor(dev) == SC_MOUSE) ? scmousestart : scstart;
734    tp->t_param = scparam;
735    tp->t_dev = dev;
736    if (!(tp->t_state & TS_ISOPEN)) {
737	ttychars(tp);
738        /* Use the current setting of the <-- key as default VERASE. */
739        /* If the Delete key is preferable, an stty is necessary     */
740        tp->t_cc[VERASE] = key_map.key[0x0e].map[0];
741	tp->t_iflag = TTYDEF_IFLAG;
742	tp->t_oflag = TTYDEF_OFLAG;
743	tp->t_cflag = TTYDEF_CFLAG;
744	tp->t_lflag = TTYDEF_LFLAG;
745	tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
746	scparam(tp, &tp->t_termios);
747	ttsetwater(tp);
748	(*linesw[tp->t_line].l_modem)(tp, 1);
749    }
750    else
751	if (tp->t_state & TS_XCLUDE && p->p_ucred->cr_uid != 0)
752	    return(EBUSY);
753    if (minor(dev) < MAXCONS && !console[minor(dev)]) {
754	console[minor(dev)] = alloc_scp();
755    }
756    if (minor(dev)<MAXCONS && !tp->t_winsize.ws_col && !tp->t_winsize.ws_row) {
757	tp->t_winsize.ws_col = console[minor(dev)]->xsize;
758	tp->t_winsize.ws_row = console[minor(dev)]->ysize;
759    }
760    return ((*linesw[tp->t_line].l_open)(dev, tp));
761}
762
763int
764scclose(dev_t dev, int flag, int mode, struct proc *p)
765{
766    struct tty *tp = scdevtotty(dev);
767    struct scr_stat *scp;
768
769    if (!tp)
770	return(ENXIO);
771    if (minor(dev) < MAXCONS) {
772	scp = get_scr_stat(tp->t_dev);
773	if (scp->status & SWITCH_WAIT_ACQ)
774	    wakeup((caddr_t)&scp->smode);
775#if not_yet_done
776	if (scp == &main_console) {
777	    scp->pid = 0;
778	    scp->proc = NULL;
779	    scp->smode.mode = VT_AUTO;
780	}
781	else {
782	    free(scp->scr_buf, M_DEVBUF);
783	    if (scp->history != NULL)
784		free(scp->history, M_DEVBUF);
785	    free(scp, M_DEVBUF);
786	    console[minor(dev)] = NULL;
787	}
788#else
789	scp->pid = 0;
790	scp->proc = NULL;
791	scp->smode.mode = VT_AUTO;
792#endif
793    }
794    spltty();
795    (*linesw[tp->t_line].l_close)(tp, flag);
796    ttyclose(tp);
797    spl0();
798    return(0);
799}
800
801int
802scread(dev_t dev, struct uio *uio, int flag)
803{
804    struct tty *tp = scdevtotty(dev);
805
806    if (!tp)
807	return(ENXIO);
808    return((*linesw[tp->t_line].l_read)(tp, uio, flag));
809}
810
811int
812scwrite(dev_t dev, struct uio *uio, int flag)
813{
814    struct tty *tp = scdevtotty(dev);
815
816    if (!tp)
817	return(ENXIO);
818    return((*linesw[tp->t_line].l_write)(tp, uio, flag));
819}
820
821void
822scintr(int unit)
823{
824    static struct tty *cur_tty;
825    int c, len;
826    u_char *cp;
827
828    /* make screensaver happy */
829    scrn_time_stamp = mono_time.tv_sec;
830
831    /*
832     * Loop while there is still input to get from the keyboard.
833     * I don't think this is nessesary, and it doesn't fix
834     * the Xaccel-2.1 keyboard hang, but it can't hurt.		XXX
835     */
836    while ((c = scgetc(SCGETC_NONBLOCK)) != NOKEY) {
837
838	cur_tty = VIRTUAL_TTY(get_scr_num());
839	if (!(cur_tty->t_state & TS_ISOPEN))
840	    if (!((cur_tty = CONSOLE_TTY)->t_state & TS_ISOPEN))
841		continue;
842
843	switch (c & 0xff00) {
844	case 0x0000: /* normal key */
845	    (*linesw[cur_tty->t_line].l_rint)(c & 0xFF, cur_tty);
846	    break;
847	case FKEY:  /* function key, return string */
848	    if (cp = get_fstr((u_int)c, (u_int *)&len)) {
849	    	while (len-- >  0)
850		    (*linesw[cur_tty->t_line].l_rint)(*cp++ & 0xFF, cur_tty);
851	    }
852	    break;
853	case MKEY:  /* meta is active, prepend ESC */
854	    (*linesw[cur_tty->t_line].l_rint)(0x1b, cur_tty);
855	    (*linesw[cur_tty->t_line].l_rint)(c & 0xFF, cur_tty);
856	    break;
857	case BKEY:  /* backtab fixed sequence (esc [ Z) */
858	    (*linesw[cur_tty->t_line].l_rint)(0x1b, cur_tty);
859	    (*linesw[cur_tty->t_line].l_rint)('[', cur_tty);
860	    (*linesw[cur_tty->t_line].l_rint)('Z', cur_tty);
861	    break;
862	}
863    }
864
865    if (cur_console->status & MOUSE_ENABLED) {
866	cur_console->status &= ~MOUSE_VISIBLE;
867	remove_mouse_image(cur_console);
868    }
869}
870
871static int
872scparam(struct tty *tp, struct termios *t)
873{
874    tp->t_ispeed = t->c_ispeed;
875    tp->t_ospeed = t->c_ospeed;
876    tp->t_cflag = t->c_cflag;
877    return 0;
878}
879
880int
881scioctl(dev_t dev, int cmd, caddr_t data, int flag, struct proc *p)
882{
883    int error;
884    u_int i;
885    struct tty *tp;
886    scr_stat *scp;
887
888    tp = scdevtotty(dev);
889    if (!tp)
890	return ENXIO;
891    scp = get_scr_stat(tp->t_dev);
892
893    /* If there is a user_ioctl function call that first */
894    if (sc_user_ioctl) {
895	if (error = (*sc_user_ioctl)(dev, cmd, data, flag, p))
896	    return error;
897    }
898
899    switch (cmd) {  		/* process console hardware related ioctl's */
900
901    case GIO_ATTR:      	/* get current attributes */
902	*(int*)data = (scp->term.cur_attr >> 8) & 0xFF;
903	return 0;
904
905    case GIO_COLOR:     	/* is this a color console ? */
906	if (crtc_addr == COLOR_BASE)
907	    *(int*)data = 1;
908	else
909	    *(int*)data = 0;
910	return 0;
911
912    case CONS_CURRENT:  	/* get current adapter type */
913	*(int *)data = crtc_type;
914	return 0;
915
916    case CONS_GET:      	/* get current video mode */
917	*(int*)data = scp->mode;
918	return 0;
919
920    case CONS_BLANKTIME:    	/* set screen saver timeout (0 = no saver) */
921	if (*(int *)data < 0)
922            return EINVAL;
923	scrn_blank_time = *(int *)data;
924	if (scrn_blank_time == 0)
925	    scrn_time_stamp = mono_time.tv_sec;
926	return 0;
927
928    case CONS_CURSORTYPE:   	/* set cursor type blink/noblink */
929	if ((*(int*)data) & 0x01)
930	    flags |= BLINK_CURSOR;
931	else
932	    flags &= ~BLINK_CURSOR;
933	if ((*(int*)data) & 0x02) {
934	    if (!crtc_vga)
935		return ENXIO;
936	    flags |= CHAR_CURSOR;
937	} else
938	    flags &= ~CHAR_CURSOR;
939	/*
940	 * The cursor shape is global property; all virtual consoles
941	 * are affected. Update the cursor in the current console...
942	 */
943	if (!(cur_console->status & UNKNOWN_MODE)) {
944            remove_cursor_image(cur_console);
945	    if (flags & CHAR_CURSOR)
946	        set_destructive_cursor(cur_console);
947	    draw_cursor_image(cur_console);
948	}
949	return 0;
950
951    case CONS_BELLTYPE: 	/* set bell type sound/visual */
952	if (*data)
953	    flags |= VISUAL_BELL;
954	else
955	    flags &= ~VISUAL_BELL;
956	return 0;
957
958    case CONS_HISTORY:  	/* set history size */
959	if (*data) {
960            if (cur_console->status & BUFFER_SAVED)
961                return EBUSY;
962	    if (scp->history != NULL)
963		free(scp->history, M_DEVBUF);
964	    scp->history_size = max(scp->ysize, *(int *)data)*scp->xsize;
965	    scp->history_head = scp->history_pos = scp->history =
966		(u_short *)malloc(scp->history_size*sizeof(u_short),
967				  M_DEVBUF, M_WAITOK);
968	    bzero(scp->history_head, scp->history_size*sizeof(u_short));
969	    return 0;
970	}
971	else
972	    return EINVAL;
973
974    case CONS_MOUSECTL:		/* control mouse arrow */
975    {
976	mouse_info_t *mouse = (mouse_info_t*)data;
977
978	if (!crtc_vga)
979	    return ENXIO;
980
981	switch (mouse->operation) {
982	case MOUSE_MODE:
983	    if (ISSIGVALID(mouse->u.mode.signal)) {
984		scp->mouse_signal = mouse->u.mode.signal;
985		scp->mouse_proc = p;
986		scp->mouse_pid = p->p_pid;
987	    }
988	    else {
989		scp->mouse_signal = 0;
990		scp->mouse_proc = NULL;
991		scp->mouse_pid = 0;
992	    }
993	    break;
994
995	case MOUSE_SHOW:
996	    if (!(scp->status & MOUSE_ENABLED)) {
997		scp->status |= (MOUSE_ENABLED | MOUSE_VISIBLE);
998		scp->mouse_oldpos = scp->mouse_pos;
999		mark_all(scp);
1000	    }
1001	    else
1002		return EINVAL;
1003	    break;
1004
1005	case MOUSE_HIDE:
1006	    if (scp->status & MOUSE_ENABLED) {
1007		scp->status &= ~(MOUSE_ENABLED | MOUSE_VISIBLE);
1008		mark_all(scp);
1009	    }
1010	    else
1011		return EINVAL;
1012	    break;
1013
1014	case MOUSE_MOVEABS:
1015	    scp->mouse_xpos = mouse->u.data.x;
1016	    scp->mouse_ypos = mouse->u.data.y;
1017	    set_mouse_pos(scp);
1018	    break;
1019
1020	case MOUSE_MOVEREL:
1021	    scp->mouse_xpos += mouse->u.data.x;
1022	    scp->mouse_ypos += mouse->u.data.y;
1023	    set_mouse_pos(scp);
1024	    break;
1025
1026	case MOUSE_GETINFO:
1027	    mouse->u.data.x = scp->mouse_xpos;
1028	    mouse->u.data.y = scp->mouse_ypos;
1029	    mouse->u.data.buttons = scp->mouse_buttons;
1030	    break;
1031
1032	case MOUSE_ACTION:
1033	    /* this should maybe only be settable from /dev/consolectl SOS */
1034	    /* send out mouse event on /dev/sysmouse */
1035	    if (cur_console->status & MOUSE_ENABLED)
1036	    	cur_console->status |= MOUSE_VISIBLE;
1037	    if ((MOUSE_TTY)->t_state & TS_ISOPEN) {
1038		u_char buf[5];
1039		int i;
1040
1041		buf[0] = 0x80 | ((~mouse->u.data.buttons) & 0x07);
1042		buf[1] = (mouse->u.data.x & 0x1fe >> 1);
1043		buf[3] = (mouse->u.data.x & 0x1ff) - buf[1];
1044		buf[2] = -(mouse->u.data.y & 0x1fe >> 1);
1045		buf[4] = -(mouse->u.data.y & 0x1ff) - buf[2];
1046		for (i=0; i<5; i++)
1047	    		(*linesw[(MOUSE_TTY)->t_line].l_rint)(buf[i],MOUSE_TTY);
1048	    }
1049	    if (cur_console->mouse_signal) {
1050		cur_console->mouse_buttons = mouse->u.data.buttons;
1051    		/* has controlling process died? */
1052		if (cur_console->mouse_proc &&
1053		    (cur_console->mouse_proc != pfind(cur_console->mouse_pid))){
1054		    	cur_console->mouse_signal = 0;
1055			cur_console->mouse_proc = NULL;
1056			cur_console->mouse_pid = 0;
1057		}
1058		else
1059		    psignal(cur_console->mouse_proc, cur_console->mouse_signal);
1060	    }
1061	    else {
1062		/* process button presses */
1063		if (cur_console->mouse_buttons != mouse->u.data.buttons) {
1064		    cur_console->mouse_buttons = mouse->u.data.buttons;
1065		    if (!(cur_console->status & UNKNOWN_MODE)) {
1066			if (cur_console->mouse_buttons & LEFT_BUTTON)
1067			    mouse_cut_start(cur_console);
1068			else
1069			    mouse_cut_end(cur_console);
1070			if (cur_console->mouse_buttons & RIGHT_BUTTON ||
1071			    cur_console->mouse_buttons & MIDDLE_BUTTON)
1072			    mouse_paste(cur_console);
1073		    }
1074		}
1075	    }
1076	    if (mouse->u.data.x != 0 || mouse->u.data.y != 0) {
1077	    	cur_console->mouse_xpos += mouse->u.data.x;
1078	    	cur_console->mouse_ypos += mouse->u.data.y;
1079		set_mouse_pos(cur_console);
1080	    }
1081	    break;
1082
1083	default:
1084	    return EINVAL;
1085	}
1086	/* make screensaver happy */
1087	scrn_time_stamp = mono_time.tv_sec;
1088	return 0;
1089    }
1090
1091    case CONS_GETINFO:  	/* get current (virtual) console info */
1092    {
1093	vid_info_t *ptr = (vid_info_t*)data;
1094	if (ptr->size == sizeof(struct vid_info)) {
1095	    ptr->m_num = get_scr_num();
1096	    ptr->mv_col = scp->xpos;
1097	    ptr->mv_row = scp->ypos;
1098	    ptr->mv_csz = scp->xsize;
1099	    ptr->mv_rsz = scp->ysize;
1100	    ptr->mv_norm.fore = (scp->term.std_color & 0x0f00)>>8;
1101	    ptr->mv_norm.back = (scp->term.std_color & 0xf000)>>12;
1102	    ptr->mv_rev.fore = (scp->term.rev_color & 0x0f00)>>8;
1103	    ptr->mv_rev.back = (scp->term.rev_color & 0xf000)>>12;
1104	    ptr->mv_grfc.fore = 0;      /* not supported */
1105	    ptr->mv_grfc.back = 0;      /* not supported */
1106	    ptr->mv_ovscan = scp->border;
1107	    ptr->mk_keylock = scp->status & LOCK_KEY_MASK;
1108	    return 0;
1109	}
1110	return EINVAL;
1111    }
1112
1113    case CONS_GETVERS:  	/* get version number */
1114	*(int*)data = 0x200;    /* version 2.0 */
1115	return 0;
1116
1117    /* VGA TEXT MODES */
1118    case SW_VGA_C40x25:
1119    case SW_VGA_C80x25: case SW_VGA_M80x25:
1120    case SW_VGA_C80x30: case SW_VGA_M80x30:
1121    case SW_VGA_C80x50: case SW_VGA_M80x50:
1122    case SW_VGA_C80x60: case SW_VGA_M80x60:
1123    case SW_B40x25:     case SW_C40x25:
1124    case SW_B80x25:     case SW_C80x25:
1125    case SW_ENH_B40x25: case SW_ENH_C40x25:
1126    case SW_ENH_B80x25: case SW_ENH_C80x25:
1127    case SW_ENH_B80x43: case SW_ENH_C80x43:
1128    case SW_EGAMONO80x25:
1129
1130	if (!crtc_vga || video_mode_ptr == NULL)
1131	    return ENXIO;
1132	switch (cmd & 0xff) {
1133	case M_VGA_C80x60: case M_VGA_M80x60:
1134	    if (!(fonts_loaded & FONT_8))
1135		return EINVAL;
1136	    scp->xsize = 80;
1137	    scp->ysize = 60;
1138	    break;
1139	case M_VGA_C80x50: case M_VGA_M80x50:
1140	    if (!(fonts_loaded & FONT_8))
1141		return EINVAL;
1142	    scp->xsize = 80;
1143	    scp->ysize = 50;
1144	    break;
1145	case M_ENH_B80x43: case M_ENH_C80x43:
1146	    if (!(fonts_loaded & FONT_8))
1147		return EINVAL;
1148	    scp->xsize = 80;
1149	    scp->ysize = 43;
1150	    break;
1151	case M_VGA_C80x30: case M_VGA_M80x30:
1152	    scp->xsize = 80;
1153	    scp->ysize = 30;
1154	    break;
1155	case M_ENH_C40x25: case M_ENH_B40x25:
1156	case M_ENH_C80x25: case M_ENH_B80x25:
1157	case M_EGAMONO80x25:
1158	    if (!(fonts_loaded & FONT_14))
1159		return EINVAL;
1160	    /* FALL THROUGH */
1161	default:
1162	    if ((cmd & 0xff) > M_VGA_CG320)
1163		return EINVAL;
1164	    else
1165		scp->xsize = *(video_mode_ptr+((cmd&0xff)*64));
1166		scp->ysize = *(video_mode_ptr+((cmd&0xff)*64)+1)+1;
1167	    break;
1168	}
1169	scp->mode = cmd & 0xff;
1170	free(scp->scr_buf, M_DEVBUF);
1171	scp->scr_buf = (u_short *)
1172	    malloc(scp->xsize*scp->ysize*sizeof(u_short), M_DEVBUF, M_WAITOK);
1173    	scp->cursor_pos = scp->cursor_oldpos =
1174	    scp->scr_buf + scp->xpos + scp->ypos * scp->xsize;
1175    	scp->mouse_pos = scp->mouse_oldpos =
1176	    scp->scr_buf + ((scp->mouse_ypos/scp->font_size)*scp->xsize +
1177	    scp->mouse_xpos/8);
1178	free(cut_buffer, M_DEVBUF);
1179    	cut_buffer = (char *)malloc(scp->xsize*scp->ysize, M_DEVBUF, M_NOWAIT);
1180	cut_buffer[0] = 0x00;
1181	if (scp->history != NULL)
1182	    free(scp->history, M_DEVBUF);
1183	scp->history_size = max(HISTORY_SIZE, scp->xsize*scp->ysize);
1184	scp->history_head = scp->history_pos = scp->history = (u_short *)
1185	    malloc(scp->history_size*sizeof(u_short), M_DEVBUF, M_NOWAIT);
1186	if (scp->history != NULL)
1187	    bzero(scp->history, scp->history_size*sizeof(u_short));
1188	if (scp == cur_console)
1189	    set_mode(scp);
1190	scp->status &= ~UNKNOWN_MODE;
1191	clear_screen(scp);
1192	if (tp->t_winsize.ws_col != scp->xsize
1193	    || tp->t_winsize.ws_row != scp->ysize) {
1194	    tp->t_winsize.ws_col = scp->xsize;
1195	    tp->t_winsize.ws_row = scp->ysize;
1196	    pgsignal(tp->t_pgrp, SIGWINCH, 1);
1197	}
1198	return 0;
1199
1200    /* GRAPHICS MODES */
1201    case SW_BG320:     case SW_BG640:
1202    case SW_CG320:     case SW_CG320_D:   case SW_CG640_E:
1203    case SW_CG640x350: case SW_ENH_CG640:
1204    case SW_BG640x480: case SW_CG640x480: case SW_VGA_CG320:
1205
1206	if (!crtc_vga || video_mode_ptr == NULL)
1207	    return ENXIO;
1208	scp->mode = cmd & 0xFF;
1209	scp->xpixel = (*(video_mode_ptr + (scp->mode*64))) * 8;
1210	scp->ypixel = (*(video_mode_ptr + (scp->mode*64) + 1) + 1) *
1211		     (*(video_mode_ptr + (scp->mode*64) + 2));
1212	if (scp == cur_console)
1213	    set_mode(scp);
1214	scp->status |= UNKNOWN_MODE;    /* graphics mode */
1215	/* clear_graphics();*/
1216
1217	if (tp->t_winsize.ws_xpixel != scp->xpixel
1218	    || tp->t_winsize.ws_ypixel != scp->ypixel) {
1219	    tp->t_winsize.ws_xpixel = scp->xpixel;
1220	    tp->t_winsize.ws_ypixel = scp->ypixel;
1221	    pgsignal(tp->t_pgrp, SIGWINCH, 1);
1222	}
1223	return 0;
1224
1225    case SW_VGA_MODEX:
1226	if (!crtc_vga || video_mode_ptr == NULL)
1227	    return ENXIO;
1228	scp->mode = cmd & 0xFF;
1229	if (scp == cur_console)
1230	    set_mode(scp);
1231	scp->status |= UNKNOWN_MODE;    /* graphics mode */
1232	/* clear_graphics();*/
1233	scp->xpixel = 320;
1234	scp->ypixel = 240;
1235	if (tp->t_winsize.ws_xpixel != scp->xpixel
1236	    || tp->t_winsize.ws_ypixel != scp->ypixel) {
1237	    tp->t_winsize.ws_xpixel = scp->xpixel;
1238	    tp->t_winsize.ws_ypixel = scp->ypixel;
1239	    pgsignal(tp->t_pgrp, SIGWINCH, 1);
1240	}
1241	return 0;
1242
1243    case VT_SETMODE:    	/* set screen switcher mode */
1244    {
1245	struct vt_mode *mode;
1246
1247	mode = (struct vt_mode *)data;
1248	if (ISSIGVALID(mode->relsig) && ISSIGVALID(mode->acqsig) &&
1249	    ISSIGVALID(mode->frsig)) {
1250	    bcopy(data, &scp->smode, sizeof(struct vt_mode));
1251	    if (scp->smode.mode == VT_PROCESS) {
1252		scp->proc = p;
1253		scp->pid = scp->proc->p_pid;
1254	    }
1255	    return 0;
1256	} else
1257	    return EINVAL;
1258    }
1259
1260    case VT_GETMODE:    	/* get screen switcher mode */
1261	bcopy(&scp->smode, data, sizeof(struct vt_mode));
1262	return 0;
1263
1264    case VT_RELDISP:    	/* screen switcher ioctl */
1265	switch(*data) {
1266	case VT_FALSE:  	/* user refuses to release screen, abort */
1267	    if (scp == old_scp && (scp->status & SWITCH_WAIT_REL)) {
1268		old_scp->status &= ~SWITCH_WAIT_REL;
1269		switch_in_progress = FALSE;
1270		return 0;
1271	    }
1272	    return EINVAL;
1273
1274	case VT_TRUE:   	/* user has released screen, go on */
1275	    if (scp == old_scp && (scp->status & SWITCH_WAIT_REL)) {
1276		scp->status &= ~SWITCH_WAIT_REL;
1277		exchange_scr();
1278		if (new_scp->smode.mode == VT_PROCESS) {
1279		    new_scp->status |= SWITCH_WAIT_ACQ;
1280		    psignal(new_scp->proc, new_scp->smode.acqsig);
1281		}
1282		else
1283		    switch_in_progress = FALSE;
1284		return 0;
1285	    }
1286	    return EINVAL;
1287
1288	case VT_ACKACQ: 	/* acquire acknowledged, switch completed */
1289	    if (scp == new_scp && (scp->status & SWITCH_WAIT_ACQ)) {
1290		scp->status &= ~SWITCH_WAIT_ACQ;
1291		switch_in_progress = FALSE;
1292		return 0;
1293	    }
1294	    return EINVAL;
1295
1296	default:
1297	    return EINVAL;
1298	}
1299	/* NOT REACHED */
1300
1301    case VT_OPENQRY:    	/* return free virtual console */
1302	for (i = 0; i < MAXCONS; i++) {
1303	    tp = VIRTUAL_TTY(i);
1304	    if (!(tp->t_state & TS_ISOPEN)) {
1305		*data = i + 1;
1306		return 0;
1307	    }
1308	}
1309	return EINVAL;
1310
1311    case VT_ACTIVATE:   	/* switch to screen *data */
1312	return switch_scr(scp, (*data) - 1);
1313
1314    case VT_WAITACTIVE: 	/* wait for switch to occur */
1315	if (*data > MAXCONS || *data < 0)
1316	    return EINVAL;
1317	if (minor(dev) == (*data) - 1)
1318	    return 0;
1319	if (*data == 0) {
1320	    if (scp == cur_console)
1321		return 0;
1322	}
1323	else
1324	    scp = console[(*data) - 1];
1325	while ((error=tsleep((caddr_t)&scp->smode, PZERO|PCATCH,
1326			     "waitvt", 0)) == ERESTART) ;
1327	return error;
1328
1329    case VT_GETACTIVE:
1330	*data = get_scr_num()+1;
1331	return 0;
1332
1333    case KDENABIO:      	/* allow io operations */
1334	error = suser(p->p_ucred, &p->p_acflag);
1335	if (error != 0)
1336	    return error;
1337	if (securelevel > 0)
1338	    return EPERM;
1339	p->p_md.md_regs->tf_eflags |= PSL_IOPL;
1340	return 0;
1341
1342    case KDDISABIO:     	/* disallow io operations (default) */
1343	p->p_md.md_regs->tf_eflags &= ~PSL_IOPL;
1344	return 0;
1345
1346    case KDSETMODE:     	/* set current mode of this (virtual) console */
1347	switch (*data) {
1348	case KD_TEXT:   	/* switch to TEXT (known) mode */
1349	    /* restore fonts & palette ! */
1350	    if (crtc_vga) {
1351		if (fonts_loaded & FONT_8)
1352		    copy_font(LOAD, FONT_8, font_8);
1353		if (fonts_loaded & FONT_14)
1354		    copy_font(LOAD, FONT_14, font_14);
1355		if (fonts_loaded & FONT_16)
1356		    copy_font(LOAD, FONT_16, font_16);
1357		load_palette(palette);
1358	    }
1359	    /* FALL THROUGH */
1360
1361	case KD_TEXT1:  	/* switch to TEXT (known) mode */
1362	    /* no restore fonts & palette */
1363	    if (crtc_vga && video_mode_ptr)
1364		set_mode(scp);
1365	    scp->status &= ~UNKNOWN_MODE;
1366	    clear_screen(scp);
1367	    return 0;
1368
1369	case KD_GRAPHICS:	/* switch to GRAPHICS (unknown) mode */
1370	    scp->status |= UNKNOWN_MODE;
1371	    return 0;
1372	default:
1373	    return EINVAL;
1374	}
1375	/* NOT REACHED */
1376
1377    case KDGETMODE:     	/* get current mode of this (virtual) console */
1378	*data = (scp->status & UNKNOWN_MODE) ? KD_GRAPHICS : KD_TEXT;
1379	return 0;
1380
1381    case KDSBORDER:     	/* set border color of this (virtual) console */
1382	scp->border = *data;
1383	if (scp == cur_console)
1384	    set_border(scp->border);
1385	return 0;
1386
1387    case KDSKBSTATE:    	/* set keyboard state (locks) */
1388	if (*data >= 0 && *data <= LOCK_KEY_MASK) {
1389	    scp->status &= ~LOCK_KEY_MASK;
1390	    scp->status |= *data;
1391	    if (scp == cur_console)
1392		update_leds(scp->status);
1393	    return 0;
1394	}
1395	return EINVAL;
1396
1397    case KDGKBSTATE:    	/* get keyboard state (locks) */
1398	*data = scp->status & LOCK_KEY_MASK;
1399	return 0;
1400
1401    case KDSETRAD:      	/* set keyboard repeat & delay rates */
1402	if (*data & 0x80)
1403	    return EINVAL;
1404	if (sc_kbdc != NULL)
1405	    set_keyboard(KBDC_SET_TYPEMATIC, *data);
1406	return 0;
1407
1408    case KDSKBMODE:     	/* set keyboard mode */
1409	switch (*data) {
1410	case K_RAW: 		/* switch to RAW scancode mode */
1411	    scp->status |= KBD_RAW_MODE;
1412	    return 0;
1413
1414	case K_XLATE:   	/* switch to XLT ascii mode */
1415	    if (scp == cur_console && scp->status & KBD_RAW_MODE)
1416		shfts = ctls = alts = agrs = metas = 0;
1417	    scp->status &= ~KBD_RAW_MODE;
1418	    return 0;
1419	default:
1420	    return EINVAL;
1421	}
1422	/* NOT REACHED */
1423
1424    case KDGKBMODE:     	/* get keyboard mode */
1425	*data = (scp->status & KBD_RAW_MODE) ? K_RAW : K_XLATE;
1426	return 0;
1427
1428    case KDMKTONE:      	/* sound the bell */
1429	if (*(int*)data)
1430	    do_bell(scp, (*(int*)data)&0xffff,
1431		    (((*(int*)data)>>16)&0xffff)*hz/1000);
1432	else
1433	    do_bell(scp, scp->bell_pitch, scp->bell_duration);
1434	return 0;
1435
1436    case KIOCSOUND:     	/* make tone (*data) hz */
1437	if (scp == cur_console) {
1438	    if (*(int*)data) {
1439		int pitch = timer_freq / *(int*)data;
1440
1441		/* set command for counter 2, 2 byte write */
1442		if (acquire_timer2(TIMER_16BIT|TIMER_SQWAVE))
1443		    return EBUSY;
1444
1445		/* set pitch */
1446		outb(TIMER_CNTR2, pitch);
1447		outb(TIMER_CNTR2, (pitch>>8));
1448
1449		/* enable counter 2 output to speaker */
1450		outb(IO_PPI, inb(IO_PPI) | 3);
1451	    }
1452	    else {
1453		/* disable counter 2 output to speaker */
1454		outb(IO_PPI, inb(IO_PPI) & 0xFC);
1455		release_timer2();
1456	    }
1457	}
1458	return 0;
1459
1460    case KDGKBTYPE:     	/* get keyboard type */
1461	*data = 0;  		/* type not known (yet) */
1462	return 0;
1463
1464    case KDSETLED:      	/* set keyboard LED status */
1465	if (*data >= 0 && *data <= LED_MASK) {
1466	    scp->status &= ~LED_MASK;
1467	    scp->status |= *data;
1468	    if (scp == cur_console)
1469		update_leds(scp->status);
1470	    return 0;
1471	}
1472	return EINVAL;
1473
1474    case KDGETLED:      	/* get keyboard LED status */
1475	*data = scp->status & LED_MASK;
1476	return 0;
1477
1478    case GETFKEY:       	/* get functionkey string */
1479	if (*(u_short*)data < n_fkey_tab) {
1480	    fkeyarg_t *ptr = (fkeyarg_t*)data;
1481	    bcopy(&fkey_tab[ptr->keynum].str, ptr->keydef,
1482		  fkey_tab[ptr->keynum].len);
1483	    ptr->flen = fkey_tab[ptr->keynum].len;
1484	    return 0;
1485	}
1486	else
1487	    return EINVAL;
1488
1489    case SETFKEY:       	/* set functionkey string */
1490	if (*(u_short*)data < n_fkey_tab) {
1491	    fkeyarg_t *ptr = (fkeyarg_t*)data;
1492	    bcopy(ptr->keydef, &fkey_tab[ptr->keynum].str,
1493		  min(ptr->flen, MAXFK));
1494	    fkey_tab[ptr->keynum].len = min(ptr->flen, MAXFK);
1495	    return 0;
1496	}
1497	else
1498	    return EINVAL;
1499
1500    case GIO_SCRNMAP:   	/* get output translation table */
1501	bcopy(&scr_map, data, sizeof(scr_map));
1502	return 0;
1503
1504    case PIO_SCRNMAP:   	/* set output translation table */
1505	bcopy(data, &scr_map, sizeof(scr_map));
1506	for (i=0; i<sizeof(scr_map); i++)
1507	    scr_rmap[scr_map[i]] = i;
1508	return 0;
1509
1510    case GIO_KEYMAP:    	/* get keyboard translation table */
1511	bcopy(&key_map, data, sizeof(key_map));
1512	return 0;
1513
1514    case PIO_KEYMAP:    	/* set keyboard translation table */
1515	bcopy(data, &key_map, sizeof(key_map));
1516	return 0;
1517
1518    case PIO_FONT8x8:   	/* set 8x8 dot font */
1519	if (!crtc_vga)
1520	    return ENXIO;
1521	bcopy(data, font_8, 8*256);
1522	fonts_loaded |= FONT_8;
1523	if (!(cur_console->status & UNKNOWN_MODE)) {
1524	    copy_font(LOAD, FONT_8, font_8);
1525	    if (flags & CHAR_CURSOR)
1526	        set_destructive_cursor(cur_console);
1527	}
1528	return 0;
1529
1530    case GIO_FONT8x8:   	/* get 8x8 dot font */
1531	if (!crtc_vga)
1532	    return ENXIO;
1533	if (fonts_loaded & FONT_8) {
1534	    bcopy(font_8, data, 8*256);
1535	    return 0;
1536	}
1537	else
1538	    return ENXIO;
1539
1540    case PIO_FONT8x14:  	/* set 8x14 dot font */
1541	if (!crtc_vga)
1542	    return ENXIO;
1543	bcopy(data, font_14, 14*256);
1544	fonts_loaded |= FONT_14;
1545	if (!(cur_console->status & UNKNOWN_MODE)) {
1546	    copy_font(LOAD, FONT_14, font_14);
1547	    if (flags & CHAR_CURSOR)
1548	        set_destructive_cursor(cur_console);
1549	}
1550	return 0;
1551
1552    case GIO_FONT8x14:  	/* get 8x14 dot font */
1553	if (!crtc_vga)
1554	    return ENXIO;
1555	if (fonts_loaded & FONT_14) {
1556	    bcopy(font_14, data, 14*256);
1557	    return 0;
1558	}
1559	else
1560	    return ENXIO;
1561
1562    case PIO_FONT8x16:  	/* set 8x16 dot font */
1563	if (!crtc_vga)
1564	    return ENXIO;
1565	bcopy(data, font_16, 16*256);
1566	fonts_loaded |= FONT_16;
1567	if (!(cur_console->status & UNKNOWN_MODE)) {
1568	    copy_font(LOAD, FONT_16, font_16);
1569	    if (flags & CHAR_CURSOR)
1570	        set_destructive_cursor(cur_console);
1571	}
1572	return 0;
1573
1574    case GIO_FONT8x16:  	/* get 8x16 dot font */
1575	if (!crtc_vga)
1576	    return ENXIO;
1577	if (fonts_loaded & FONT_16) {
1578	    bcopy(font_16, data, 16*256);
1579	    return 0;
1580	}
1581	else
1582	    return ENXIO;
1583    default:
1584	break;
1585    }
1586
1587    error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
1588    if (error >= 0)
1589	return(error);
1590    error = ttioctl(tp, cmd, data, flag);
1591    if (error >= 0)
1592	return(error);
1593    return(ENOTTY);
1594}
1595
1596static void
1597scstart(struct tty *tp)
1598{
1599    struct clist *rbp;
1600    int s, len;
1601    u_char buf[PCBURST];
1602    scr_stat *scp = get_scr_stat(tp->t_dev);
1603
1604    if (scp->status & SLKED || blink_in_progress)
1605	return; /* XXX who repeats the call when the above flags are cleared? */
1606    s = spltty();
1607    if (!(tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP))) {
1608	tp->t_state |= TS_BUSY;
1609	rbp = &tp->t_outq;
1610	while (rbp->c_cc) {
1611	    len = q_to_b(rbp, buf, PCBURST);
1612	    splx(s);
1613	    ansi_put(scp, buf, len);
1614	    s = spltty();
1615	}
1616	tp->t_state &= ~TS_BUSY;
1617	ttwwakeup(tp);
1618    }
1619    splx(s);
1620}
1621
1622static void
1623scmousestart(struct tty *tp)
1624{
1625    struct clist *rbp;
1626    int s;
1627    u_char buf[PCBURST];
1628
1629    s = spltty();
1630    if (!(tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP))) {
1631	tp->t_state |= TS_BUSY;
1632	rbp = &tp->t_outq;
1633	while (rbp->c_cc) {
1634	    q_to_b(rbp, buf, PCBURST);
1635	}
1636	tp->t_state &= ~TS_BUSY;
1637	ttwwakeup(tp);
1638    }
1639    splx(s);
1640}
1641
1642void
1643sccnprobe(struct consdev *cp)
1644{
1645    struct isa_device *dvp;
1646
1647    /*
1648     * Take control if we are the highest priority enabled display device.
1649     */
1650    dvp = find_display();
1651    if (dvp == NULL || dvp->id_driver != &scdriver) {
1652	cp->cn_pri = CN_DEAD;
1653	return;
1654    }
1655
1656    if (!scvidprobe(dvp->id_unit, dvp->id_flags)) {
1657	cp->cn_pri = CN_DEAD;
1658	return;
1659    }
1660
1661    /* initialize required fields */
1662    cp->cn_dev = makedev(CDEV_MAJOR, SC_CONSOLE);
1663    cp->cn_pri = CN_INTERNAL;
1664
1665    sc_kbdc = kbdc_open(sc_port);
1666}
1667
1668void
1669sccninit(struct consdev *cp)
1670{
1671    scinit();
1672}
1673
1674void
1675sccnputc(dev_t dev, int c)
1676{
1677    u_char buf[1];
1678    int s;
1679    scr_stat *scp = console[0];
1680    term_stat save = scp->term;
1681
1682    scp->term = kernel_console;
1683    current_default = &kernel_default;
1684    if (scp == cur_console && !(scp->status & UNKNOWN_MODE))
1685	remove_cursor_image(scp);
1686    buf[0] = c;
1687    ansi_put(scp, buf, 1);
1688    kernel_console = scp->term;
1689    current_default = &user_default;
1690    scp->term = save;
1691    s = splclock();
1692    if (scp == cur_console && !(scp->status & UNKNOWN_MODE)) {
1693	if (/* timer not running && */ (scp->start <= scp->end)) {
1694	    sc_bcopy(scp->scr_buf + scp->start, Crtat + scp->start,
1695		   (1 + scp->end - scp->start) * sizeof(u_short));
1696	    scp->start = scp->xsize * scp->ysize;
1697	    scp->end = 0;
1698	}
1699    	scp->cursor_oldpos = scp->cursor_pos;
1700	draw_cursor_image(scp);
1701    }
1702    splx(s);
1703}
1704
1705int
1706sccngetc(dev_t dev)
1707{
1708    int s = spltty();	/* block scintr and scrn_timer while we poll */
1709    int c;
1710
1711    /*
1712     * Stop the screen saver if necessary.
1713     * What if we have been running in the screen saver code... XXX
1714     */
1715    if (scrn_blanked > 0)
1716        stop_scrn_saver(current_saver);
1717
1718    c = scgetc(SCGETC_CN);
1719
1720    /* make sure the screen saver won't be activated soon */
1721    scrn_time_stamp = mono_time.tv_sec;
1722    splx(s);
1723    return(c);
1724}
1725
1726int
1727sccncheckc(dev_t dev)
1728{
1729    int c, s;
1730
1731    s = spltty();
1732    if (scrn_blanked > 0)
1733        stop_scrn_saver(current_saver);
1734    c = scgetc(SCGETC_CN | SCGETC_NONBLOCK);
1735    if (c != NOKEY)
1736        scrn_time_stamp = mono_time.tv_sec;
1737    splx(s);
1738    return(c == NOKEY ? -1 : c);	/* c == -1 can't happen */
1739}
1740
1741static scr_stat
1742*get_scr_stat(dev_t dev)
1743{
1744    int unit = minor(dev);
1745
1746    if (unit == SC_CONSOLE)
1747	return console[0];
1748    if (unit >= MAXCONS || unit < 0)
1749	return(NULL);
1750    return console[unit];
1751}
1752
1753static int
1754get_scr_num()
1755{
1756    int i = 0;
1757
1758    while ((i < MAXCONS) && (cur_console != console[i]))
1759	i++;
1760    return i < MAXCONS ? i : 0;
1761}
1762
1763static void
1764scrn_timer(void *arg)
1765{
1766    scr_stat *scp = cur_console;
1767    int s = spltty();
1768
1769    /*
1770     * With release 2.1 of the Xaccel server, the keyboard is left
1771     * hanging pretty often. Apparently an interrupt from the
1772     * keyboard is lost, and I don't know why (yet).
1773     * This ugly hack calls scintr if input is ready for the keyboard
1774     * and conveniently hides the problem.			XXX
1775     */
1776    /* Try removing anything stuck in the keyboard controller; whether
1777     * it's a keyboard scan code or mouse data. `scintr()' doesn't
1778     * read the mouse data directly, but `kbdio' routines will, as a
1779     * side effect.
1780     */
1781    if (kbdc_lock(sc_kbdc, TRUE)) {
1782	/*
1783	 * We have seen the lock flag is not set. Let's reset the flag early;
1784	 * otherwise `update_led()' failes which may want the lock
1785	 * during `scintr()'.
1786	 */
1787	kbdc_lock(sc_kbdc, FALSE);
1788	if (kbdc_data_ready(sc_kbdc))
1789	    scintr(0);
1790    }
1791
1792    /* should we just return ? */
1793    if ((scp->status&UNKNOWN_MODE) || blink_in_progress || switch_in_progress) {
1794	timeout(scrn_timer, NULL, hz / 10);
1795	splx(s);
1796	return;
1797    }
1798
1799    /* should we stop the screen saver? */
1800    if (mono_time.tv_sec <= scrn_time_stamp + scrn_blank_time)
1801	if (scrn_blanked > 0)
1802            stop_scrn_saver(current_saver);
1803
1804    if (scrn_blanked <= 0) {
1805	/* update screen image */
1806	if (scp->start <= scp->end) {
1807	    sc_bcopy(scp->scr_buf + scp->start, Crtat + scp->start,
1808		   (1 + scp->end - scp->start) * sizeof(u_short));
1809	}
1810
1811	/* update "pseudo" mouse pointer image */
1812	if ((scp->status & MOUSE_VISIBLE) && crtc_vga) {
1813	    /* did mouse move since last time ? */
1814	    if (scp->status & MOUSE_MOVED) {
1815		/* do we need to remove old mouse pointer image ? */
1816		if (scp->mouse_cut_start != NULL ||
1817		    (scp->mouse_pos-scp->scr_buf) <= scp->start ||
1818		    (scp->mouse_pos+scp->xsize+1-scp->scr_buf) >= scp->end) {
1819		    remove_mouse_image(scp);
1820		}
1821		scp->status &= ~MOUSE_MOVED;
1822		draw_mouse_image(scp);
1823	    }
1824	    else {
1825		/* mouse didn't move, has it been overwritten ? */
1826		if ((scp->mouse_pos+scp->xsize+1-scp->scr_buf) >= scp->start &&
1827		    (scp->mouse_pos - scp->scr_buf) <= scp->end) {
1828		    draw_mouse_image(scp);
1829		}
1830	    }
1831	}
1832
1833	/* update cursor image */
1834	if (scp->status & CURSOR_ENABLED) {
1835	    /* did cursor move since last time ? */
1836	    if (scp->cursor_pos != scp->cursor_oldpos) {
1837		/* do we need to remove old cursor image ? */
1838		if ((scp->cursor_oldpos - scp->scr_buf) < scp->start ||
1839		    ((scp->cursor_oldpos - scp->scr_buf) > scp->end)) {
1840		    remove_cursor_image(scp);
1841		}
1842    		scp->cursor_oldpos = scp->cursor_pos;
1843		draw_cursor_image(scp);
1844	    }
1845	    else {
1846		/* cursor didn't move, has it been overwritten ? */
1847		if (scp->cursor_pos - scp->scr_buf >= scp->start &&
1848		    scp->cursor_pos - scp->scr_buf <= scp->end) {
1849		    	draw_cursor_image(scp);
1850		} else {
1851		    /* if its a blinking cursor, we may have to update it */
1852		    if (flags & BLINK_CURSOR)
1853			draw_cursor_image(scp);
1854		}
1855	    }
1856	    blinkrate++;
1857	}
1858
1859	if (scp->mouse_cut_start != NULL)
1860	    draw_cutmarking(scp);
1861
1862	scp->end = 0;
1863	scp->start = scp->xsize*scp->ysize;
1864    }
1865
1866    /* should we activate the screen saver? */
1867    if ((scrn_blank_time != 0)
1868	    && (mono_time.tv_sec > scrn_time_stamp + scrn_blank_time))
1869	(*current_saver)(TRUE);
1870
1871    timeout(scrn_timer, NULL, hz / 25);
1872    splx(s);
1873}
1874
1875int
1876add_scrn_saver(void (*this_saver)(int))
1877{
1878    if (current_saver != none_saver)
1879	return EBUSY;
1880    current_saver = this_saver;
1881    return 0;
1882}
1883
1884int
1885remove_scrn_saver(void (*this_saver)(int))
1886{
1887    if (current_saver != this_saver)
1888	return EINVAL;
1889
1890    /*
1891     * In order to prevent `current_saver' from being called by
1892     * the timeout routine `scrn_timer()' while we manipulate
1893     * the saver list, we shall set `current_saver' to `none_saver'
1894     * before stopping the current saver, rather than blocking by `splXX()'.
1895     */
1896    current_saver = none_saver;
1897    if (scrn_blanked > 0)
1898        stop_scrn_saver(this_saver);
1899
1900    return 0;
1901}
1902
1903static void
1904stop_scrn_saver(void (*saver)(int))
1905{
1906    (*saver)(FALSE);
1907    scrn_time_stamp = mono_time.tv_sec;
1908    mark_all(cur_console);
1909}
1910
1911static void
1912clear_screen(scr_stat *scp)
1913{
1914    move_crsr(scp, 0, 0);
1915    scp->cursor_oldpos = scp->cursor_pos;
1916    fillw(scp->term.cur_color | scr_map[0x20], scp->scr_buf,
1917	  scp->xsize * scp->ysize);
1918    mark_all(scp);
1919    remove_cutmarking(scp);
1920}
1921
1922static int
1923switch_scr(scr_stat *scp, u_int next_scr)
1924{
1925    if (switch_in_progress && (cur_console->proc != pfind(cur_console->pid)))
1926	switch_in_progress = FALSE;
1927
1928    if (next_scr >= MAXCONS || switch_in_progress ||
1929	(cur_console->smode.mode == VT_AUTO
1930	 && cur_console->status & UNKNOWN_MODE)) {
1931	do_bell(scp, BELL_PITCH, BELL_DURATION);
1932	return EINVAL;
1933    }
1934
1935    /* is the wanted virtual console open ? */
1936    if (next_scr) {
1937	struct tty *tp = VIRTUAL_TTY(next_scr);
1938	if (!(tp->t_state & TS_ISOPEN)) {
1939	    do_bell(scp, BELL_PITCH, BELL_DURATION);
1940	    return EINVAL;
1941	}
1942    }
1943    /* delay switch if actively updating screen */
1944    if (write_in_progress || blink_in_progress) {
1945	delayed_next_scr = next_scr+1;
1946	return 0;
1947    }
1948    switch_in_progress = TRUE;
1949    old_scp = cur_console;
1950    new_scp = console[next_scr];
1951    wakeup((caddr_t)&new_scp->smode);
1952    if (new_scp == old_scp) {
1953	switch_in_progress = FALSE;
1954	delayed_next_scr = FALSE;
1955	return 0;
1956    }
1957
1958    /* has controlling process died? */
1959    if (old_scp->proc && (old_scp->proc != pfind(old_scp->pid)))
1960	old_scp->smode.mode = VT_AUTO;
1961    if (new_scp->proc && (new_scp->proc != pfind(new_scp->pid)))
1962	new_scp->smode.mode = VT_AUTO;
1963
1964    /* check the modes and switch appropriately */
1965    if (old_scp->smode.mode == VT_PROCESS) {
1966	old_scp->status |= SWITCH_WAIT_REL;
1967	psignal(old_scp->proc, old_scp->smode.relsig);
1968    }
1969    else {
1970	exchange_scr();
1971	if (new_scp->smode.mode == VT_PROCESS) {
1972	    new_scp->status |= SWITCH_WAIT_ACQ;
1973	    psignal(new_scp->proc, new_scp->smode.acqsig);
1974	}
1975	else
1976	    switch_in_progress = FALSE;
1977    }
1978    return 0;
1979}
1980
1981static void
1982exchange_scr(void)
1983{
1984    move_crsr(old_scp, old_scp->xpos, old_scp->ypos);
1985    cur_console = new_scp;
1986    if (old_scp->mode != new_scp->mode || (old_scp->status & UNKNOWN_MODE)){
1987	if (crtc_vga && video_mode_ptr)
1988	    set_mode(new_scp);
1989    }
1990    move_crsr(new_scp, new_scp->xpos, new_scp->ypos);
1991    if (!(new_scp->status & UNKNOWN_MODE) && (flags & CHAR_CURSOR))
1992	set_destructive_cursor(new_scp);
1993    if ((old_scp->status & UNKNOWN_MODE) && crtc_vga)
1994	load_palette(palette);
1995    if (old_scp->status & KBD_RAW_MODE || new_scp->status & KBD_RAW_MODE)
1996	shfts = ctls = alts = agrs = metas = 0;
1997    update_leds(new_scp->status);
1998    delayed_next_scr = FALSE;
1999    mark_all(new_scp);
2000}
2001
2002static void
2003scan_esc(scr_stat *scp, u_char c)
2004{
2005    static u_char ansi_col[16] =
2006	{0, 4, 2, 6, 1, 5, 3, 7, 8, 12, 10, 14, 9, 13, 11, 15};
2007    int i, n;
2008    u_short *src, *dst, count;
2009
2010    if (scp->term.esc == 1) {	/* seen ESC */
2011	switch (c) {
2012
2013	case '7':   /* Save cursor position */
2014	    scp->saved_xpos = scp->xpos;
2015	    scp->saved_ypos = scp->ypos;
2016	    break;
2017
2018	case '8':   /* Restore saved cursor position */
2019	    if (scp->saved_xpos >= 0 && scp->saved_ypos >= 0)
2020		move_crsr(scp, scp->saved_xpos, scp->saved_ypos);
2021	    break;
2022
2023	case '[':   /* Start ESC [ sequence */
2024	    scp->term.esc = 2;
2025	    scp->term.last_param = -1;
2026	    for (i = scp->term.num_param; i < MAX_ESC_PAR; i++)
2027		scp->term.param[i] = 1;
2028	    scp->term.num_param = 0;
2029	    return;
2030
2031	case 'M':   /* Move cursor up 1 line, scroll if at top */
2032	    if (scp->ypos > 0)
2033		move_crsr(scp, scp->xpos, scp->ypos - 1);
2034	    else {
2035		bcopy(scp->scr_buf, scp->scr_buf + scp->xsize,
2036		       (scp->ysize - 1) * scp->xsize * sizeof(u_short));
2037		fillw(scp->term.cur_color | scr_map[0x20],
2038		      scp->scr_buf, scp->xsize);
2039    		mark_all(scp);
2040	    }
2041	    break;
2042#if notyet
2043	case 'Q':
2044	    scp->term.esc = 4;
2045	    return;
2046#endif
2047	case 'c':   /* Clear screen & home */
2048	    clear_screen(scp);
2049	    break;
2050
2051	case '(':   /* iso-2022: designate 94 character set to G0 */
2052	    scp->term.esc = 5;
2053	    return;
2054	}
2055    }
2056    else if (scp->term.esc == 2) {	/* seen ESC [ */
2057	if (c >= '0' && c <= '9') {
2058	    if (scp->term.num_param < MAX_ESC_PAR) {
2059	    if (scp->term.last_param != scp->term.num_param) {
2060		scp->term.last_param = scp->term.num_param;
2061		scp->term.param[scp->term.num_param] = 0;
2062	    }
2063	    else
2064		scp->term.param[scp->term.num_param] *= 10;
2065	    scp->term.param[scp->term.num_param] += c - '0';
2066	    return;
2067	    }
2068	}
2069	scp->term.num_param = scp->term.last_param + 1;
2070	switch (c) {
2071
2072	case ';':
2073	    if (scp->term.num_param < MAX_ESC_PAR)
2074		return;
2075	    break;
2076
2077	case '=':
2078	    scp->term.esc = 3;
2079	    scp->term.last_param = -1;
2080	    for (i = scp->term.num_param; i < MAX_ESC_PAR; i++)
2081		scp->term.param[i] = 1;
2082	    scp->term.num_param = 0;
2083	    return;
2084
2085	case 'A':   /* up n rows */
2086	    n = scp->term.param[0]; if (n < 1) n = 1;
2087	    move_crsr(scp, scp->xpos, scp->ypos - n);
2088	    break;
2089
2090	case 'B':   /* down n rows */
2091	    n = scp->term.param[0]; if (n < 1) n = 1;
2092	    move_crsr(scp, scp->xpos, scp->ypos + n);
2093	    break;
2094
2095	case 'C':   /* right n columns */
2096	    n = scp->term.param[0]; if (n < 1) n = 1;
2097	    move_crsr(scp, scp->xpos + n, scp->ypos);
2098	    break;
2099
2100	case 'D':   /* left n columns */
2101	    n = scp->term.param[0]; if (n < 1) n = 1;
2102	    move_crsr(scp, scp->xpos - n, scp->ypos);
2103	    break;
2104
2105	case 'E':   /* cursor to start of line n lines down */
2106	    n = scp->term.param[0]; if (n < 1) n = 1;
2107	    move_crsr(scp, 0, scp->ypos + n);
2108	    break;
2109
2110	case 'F':   /* cursor to start of line n lines up */
2111	    n = scp->term.param[0]; if (n < 1) n = 1;
2112	    move_crsr(scp, 0, scp->ypos - n);
2113	    break;
2114
2115	case 'f':   /* Cursor move */
2116	case 'H':
2117	    if (scp->term.num_param == 0)
2118		move_crsr(scp, 0, 0);
2119	    else if (scp->term.num_param == 2)
2120		move_crsr(scp, scp->term.param[1] - 1, scp->term.param[0] - 1);
2121	    break;
2122
2123	case 'J':   /* Clear all or part of display */
2124	    if (scp->term.num_param == 0)
2125		n = 0;
2126	    else
2127		n = scp->term.param[0];
2128	    switch (n) {
2129	    case 0: /* clear form cursor to end of display */
2130		fillw(scp->term.cur_color | scr_map[0x20],
2131		      scp->cursor_pos,
2132		      scp->scr_buf + scp->xsize * scp->ysize - scp->cursor_pos);
2133    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2134    		mark_for_update(scp, scp->xsize * scp->ysize);
2135		remove_cutmarking(scp);
2136		break;
2137	    case 1: /* clear from beginning of display to cursor */
2138		fillw(scp->term.cur_color | scr_map[0x20],
2139		      scp->scr_buf,
2140		      scp->cursor_pos - scp->scr_buf);
2141    		mark_for_update(scp, 0);
2142    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2143		remove_cutmarking(scp);
2144		break;
2145	    case 2: /* clear entire display */
2146		fillw(scp->term.cur_color | scr_map[0x20], scp->scr_buf,
2147		      scp->xsize * scp->ysize);
2148		mark_all(scp);
2149		remove_cutmarking(scp);
2150		break;
2151	    }
2152	    break;
2153
2154	case 'K':   /* Clear all or part of line */
2155	    if (scp->term.num_param == 0)
2156		n = 0;
2157	    else
2158		n = scp->term.param[0];
2159	    switch (n) {
2160	    case 0: /* clear form cursor to end of line */
2161		fillw(scp->term.cur_color | scr_map[0x20],
2162		      scp->cursor_pos,
2163		      scp->xsize - scp->xpos);
2164    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2165    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf +
2166				scp->xsize - scp->xpos);
2167		break;
2168	    case 1: /* clear from beginning of line to cursor */
2169		fillw(scp->term.cur_color | scr_map[0x20],
2170		      scp->cursor_pos - scp->xpos,
2171		      scp->xpos + 1);
2172    		mark_for_update(scp, scp->ypos * scp->xsize);
2173    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2174		break;
2175	    case 2: /* clear entire line */
2176		fillw(scp->term.cur_color | scr_map[0x20],
2177		      scp->cursor_pos - scp->xpos,
2178		      scp->xsize);
2179    		mark_for_update(scp, scp->ypos * scp->xsize);
2180    		mark_for_update(scp, (scp->ypos + 1) * scp->xsize);
2181		break;
2182	    }
2183	    break;
2184
2185	case 'L':   /* Insert n lines */
2186	    n = scp->term.param[0]; if (n < 1) n = 1;
2187	    if (n > scp->ysize - scp->ypos)
2188		n = scp->ysize - scp->ypos;
2189	    src = scp->scr_buf + scp->ypos * scp->xsize;
2190	    dst = src + n * scp->xsize;
2191	    count = scp->ysize - (scp->ypos + n);
2192	    bcopy(src, dst, count * scp->xsize * sizeof(u_short));
2193	    fillw(scp->term.cur_color | scr_map[0x20], src,
2194		  n * scp->xsize);
2195	    mark_for_update(scp, scp->ypos * scp->xsize);
2196	    mark_for_update(scp, scp->xsize * scp->ysize);
2197	    break;
2198
2199	case 'M':   /* Delete n lines */
2200	    n = scp->term.param[0]; if (n < 1) n = 1;
2201	    if (n > scp->ysize - scp->ypos)
2202		n = scp->ysize - scp->ypos;
2203	    dst = scp->scr_buf + scp->ypos * scp->xsize;
2204	    src = dst + n * scp->xsize;
2205	    count = scp->ysize - (scp->ypos + n);
2206	    bcopy(src, dst, count * scp->xsize * sizeof(u_short));
2207	    src = dst + count * scp->xsize;
2208	    fillw(scp->term.cur_color | scr_map[0x20], src,
2209		  n * scp->xsize);
2210	    mark_for_update(scp, scp->ypos * scp->xsize);
2211	    mark_for_update(scp, scp->xsize * scp->ysize);
2212	    break;
2213
2214	case 'P':   /* Delete n chars */
2215	    n = scp->term.param[0]; if (n < 1) n = 1;
2216	    if (n > scp->xsize - scp->xpos)
2217		n = scp->xsize - scp->xpos;
2218	    dst = scp->cursor_pos;
2219	    src = dst + n;
2220	    count = scp->xsize - (scp->xpos + n);
2221	    bcopy(src, dst, count * sizeof(u_short));
2222	    src = dst + count;
2223	    fillw(scp->term.cur_color | scr_map[0x20], src, n);
2224	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2225	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n + count);
2226	    break;
2227
2228	case '@':   /* Insert n chars */
2229	    n = scp->term.param[0]; if (n < 1) n = 1;
2230	    if (n > scp->xsize - scp->xpos)
2231		n = scp->xsize - scp->xpos;
2232	    src = scp->cursor_pos;
2233	    dst = src + n;
2234	    count = scp->xsize - (scp->xpos + n);
2235	    bcopy(src, dst, count * sizeof(u_short));
2236	    fillw(scp->term.cur_color | scr_map[0x20], src, n);
2237	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2238	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n + count);
2239	    break;
2240
2241	case 'S':   /* scroll up n lines */
2242	    n = scp->term.param[0]; if (n < 1)  n = 1;
2243	    if (n > scp->ysize)
2244		n = scp->ysize;
2245	    bcopy(scp->scr_buf + (scp->xsize * n),
2246		   scp->scr_buf,
2247		   scp->xsize * (scp->ysize - n) * sizeof(u_short));
2248	    fillw(scp->term.cur_color | scr_map[0x20],
2249		  scp->scr_buf + scp->xsize * (scp->ysize - n),
2250		  scp->xsize * n);
2251    	    mark_all(scp);
2252	    break;
2253
2254	case 'T':   /* scroll down n lines */
2255	    n = scp->term.param[0]; if (n < 1)  n = 1;
2256	    if (n > scp->ysize)
2257		n = scp->ysize;
2258	    bcopy(scp->scr_buf,
2259		  scp->scr_buf + (scp->xsize * n),
2260		  scp->xsize * (scp->ysize - n) *
2261		  sizeof(u_short));
2262	    fillw(scp->term.cur_color | scr_map[0x20],
2263		  scp->scr_buf, scp->xsize * n);
2264    	    mark_all(scp);
2265	    break;
2266
2267	case 'X':   /* erase n characters in line */
2268	    n = scp->term.param[0]; if (n < 1)  n = 1;
2269	    if (n > scp->xsize - scp->xpos)
2270		n = scp->xsize - scp->xpos;
2271	    fillw(scp->term.cur_color | scr_map[0x20],
2272		  scp->cursor_pos, n);
2273	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2274	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n);
2275	    break;
2276
2277	case 'Z':   /* move n tabs backwards */
2278	    n = scp->term.param[0]; if (n < 1)  n = 1;
2279	    if ((i = scp->xpos & 0xf8) == scp->xpos)
2280		i -= 8*n;
2281	    else
2282		i -= 8*(n-1);
2283	    if (i < 0)
2284		i = 0;
2285	    move_crsr(scp, i, scp->ypos);
2286	    break;
2287
2288	case '`':   /* move cursor to column n */
2289	    n = scp->term.param[0]; if (n < 1)  n = 1;
2290	    move_crsr(scp, n - 1, scp->ypos);
2291	    break;
2292
2293	case 'a':   /* move cursor n columns to the right */
2294	    n = scp->term.param[0]; if (n < 1)  n = 1;
2295	    move_crsr(scp, scp->xpos + n, scp->ypos);
2296	    break;
2297
2298	case 'd':   /* move cursor to row n */
2299	    n = scp->term.param[0]; if (n < 1)  n = 1;
2300	    move_crsr(scp, scp->xpos, n - 1);
2301	    break;
2302
2303	case 'e':   /* move cursor n rows down */
2304	    n = scp->term.param[0]; if (n < 1)  n = 1;
2305	    move_crsr(scp, scp->xpos, scp->ypos + n);
2306	    break;
2307
2308	case 'm':   /* change attribute */
2309	    if (scp->term.num_param == 0) {
2310		scp->term.attr_mask = NORMAL_ATTR;
2311		scp->term.cur_attr =
2312		    scp->term.cur_color = scp->term.std_color;
2313		break;
2314	    }
2315	    for (i = 0; i < scp->term.num_param; i++) {
2316		switch (n = scp->term.param[i]) {
2317		case 0: /* back to normal */
2318		    scp->term.attr_mask = NORMAL_ATTR;
2319		    scp->term.cur_attr =
2320			scp->term.cur_color = scp->term.std_color;
2321		    break;
2322		case 1: /* bold */
2323		    scp->term.attr_mask |= BOLD_ATTR;
2324		    scp->term.cur_attr = mask2attr(&scp->term);
2325		    break;
2326		case 4: /* underline */
2327		    scp->term.attr_mask |= UNDERLINE_ATTR;
2328		    scp->term.cur_attr = mask2attr(&scp->term);
2329		    break;
2330		case 5: /* blink */
2331		    scp->term.attr_mask |= BLINK_ATTR;
2332		    scp->term.cur_attr = mask2attr(&scp->term);
2333		    break;
2334		case 7: /* reverse video */
2335		    scp->term.attr_mask |= REVERSE_ATTR;
2336		    scp->term.cur_attr = mask2attr(&scp->term);
2337		    break;
2338		case 30: case 31: /* set fg color */
2339		case 32: case 33: case 34:
2340		case 35: case 36: case 37:
2341		    scp->term.attr_mask |= FOREGROUND_CHANGED;
2342		    scp->term.cur_color =
2343			(scp->term.cur_color&0xF000) | (ansi_col[(n-30)&7]<<8);
2344		    scp->term.cur_attr = mask2attr(&scp->term);
2345		    break;
2346		case 40: case 41: /* set bg color */
2347		case 42: case 43: case 44:
2348		case 45: case 46: case 47:
2349		    scp->term.attr_mask |= BACKGROUND_CHANGED;
2350		    scp->term.cur_color =
2351			(scp->term.cur_color&0x0F00) | (ansi_col[(n-40)&7]<<12);
2352		    scp->term.cur_attr = mask2attr(&scp->term);
2353		    break;
2354		}
2355	    }
2356	    break;
2357
2358	case 's':   /* Save cursor position */
2359	    scp->saved_xpos = scp->xpos;
2360	    scp->saved_ypos = scp->ypos;
2361	    break;
2362
2363	case 'u':   /* Restore saved cursor position */
2364	    if (scp->saved_xpos >= 0 && scp->saved_ypos >= 0)
2365		move_crsr(scp, scp->saved_xpos, scp->saved_ypos);
2366	    break;
2367
2368	case 'x':
2369	    if (scp->term.num_param == 0)
2370		n = 0;
2371	    else
2372		n = scp->term.param[0];
2373	    switch (n) {
2374	    case 0:     /* reset attributes */
2375		scp->term.attr_mask = NORMAL_ATTR;
2376		scp->term.cur_attr =
2377		    scp->term.cur_color = scp->term.std_color =
2378		    current_default->std_color;
2379		scp->term.rev_color = current_default->rev_color;
2380		break;
2381	    case 1:     /* set ansi background */
2382		scp->term.attr_mask &= ~BACKGROUND_CHANGED;
2383		scp->term.cur_color = scp->term.std_color =
2384		    (scp->term.std_color & 0x0F00) |
2385		    (ansi_col[(scp->term.param[1])&0x0F]<<12);
2386		scp->term.cur_attr = mask2attr(&scp->term);
2387		break;
2388	    case 2:     /* set ansi foreground */
2389		scp->term.attr_mask &= ~FOREGROUND_CHANGED;
2390		scp->term.cur_color = scp->term.std_color =
2391		    (scp->term.std_color & 0xF000) |
2392		    (ansi_col[(scp->term.param[1])&0x0F]<<8);
2393		scp->term.cur_attr = mask2attr(&scp->term);
2394		break;
2395	    case 3:     /* set ansi attribute directly */
2396		scp->term.attr_mask &= ~(FOREGROUND_CHANGED|BACKGROUND_CHANGED);
2397		scp->term.cur_color = scp->term.std_color =
2398		    (scp->term.param[1]&0xFF)<<8;
2399		scp->term.cur_attr = mask2attr(&scp->term);
2400		break;
2401	    case 5:     /* set ansi reverse video background */
2402		scp->term.rev_color =
2403		    (scp->term.rev_color & 0x0F00) |
2404		    (ansi_col[(scp->term.param[1])&0x0F]<<12);
2405		scp->term.cur_attr = mask2attr(&scp->term);
2406		break;
2407	    case 6:     /* set ansi reverse video foreground */
2408		scp->term.rev_color =
2409		    (scp->term.rev_color & 0xF000) |
2410		    (ansi_col[(scp->term.param[1])&0x0F]<<8);
2411		scp->term.cur_attr = mask2attr(&scp->term);
2412		break;
2413	    case 7:     /* set ansi reverse video directly */
2414		scp->term.rev_color =
2415		    (scp->term.param[1]&0xFF)<<8;
2416		scp->term.cur_attr = mask2attr(&scp->term);
2417		break;
2418	    }
2419	    break;
2420
2421	case 'z':   /* switch to (virtual) console n */
2422	    if (scp->term.num_param == 1)
2423		switch_scr(scp, scp->term.param[0]);
2424	    break;
2425	}
2426    }
2427    else if (scp->term.esc == 3) {	/* seen ESC [0-9]+ = */
2428	if (c >= '0' && c <= '9') {
2429	    if (scp->term.num_param < MAX_ESC_PAR) {
2430	    if (scp->term.last_param != scp->term.num_param) {
2431		scp->term.last_param = scp->term.num_param;
2432		scp->term.param[scp->term.num_param] = 0;
2433	    }
2434	    else
2435		scp->term.param[scp->term.num_param] *= 10;
2436	    scp->term.param[scp->term.num_param] += c - '0';
2437	    return;
2438	    }
2439	}
2440	scp->term.num_param = scp->term.last_param + 1;
2441	switch (c) {
2442
2443	case ';':
2444	    if (scp->term.num_param < MAX_ESC_PAR)
2445		return;
2446	    break;
2447
2448	case 'A':   /* set display border color */
2449	    if (scp->term.num_param == 1) {
2450		scp->border=scp->term.param[0] & 0xff;
2451		if (scp == cur_console)
2452		    set_border(scp->border);
2453            }
2454	    break;
2455
2456	case 'B':   /* set bell pitch and duration */
2457	    if (scp->term.num_param == 2) {
2458		scp->bell_pitch = scp->term.param[0];
2459		scp->bell_duration = scp->term.param[1]*10;
2460	    }
2461	    break;
2462
2463	case 'C':   /* set cursor type & shape */
2464	    if (scp->term.num_param == 1) {
2465		if (scp->term.param[0] & 0x01)
2466		    flags |= BLINK_CURSOR;
2467		else
2468		    flags &= ~BLINK_CURSOR;
2469		if ((scp->term.param[0] & 0x02) && crtc_vga)
2470		    flags |= CHAR_CURSOR;
2471		else
2472		    flags &= ~CHAR_CURSOR;
2473	    }
2474	    else if (scp->term.num_param == 2) {
2475		scp->cursor_start = scp->term.param[0] & 0x1F;
2476		scp->cursor_end = scp->term.param[1] & 0x1F;
2477	    }
2478	    /*
2479	     * The cursor shape is global property; all virtual consoles
2480	     * are affected. Update the cursor in the current console...
2481	     */
2482	    if (!(cur_console->status & UNKNOWN_MODE)) {
2483		remove_cursor_image(cur_console);
2484		if (crtc_vga && (flags & CHAR_CURSOR))
2485	            set_destructive_cursor(cur_console);
2486		draw_cursor_image(cur_console);
2487	    }
2488	    break;
2489
2490	case 'F':   /* set ansi foreground */
2491	    if (scp->term.num_param == 1) {
2492		scp->term.attr_mask &= ~FOREGROUND_CHANGED;
2493		scp->term.cur_color = scp->term.std_color =
2494		    (scp->term.std_color & 0xF000)
2495		    | ((scp->term.param[0] & 0x0F) << 8);
2496		scp->term.cur_attr = mask2attr(&scp->term);
2497	    }
2498	    break;
2499
2500	case 'G':   /* set ansi background */
2501	    if (scp->term.num_param == 1) {
2502		scp->term.attr_mask &= ~BACKGROUND_CHANGED;
2503		scp->term.cur_color = scp->term.std_color =
2504		    (scp->term.std_color & 0x0F00)
2505		    | ((scp->term.param[0] & 0x0F) << 12);
2506		scp->term.cur_attr = mask2attr(&scp->term);
2507	    }
2508	    break;
2509
2510	case 'H':   /* set ansi reverse video foreground */
2511	    if (scp->term.num_param == 1) {
2512		scp->term.rev_color =
2513		    (scp->term.rev_color & 0xF000)
2514		    | ((scp->term.param[0] & 0x0F) << 8);
2515		scp->term.cur_attr = mask2attr(&scp->term);
2516	    }
2517	    break;
2518
2519	case 'I':   /* set ansi reverse video background */
2520	    if (scp->term.num_param == 1) {
2521		scp->term.rev_color =
2522		    (scp->term.rev_color & 0x0F00)
2523		    | ((scp->term.param[0] & 0x0F) << 12);
2524		scp->term.cur_attr = mask2attr(&scp->term);
2525	    }
2526	    break;
2527	}
2528    }
2529#if notyet
2530    else if (scp->term.esc == 4) {	/* seen ESC Q */
2531	/* to be filled */
2532    }
2533#endif
2534    else if (scp->term.esc == 5) {	/* seen ESC ( */
2535	switch (c) {
2536	case 'B':   /* iso-2022: desginate ASCII into G0 */
2537	    break;
2538	/* other items to be filled */
2539	default:
2540	    break;
2541	}
2542    }
2543    scp->term.esc = 0;
2544}
2545
2546static void
2547ansi_put(scr_stat *scp, u_char *buf, int len)
2548{
2549    u_char *ptr = buf;
2550
2551    /* make screensaver happy */
2552    if (scp == cur_console)
2553	scrn_time_stamp = mono_time.tv_sec;
2554
2555    write_in_progress++;
2556outloop:
2557    if (scp->term.esc) {
2558	scan_esc(scp, *ptr++);
2559	len--;
2560    }
2561    else if (PRINTABLE(*ptr)) {     /* Print only printables */
2562 	int cnt = len <= (scp->xsize-scp->xpos) ? len : (scp->xsize-scp->xpos);
2563 	u_short cur_attr = scp->term.cur_attr;
2564 	u_short *cursor_pos = scp->cursor_pos;
2565	do {
2566	    /*
2567	     * gcc-2.6.3 generates poor (un)sign extension code.  Casting the
2568	     * pointers in the following to volatile should have no effect,
2569	     * but in fact speeds up this inner loop from 26 to 18 cycles
2570	     * (+ cache misses) on i486's.
2571	     */
2572#define	UCVP(ucp)	((u_char volatile *)(ucp))
2573	    *cursor_pos++ = UCVP(scr_map)[*UCVP(ptr)] | cur_attr;
2574	    ptr++;
2575	    cnt--;
2576	} while (cnt && PRINTABLE(*ptr));
2577	len -= (cursor_pos - scp->cursor_pos);
2578	scp->xpos += (cursor_pos - scp->cursor_pos);
2579	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2580	mark_for_update(scp, cursor_pos - scp->scr_buf);
2581	scp->cursor_pos = cursor_pos;
2582	if (scp->xpos >= scp->xsize) {
2583	    scp->xpos = 0;
2584	    scp->ypos++;
2585	}
2586    }
2587    else  {
2588	switch(*ptr) {
2589	case 0x07:
2590	    do_bell(scp, scp->bell_pitch, scp->bell_duration);
2591	    break;
2592
2593	case 0x08:      /* non-destructive backspace */
2594	    if (scp->cursor_pos > scp->scr_buf) {
2595	    	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2596		scp->cursor_pos--;
2597	    	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2598		if (scp->xpos > 0)
2599		    scp->xpos--;
2600		else {
2601		    scp->xpos += scp->xsize - 1;
2602		    scp->ypos--;
2603		}
2604	    }
2605	    break;
2606
2607	case 0x09:  /* non-destructive tab */
2608	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2609	    scp->cursor_pos += (8 - scp->xpos % 8u);
2610	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2611	    if ((scp->xpos += (8 - scp->xpos % 8u)) >= scp->xsize) {
2612	        scp->xpos = 0;
2613	        scp->ypos++;
2614	    }
2615	    break;
2616
2617	case 0x0a:  /* newline, same pos */
2618	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2619	    scp->cursor_pos += scp->xsize;
2620	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2621	    scp->ypos++;
2622	    break;
2623
2624	case 0x0c:  /* form feed, clears screen */
2625	    clear_screen(scp);
2626	    break;
2627
2628	case 0x0d:  /* return, return to pos 0 */
2629	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2630	    scp->cursor_pos -= scp->xpos;
2631	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2632	    scp->xpos = 0;
2633	    break;
2634
2635	case 0x1b:  /* start escape sequence */
2636	    scp->term.esc = 1;
2637	    scp->term.num_param = 0;
2638	    break;
2639	}
2640	ptr++; len--;
2641    }
2642    /* do we have to scroll ?? */
2643    if (scp->cursor_pos >= scp->scr_buf + scp->ysize * scp->xsize) {
2644	remove_cutmarking(scp);
2645	if (scp->history) {
2646	    bcopy(scp->scr_buf, scp->history_head,
2647		   scp->xsize * sizeof(u_short));
2648	    scp->history_head += scp->xsize;
2649	    if (scp->history_head + scp->xsize >
2650		scp->history + scp->history_size)
2651		scp->history_head = scp->history;
2652	}
2653	bcopy(scp->scr_buf + scp->xsize, scp->scr_buf,
2654	       scp->xsize * (scp->ysize - 1) * sizeof(u_short));
2655	fillw(scp->term.cur_color | scr_map[0x20],
2656	      scp->scr_buf + scp->xsize * (scp->ysize - 1),
2657	      scp->xsize);
2658	scp->cursor_pos -= scp->xsize;
2659	scp->ypos--;
2660    	mark_all(scp);
2661    }
2662    if (len)
2663	goto outloop;
2664    write_in_progress--;
2665    if (delayed_next_scr)
2666	switch_scr(scp, delayed_next_scr - 1);
2667}
2668
2669static void
2670scinit(void)
2671{
2672    u_int hw_cursor;
2673    u_int i;
2674
2675    if (init_done != COLD)
2676	return;
2677    init_done = WARM;
2678
2679    /*
2680     * Ensure a zero start address.  This is mainly to recover after
2681     * switching from pcvt using userconfig().  The registers are w/o
2682     * for old hardware so it's too hard to relocate the active screen
2683     * memory.
2684     */
2685    outb(crtc_addr, 12);
2686    outb(crtc_addr + 1, 0);
2687    outb(crtc_addr, 13);
2688    outb(crtc_addr + 1, 0);
2689
2690    /* extract cursor location */
2691    outb(crtc_addr, 14);
2692    hw_cursor = inb(crtc_addr + 1) << 8;
2693    outb(crtc_addr, 15);
2694    hw_cursor |= inb(crtc_addr + 1);
2695
2696    /*
2697     * Validate cursor location.  It may be off the screen.  Then we must
2698     * not use it for the initial buffer offset.
2699     */
2700    if (hw_cursor >= ROW * COL)
2701	hw_cursor = (ROW - 1) * COL;
2702
2703    /* move hardware cursor out of the way */
2704    outb(crtc_addr, 14);
2705    outb(crtc_addr + 1, 0xff);
2706    outb(crtc_addr, 15);
2707    outb(crtc_addr + 1, 0xff);
2708
2709    /* set up the first console */
2710    current_default = &user_default;
2711    console[0] = &main_console;
2712    init_scp(console[0]);
2713    cur_console = console[0];
2714
2715    /* discard the video mode table if we are not familiar with it... */
2716    if (video_mode_ptr) {
2717        if (comp_vgaregs(vgaregs, video_mode_ptr + 64*console[0]->mode))
2718            video_mode_ptr = NULL;
2719    }
2720
2721    /* copy screen to temporary buffer */
2722    sc_bcopy(Crtat, sc_buffer,
2723	   console[0]->xsize * console[0]->ysize * sizeof(u_short));
2724
2725    console[0]->scr_buf = console[0]->mouse_pos = sc_buffer;
2726    console[0]->cursor_pos = console[0]->cursor_oldpos = sc_buffer + hw_cursor;
2727    console[0]->cursor_saveunder = *console[0]->cursor_pos;
2728    console[0]->xpos = hw_cursor % COL;
2729    console[0]->ypos = hw_cursor / COL;
2730    for (i=1; i<MAXCONS; i++)
2731	console[i] = NULL;
2732    kernel_console.esc = 0;
2733    kernel_console.attr_mask = NORMAL_ATTR;
2734    kernel_console.cur_attr =
2735	kernel_console.cur_color = kernel_console.std_color =
2736	kernel_default.std_color;
2737    kernel_console.rev_color = kernel_default.rev_color;
2738
2739    /* initialize mapscrn arrays to a one to one map */
2740    for (i=0; i<sizeof(scr_map); i++) {
2741	scr_map[i] = scr_rmap[i] = i;
2742    }
2743
2744    /* Save font and palette if VGA */
2745    if (crtc_vga) {
2746	if (fonts_loaded & FONT_16) {
2747		copy_font(LOAD, FONT_16, font_16);
2748	} else {
2749		copy_font(SAVE, FONT_16, font_16);
2750		fonts_loaded = FONT_16;
2751	}
2752	save_palette();
2753	set_destructive_cursor(console[0]);
2754    }
2755
2756#ifdef SC_SPLASH_SCREEN
2757    /*
2758     * Now put up a graphics image, and maybe cycle a
2759     * couble of palette entries for simple animation.
2760     */
2761    toggle_splash_screen(cur_console);
2762#endif
2763}
2764
2765static scr_stat
2766*alloc_scp()
2767{
2768    scr_stat *scp;
2769
2770    scp = (scr_stat *)malloc(sizeof(scr_stat), M_DEVBUF, M_WAITOK);
2771    init_scp(scp);
2772    scp->scr_buf = scp->cursor_pos = scp->cursor_oldpos =
2773	(u_short *)malloc(scp->xsize*scp->ysize*sizeof(u_short),
2774			  M_DEVBUF, M_WAITOK);
2775    scp->mouse_pos = scp->mouse_oldpos =
2776	scp->scr_buf + ((scp->mouse_ypos/scp->font_size)*scp->xsize +
2777			scp->mouse_xpos/8);
2778    scp->history_head = scp->history_pos = scp->history =
2779	(u_short *)malloc(scp->history_size*sizeof(u_short),
2780			  M_DEVBUF, M_WAITOK);
2781    bzero(scp->history_head, scp->history_size*sizeof(u_short));
2782/* SOS
2783    if (crtc_vga && video_mode_ptr)
2784	set_mode(scp);
2785*/
2786    clear_screen(scp);
2787    scp->cursor_saveunder = *scp->cursor_pos;
2788    return scp;
2789}
2790
2791static void
2792init_scp(scr_stat *scp)
2793{
2794    if (crtc_vga)
2795	if (crtc_addr == MONO_BASE)
2796	    scp->mode = M_VGA_M80x25;
2797	else
2798	    scp->mode = M_VGA_C80x25;
2799    else
2800	if (crtc_addr == MONO_BASE)
2801	    scp->mode = M_B80x25;
2802	else
2803	    scp->mode = M_C80x25;
2804
2805    scp->font_size = 16;
2806    scp->xsize = COL;
2807    scp->ysize = ROW;
2808    scp->xpos = scp->ypos = 0;
2809    scp->saved_xpos = scp->saved_ypos = -1;
2810    scp->start = scp->xsize * scp->ysize;
2811    scp->end = 0;
2812    scp->term.esc = 0;
2813    scp->term.attr_mask = NORMAL_ATTR;
2814    scp->term.cur_attr =
2815	scp->term.cur_color = scp->term.std_color =
2816	current_default->std_color;
2817    scp->term.rev_color = current_default->rev_color;
2818    scp->border = BG_BLACK;
2819    scp->cursor_start = *(char *)pa_to_va(0x461);
2820    scp->cursor_end = *(char *)pa_to_va(0x460);
2821    scp->mouse_xpos = scp->xsize*8/2;
2822    scp->mouse_ypos = scp->ysize*scp->font_size/2;
2823    scp->mouse_cut_start = scp->mouse_cut_end = NULL;
2824    scp->mouse_signal = 0;
2825    scp->mouse_pid = 0;
2826    scp->mouse_proc = NULL;
2827    scp->bell_pitch = BELL_PITCH;
2828    scp->bell_duration = BELL_DURATION;
2829    scp->status = (*(char *)pa_to_va(0x417) & 0x20) ? NLKED : 0;
2830    scp->status |= CURSOR_ENABLED;
2831    scp->pid = 0;
2832    scp->proc = NULL;
2833    scp->smode.mode = VT_AUTO;
2834    scp->history_head = scp->history_pos = scp->history = NULL;
2835    scp->history_size = max(HISTORY_SIZE, scp->xsize*scp->ysize);
2836}
2837
2838static u_char
2839*get_fstr(u_int c, u_int *len)
2840{
2841    u_int i;
2842
2843    if (!(c & FKEY))
2844	return(NULL);
2845    i = (c & 0xFF) - F_FN;
2846    if (i > n_fkey_tab)
2847	return(NULL);
2848    *len = fkey_tab[i].len;
2849    return(fkey_tab[i].str);
2850}
2851
2852static void
2853history_to_screen(scr_stat *scp)
2854{
2855    int i;
2856
2857    for (i=0; i<scp->ysize; i++)
2858	bcopy(scp->history + (((scp->history_pos - scp->history) +
2859	       scp->history_size-((i+1)*scp->xsize))%scp->history_size),
2860	       scp->scr_buf + (scp->xsize * (scp->ysize-1 - i)),
2861	       scp->xsize * sizeof(u_short));
2862    mark_all(scp);
2863}
2864
2865static int
2866history_up_line(scr_stat *scp)
2867{
2868    if (WRAPHIST(scp, scp->history_pos, -(scp->xsize*scp->ysize)) !=
2869	scp->history_head) {
2870	scp->history_pos = WRAPHIST(scp, scp->history_pos, -scp->xsize);
2871	history_to_screen(scp);
2872	return 0;
2873    }
2874    else
2875	return -1;
2876}
2877
2878static int
2879history_down_line(scr_stat *scp)
2880{
2881    if (scp->history_pos != scp->history_head) {
2882	scp->history_pos = WRAPHIST(scp, scp->history_pos, scp->xsize);
2883	history_to_screen(scp);
2884	return 0;
2885    }
2886    else
2887	return -1;
2888}
2889
2890/*
2891 * scgetc(flags) - get character from keyboard.
2892 * If flags & SCGETC_CN, then avoid harmful side effects.
2893 * If flags & SCGETC_NONBLOCK, then wait until a key is pressed, else
2894 * return NOKEY if there is nothing there.
2895 */
2896static u_int
2897scgetc(u_int flags)
2898{
2899    struct key_t *key;
2900    u_char scancode, keycode;
2901    u_int state, action;
2902    int c;
2903    static u_char esc_flag = 0, compose = 0;
2904    static u_int chr = 0;
2905
2906next_code:
2907    /* first see if there is something in the keyboard port */
2908    if (flags & SCGETC_NONBLOCK) {
2909	c = read_kbd_data_no_wait(sc_kbdc);
2910	if (c == -1)
2911	    return(NOKEY);
2912    } else {
2913	do {
2914	    c = read_kbd_data(sc_kbdc);
2915	} while(c == -1);
2916    }
2917    scancode = (u_char)c;
2918
2919    /* do the /dev/random device a favour */
2920    if (!(flags & SCGETC_CN))
2921	add_keyboard_randomness(scancode);
2922
2923    if (cur_console->status & KBD_RAW_MODE)
2924	return scancode;
2925
2926    keycode = scancode & 0x7F;
2927    switch (esc_flag) {
2928    case 0x00:      /* normal scancode */
2929	switch(scancode) {
2930	case 0xB8:  /* left alt (compose key) */
2931	    if (compose) {
2932		compose = 0;
2933		if (chr > 255) {
2934		    do_bell(cur_console,
2935			BELL_PITCH, BELL_DURATION);
2936		    chr = 0;
2937		}
2938	    }
2939	    break;
2940	case 0x38:
2941	    if (!compose) {
2942		compose = 1;
2943		chr = 0;
2944	    }
2945	    break;
2946	case 0xE0:
2947	case 0xE1:
2948	    esc_flag = scancode;
2949	    goto next_code;
2950	}
2951	break;
2952    case 0xE0:      /* 0xE0 prefix */
2953	esc_flag = 0;
2954	switch (keycode) {
2955	case 0x1C:  /* right enter key */
2956	    keycode = 0x59;
2957	    break;
2958	case 0x1D:  /* right ctrl key */
2959	    keycode = 0x5A;
2960	    break;
2961	case 0x35:  /* keypad divide key */
2962	    keycode = 0x5B;
2963	    break;
2964	case 0x37:  /* print scrn key */
2965	    keycode = 0x5C;
2966	    break;
2967	case 0x38:  /* right alt key (alt gr) */
2968	    keycode = 0x5D;
2969	    break;
2970	case 0x47:  /* grey home key */
2971	    keycode = 0x5E;
2972	    break;
2973	case 0x48:  /* grey up arrow key */
2974	    keycode = 0x5F;
2975	    break;
2976	case 0x49:  /* grey page up key */
2977	    keycode = 0x60;
2978	    break;
2979	case 0x4B:  /* grey left arrow key */
2980	    keycode = 0x61;
2981	    break;
2982	case 0x4D:  /* grey right arrow key */
2983	    keycode = 0x62;
2984	    break;
2985	case 0x4F:  /* grey end key */
2986	    keycode = 0x63;
2987	    break;
2988	case 0x50:  /* grey down arrow key */
2989	    keycode = 0x64;
2990	    break;
2991	case 0x51:  /* grey page down key */
2992	    keycode = 0x65;
2993	    break;
2994	case 0x52:  /* grey insert key */
2995	    keycode = 0x66;
2996	    break;
2997	case 0x53:  /* grey delete key */
2998	    keycode = 0x67;
2999	    break;
3000
3001	/* the following 3 are only used on the MS "Natural" keyboard */
3002	case 0x5b:  /* left Window key */
3003	    keycode = 0x69;
3004	    break;
3005	case 0x5c:  /* right Window key */
3006	    keycode = 0x6a;
3007	    break;
3008	case 0x5d:  /* menu key */
3009	    keycode = 0x6b;
3010	    break;
3011	default:    /* ignore everything else */
3012	    goto next_code;
3013	}
3014	break;
3015    case 0xE1:      /* 0xE1 prefix */
3016	esc_flag = 0;
3017	if (keycode == 0x1D)
3018	    esc_flag = 0x1D;
3019	goto next_code;
3020	/* NOT REACHED */
3021    case 0x1D:      /* pause / break */
3022	esc_flag = 0;
3023	if (keycode != 0x45)
3024	    goto next_code;
3025	keycode = 0x68;
3026	break;
3027    }
3028
3029    /* if scroll-lock pressed allow history browsing */
3030    if (cur_console->history && cur_console->status & SLKED) {
3031	int i;
3032
3033	cur_console->status &= ~CURSOR_ENABLED;
3034	if (!(cur_console->status & BUFFER_SAVED)) {
3035	    cur_console->status |= BUFFER_SAVED;
3036	    cur_console->history_save = cur_console->history_head;
3037
3038	    /* copy screen into top of history buffer */
3039	    for (i=0; i<cur_console->ysize; i++) {
3040		bcopy(cur_console->scr_buf + (cur_console->xsize * i),
3041		       cur_console->history_head,
3042		       cur_console->xsize * sizeof(u_short));
3043		cur_console->history_head += cur_console->xsize;
3044		if (cur_console->history_head + cur_console->xsize >
3045		    cur_console->history + cur_console->history_size)
3046		    cur_console->history_head=cur_console->history;
3047	    }
3048	    cur_console->history_pos = cur_console->history_head;
3049	    history_to_screen(cur_console);
3050	}
3051	switch (scancode) {
3052	case 0x47:  /* home key */
3053	    cur_console->history_pos = cur_console->history_head;
3054	    history_to_screen(cur_console);
3055	    goto next_code;
3056
3057	case 0x4F:  /* end key */
3058	    cur_console->history_pos =
3059		WRAPHIST(cur_console, cur_console->history_head,
3060			 cur_console->xsize*cur_console->ysize);
3061	    history_to_screen(cur_console);
3062	    goto next_code;
3063
3064	case 0x48:  /* up arrow key */
3065	    if (history_up_line(cur_console))
3066		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3067	    goto next_code;
3068
3069	case 0x50:  /* down arrow key */
3070	    if (history_down_line(cur_console))
3071		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3072	    goto next_code;
3073
3074	case 0x49:  /* page up key */
3075	    for (i=0; i<cur_console->ysize; i++)
3076	    if (history_up_line(cur_console)) {
3077		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3078		break;
3079	    }
3080	    goto next_code;
3081
3082	case 0x51:  /* page down key */
3083	    for (i=0; i<cur_console->ysize; i++)
3084	    if (history_down_line(cur_console)) {
3085		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3086		break;
3087	    }
3088	    goto next_code;
3089	}
3090    }
3091
3092    if (compose) {
3093	switch (scancode) {
3094	/* key pressed process it */
3095	case 0x47: case 0x48: case 0x49:    /* keypad 7,8,9 */
3096	    chr = (scancode - 0x40) + chr*10;
3097	    goto next_code;
3098	case 0x4B: case 0x4C: case 0x4D:    /* keypad 4,5,6 */
3099	    chr = (scancode - 0x47) + chr*10;
3100	    goto next_code;
3101	case 0x4F: case 0x50: case 0x51:    /* keypad 1,2,3 */
3102	    chr = (scancode - 0x4E) + chr*10;
3103	    goto next_code;
3104	case 0x52:              /* keypad 0 */
3105	    chr *= 10;
3106	    goto next_code;
3107
3108	/* key release, no interest here */
3109	case 0xC7: case 0xC8: case 0xC9:    /* keypad 7,8,9 */
3110	case 0xCB: case 0xCC: case 0xCD:    /* keypad 4,5,6 */
3111	case 0xCF: case 0xD0: case 0xD1:    /* keypad 1,2,3 */
3112	case 0xD2:              /* keypad 0 */
3113	    goto next_code;
3114
3115	case 0x38:              /* left alt key */
3116	    break;
3117	default:
3118	    if (chr) {
3119		compose = chr = 0;
3120		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3121		goto next_code;
3122	    }
3123	    break;
3124	}
3125    }
3126
3127    state = (shfts ? 1 : 0 ) | (2 * (ctls ? 1 : 0)) | (4 * (alts ? 1 : 0));
3128    if ((!agrs && (cur_console->status & ALKED))
3129	|| (agrs && !(cur_console->status & ALKED)))
3130	keycode += ALTGR_OFFSET;
3131    key = &key_map.key[keycode];
3132    if ( ((key->flgs & FLAG_LOCK_C) && (cur_console->status & CLKED))
3133	 || ((key->flgs & FLAG_LOCK_N) && (cur_console->status & NLKED)) )
3134	state ^= 1;
3135
3136    /* Check for make/break */
3137    action = key->map[state];
3138    if (scancode & 0x80) {      /* key released */
3139	if (key->spcl & (0x80>>state)) {
3140	    switch (action) {
3141	    case LSH:
3142		shfts &= ~1;
3143		break;
3144	    case RSH:
3145		shfts &= ~2;
3146		break;
3147	    case LCTR:
3148		ctls &= ~1;
3149		break;
3150	    case RCTR:
3151		ctls &= ~2;
3152		break;
3153	    case LALT:
3154		alts &= ~1;
3155		break;
3156	    case RALT:
3157		alts &= ~2;
3158		break;
3159	    case NLK:
3160		nlkcnt = 0;
3161		break;
3162	    case CLK:
3163		clkcnt = 0;
3164		break;
3165	    case SLK:
3166		slkcnt = 0;
3167		break;
3168	    case ASH:
3169		agrs = 0;
3170		break;
3171	    case ALK:
3172		alkcnt = 0;
3173		break;
3174	    case META:
3175		metas = 0;
3176		break;
3177	    }
3178	}
3179	if (chr && !compose) {
3180	    action = chr;
3181	    chr = 0;
3182	    return(action);
3183	}
3184    } else {
3185	/* key pressed */
3186	if (key->spcl & (0x80>>state)) {
3187	    switch (action) {
3188	    /* LOCKING KEYS */
3189	    case NLK:
3190#ifdef SC_SPLASH_SCREEN
3191		toggle_splash_screen(cur_console); /* SOS XXX */
3192#endif
3193		if (!nlkcnt) {
3194		    nlkcnt++;
3195		    if (cur_console->status & NLKED)
3196			cur_console->status &= ~NLKED;
3197		    else
3198			cur_console->status |= NLKED;
3199		    update_leds(cur_console->status);
3200		}
3201		break;
3202	    case CLK:
3203		if (!clkcnt) {
3204		    clkcnt++;
3205		    if (cur_console->status & CLKED)
3206			cur_console->status &= ~CLKED;
3207		    else
3208			cur_console->status |= CLKED;
3209		    update_leds(cur_console->status);
3210		}
3211		break;
3212	    case SLK:
3213		if (!slkcnt) {
3214		    slkcnt++;
3215		    if (cur_console->status & SLKED) {
3216			cur_console->status &= ~SLKED;
3217			if (cur_console->status & BUFFER_SAVED){
3218			    int i;
3219			    u_short *ptr = cur_console->history_save;
3220
3221			    for (i=0; i<cur_console->ysize; i++) {
3222				bcopy(ptr,
3223				       cur_console->scr_buf +
3224				       (cur_console->xsize*i),
3225				       cur_console->xsize * sizeof(u_short));
3226				ptr += cur_console->xsize;
3227				if (ptr + cur_console->xsize >
3228				    cur_console->history +
3229				    cur_console->history_size)
3230				    ptr = cur_console->history;
3231			    }
3232			    cur_console->status &= ~BUFFER_SAVED;
3233			    cur_console->history_head=cur_console->history_save;
3234			    cur_console->status |= CURSOR_ENABLED;
3235			    mark_all(cur_console);
3236			}
3237			scstart(VIRTUAL_TTY(get_scr_num()));
3238		    }
3239		    else
3240			cur_console->status |= SLKED;
3241		    update_leds(cur_console->status);
3242		}
3243		break;
3244	    case ALK:
3245		if (!alkcnt) {
3246		    alkcnt++;
3247		    if (cur_console->status & ALKED)
3248			cur_console->status &= ~ALKED;
3249		    else
3250			cur_console->status |= ALKED;
3251		    update_leds(cur_console->status);
3252		}
3253		break;
3254
3255	    /* NON-LOCKING KEYS */
3256	    case NOP:
3257		break;
3258	    case SPSC:
3259#ifdef SC_SPLASH_SCREEN
3260		toggle_splash_screen(cur_console);
3261#endif
3262		break;
3263	    case RBT:
3264		shutdown_nice();
3265		break;
3266	    case SUSP:
3267#if NAPM > 0
3268		apm_suspend();
3269#endif
3270		break;
3271
3272	    case DBG:
3273#ifdef DDB          /* try to switch to console 0 */
3274		if (cur_console->smode.mode == VT_AUTO &&
3275		    console[0]->smode.mode == VT_AUTO)
3276		    switch_scr(cur_console, 0);
3277		Debugger("manual escape to debugger");
3278#else
3279		printf("No debugger in kernel\n");
3280#endif
3281		break;
3282	    case LSH:
3283		shfts |= 1;
3284		break;
3285	    case RSH:
3286		shfts |= 2;
3287		break;
3288	    case LCTR:
3289		ctls |= 1;
3290		break;
3291	    case RCTR:
3292		ctls |= 2;
3293		break;
3294	    case LALT:
3295		alts |= 1;
3296		break;
3297	    case RALT:
3298		alts |= 2;
3299		break;
3300	    case ASH:
3301		agrs = 1;
3302		break;
3303	    case META:
3304		metas = 1;
3305		break;
3306	    case NEXT:
3307		{
3308		int next, this = get_scr_num();
3309		for (next = this+1; next != this; next = (next+1)%MAXCONS) {
3310		    struct tty *tp = VIRTUAL_TTY(next);
3311		    if (tp->t_state & TS_ISOPEN) {
3312			switch_scr(cur_console, next);
3313			break;
3314		    }
3315		}
3316		}
3317		break;
3318	    case BTAB:
3319		return(BKEY);
3320	    default:
3321		if (action >= F_SCR && action <= L_SCR) {
3322		    switch_scr(cur_console, action - F_SCR);
3323		    break;
3324		}
3325		if (action >= F_FN && action <= L_FN)
3326		    action |= FKEY;
3327		return(action);
3328	    }
3329	}
3330	else {
3331	    if (metas)
3332		action |= MKEY;
3333	    return(action);
3334	}
3335    }
3336    goto next_code;
3337}
3338
3339int
3340scmmap(dev_t dev, int offset, int nprot)
3341{
3342    if (offset > 0x20000 - PAGE_SIZE)
3343	return -1;
3344    return i386_btop((VIDEOMEM + offset));
3345}
3346
3347/*
3348 * Calculate hardware attributes word using logical attributes mask and
3349 * hardware colors
3350 */
3351
3352static int
3353mask2attr(struct term_stat *term)
3354{
3355    int attr, mask = term->attr_mask;
3356
3357    if (mask & REVERSE_ATTR) {
3358	attr = ((mask & FOREGROUND_CHANGED) ?
3359		((term->cur_color & 0xF000) >> 4) :
3360		(term->rev_color & 0x0F00)) |
3361	       ((mask & BACKGROUND_CHANGED) ?
3362		((term->cur_color & 0x0F00) << 4) :
3363		(term->rev_color & 0xF000));
3364    } else
3365	attr = term->cur_color;
3366
3367    /* XXX: underline mapping for Hercules adapter can be better */
3368    if (mask & (BOLD_ATTR | UNDERLINE_ATTR))
3369	attr ^= 0x0800;
3370    if (mask & BLINK_ATTR)
3371	attr ^= 0x8000;
3372
3373    return attr;
3374}
3375
3376static void
3377set_keyboard(int command, int data)
3378{
3379    int s;
3380    int c;
3381
3382    if (sc_kbdc == NULL)
3383	return;
3384
3385    /* prevent the timeout routine from polling the keyboard */
3386    if (!kbdc_lock(sc_kbdc, TRUE))
3387	return;
3388
3389    /* disable the keyboard and mouse interrupt */
3390    s = spltty();
3391#if 0
3392    c = get_controller_command_byte(sc_kbdc);
3393    if ((c == -1)
3394	|| !set_controller_command_byte(sc_kbdc,
3395            kbdc_get_device_mask(sc_kbdc),
3396            KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
3397                | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
3398	/* CONTROLLER ERROR */
3399        kbdc_lock(sc_kbdc, FALSE);
3400	splx(s);
3401	return;
3402    }
3403    /*
3404     * Now that the keyboard controller is told not to generate
3405     * the keyboard and mouse interrupts, call `splx()' to allow
3406     * the other tty interrupts. The clock interrupt may also occur,
3407     * but the timeout routine (`scrn_timer()') will be blocked
3408     * by the lock flag set via `kbdc_lock()'
3409     */
3410    splx(s);
3411#endif
3412
3413    if (send_kbd_command_and_data(sc_kbdc, command, data) != KBD_ACK)
3414        send_kbd_command(sc_kbdc, KBDC_ENABLE_KBD);
3415
3416#if 0
3417    /* restore the interrupts */
3418    if (!set_controller_command_byte(sc_kbdc,
3419            kbdc_get_device_mask(sc_kbdc),
3420	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
3421	/* CONTROLLER ERROR */
3422    }
3423#else
3424    splx(s);
3425#endif
3426    kbdc_lock(sc_kbdc, FALSE);
3427}
3428
3429static void
3430update_leds(int which)
3431{
3432    static u_char xlate_leds[8] = { 0, 4, 2, 6, 1, 5, 3, 7 };
3433
3434    /* replace CAPS led with ALTGR led for ALTGR keyboards */
3435    if (key_map.n_keys > ALTGR_OFFSET) {
3436	if (which & ALKED)
3437	    which |= CLKED;
3438	else
3439	    which &= ~CLKED;
3440    }
3441
3442    set_keyboard(KBDC_SET_LEDS, xlate_leds[which & LED_MASK]);
3443}
3444
3445void
3446set_mode(scr_stat *scp)
3447{
3448    char *modetable;
3449    char special_modetable[64];
3450
3451    if (scp != cur_console)
3452	return;
3453
3454    /* setup video hardware for the given mode */
3455    switch (scp->mode) {
3456    case M_VGA_M80x60:
3457	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3458	goto special_80x60;
3459
3460    case M_VGA_C80x60:
3461	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3462special_80x60:
3463	special_modetable[2]  = 0x08;
3464	special_modetable[19] = 0x47;
3465	goto special_480l;
3466
3467    case M_VGA_M80x30:
3468	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3469	goto special_80x30;
3470
3471    case M_VGA_C80x30:
3472	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3473special_80x30:
3474	special_modetable[19] = 0x4f;
3475special_480l:
3476	special_modetable[9] |= 0xc0;
3477	special_modetable[16] = 0x08;
3478	special_modetable[17] = 0x3e;
3479	special_modetable[26] = 0xea;
3480	special_modetable[28] = 0xdf;
3481	special_modetable[31] = 0xe7;
3482	special_modetable[32] = 0x04;
3483	modetable = special_modetable;
3484	goto setup_mode;
3485
3486    case M_ENH_B80x43:
3487	bcopy(video_mode_ptr+(64*M_ENH_B80x25), &special_modetable, 64);
3488	goto special_80x43;
3489
3490    case M_ENH_C80x43:
3491	bcopy(video_mode_ptr+(64*M_ENH_C80x25), &special_modetable, 64);
3492special_80x43:
3493	special_modetable[28] = 87;
3494	goto special_80x50;
3495
3496    case M_VGA_M80x50:
3497	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3498	goto special_80x50;
3499
3500    case M_VGA_C80x50:
3501	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3502special_80x50:
3503	special_modetable[2] = 8;
3504	special_modetable[19] = 7;
3505	modetable = special_modetable;
3506	goto setup_mode;
3507
3508    case M_VGA_C40x25: case M_VGA_C80x25:
3509    case M_VGA_M80x25:
3510    case M_B40x25:     case M_C40x25:
3511    case M_B80x25:     case M_C80x25:
3512    case M_ENH_B40x25: case M_ENH_C40x25:
3513    case M_ENH_B80x25: case M_ENH_C80x25:
3514    case M_EGAMONO80x25:
3515
3516	modetable = video_mode_ptr + (scp->mode * 64);
3517setup_mode:
3518	set_vgaregs(modetable);
3519	scp->font_size = *(modetable + 2);
3520
3521	/* set font type (size) */
3522	if (scp->font_size < 14) {
3523	    if (fonts_loaded & FONT_8)
3524		copy_font(LOAD, FONT_8, font_8);
3525	    outb(TSIDX, 0x03); outb(TSREG, 0x0A);   /* font 2 */
3526	} else if (scp->font_size >= 16) {
3527	    if (fonts_loaded & FONT_16)
3528		copy_font(LOAD, FONT_16, font_16);
3529	    outb(TSIDX, 0x03); outb(TSREG, 0x00);   /* font 0 */
3530	} else {
3531	    if (fonts_loaded & FONT_14)
3532		copy_font(LOAD, FONT_14, font_14);
3533	    outb(TSIDX, 0x03); outb(TSREG, 0x05);   /* font 1 */
3534	}
3535	if (flags & CHAR_CURSOR)
3536	    set_destructive_cursor(scp);
3537	mark_all(scp);
3538	break;
3539
3540    case M_VGA_MODEX:
3541	/* start out with std 320x200x256 mode */
3542	bcopy(video_mode_ptr+(64*M_VGA_CG320), &special_modetable, 64);
3543	/* "unchain" the VGA mode */
3544	special_modetable[5-1+0x04] &= 0xf7;
3545	special_modetable[5-1+0x04] |= 0x04;
3546	/* turn off doubleword mode */
3547	special_modetable[10+0x14] &= 0xbf;
3548	/* turn off word adressing */
3549	special_modetable[10+0x17] |= 0x40;
3550	/* set logical screen width */
3551	special_modetable[10+0x13] = 80;
3552	/* set 240 lines */
3553	special_modetable[10+0x11] = 0x2c;
3554	special_modetable[10+0x06] = 0x0d;
3555	special_modetable[10+0x07] = 0x3e;
3556	special_modetable[10+0x10] = 0xea;
3557	special_modetable[10+0x11] = 0xac;
3558	special_modetable[10+0x12] = 0xdf;
3559	special_modetable[10+0x15] = 0xe7;
3560	special_modetable[10+0x16] = 0x06;
3561	/* set vertical sync polarity to reflect aspect ratio */
3562	special_modetable[9] = 0xe3;
3563
3564	modetable = special_modetable;
3565	goto setup_grmode;
3566
3567    case M_BG320:     case M_CG320:     case M_BG640:
3568    case M_CG320_D:   case M_CG640_E:
3569    case M_CG640x350: case M_ENH_CG640:
3570    case M_BG640x480: case M_CG640x480: case M_VGA_CG320:
3571	modetable = video_mode_ptr + (scp->mode * 64);
3572setup_grmode:
3573	set_vgaregs(modetable);
3574	scp->font_size = FONT_NONE;
3575	break;
3576
3577    default:
3578	/* call user defined function XXX */
3579	break;
3580    }
3581
3582    /* set border color for this (virtual) console */
3583    set_border(scp->border);
3584    return;
3585}
3586
3587void
3588set_border(u_char color)
3589{
3590    switch (crtc_type) {
3591    case KD_EGA:
3592    case KD_VGA:
3593        inb(crtc_addr + 6);		/* reset flip-flop */
3594        outb(ATC, 0x11); outb(ATC, color);
3595        inb(crtc_addr + 6);		/* reset flip-flop */
3596        outb(ATC, 0x20);		/* enable Palette */
3597	break;
3598    case KD_CGA:
3599	outb(crtc_addr + 5, color & 0x0f); /* color select register */
3600	break;
3601    case KD_MONO:
3602    case KD_HERCULES:
3603    default:
3604	break;
3605    }
3606}
3607
3608static void
3609set_vgaregs(char *modetable)
3610{
3611    int i, s = splhigh();
3612
3613    outb(TSIDX, 0x00); outb(TSREG, 0x01);   	/* stop sequencer */
3614    outb(TSIDX, 0x07); outb(TSREG, 0x00);   	/* unlock registers */
3615    for (i=0; i<4; i++) {           		/* program sequencer */
3616	outb(TSIDX, i+1);
3617	outb(TSREG, modetable[i+5]);
3618    }
3619    outb(MISC, modetable[9]);       		/* set dot-clock */
3620    outb(TSIDX, 0x00); outb(TSREG, 0x03);   	/* start sequencer */
3621    outb(crtc_addr, 0x11);
3622    outb(crtc_addr+1, inb(crtc_addr+1) & 0x7F);
3623    for (i=0; i<25; i++) {          		/* program crtc */
3624	outb(crtc_addr, i);
3625	if (i == 14 || i == 15)     		/* no hardware cursor */
3626	    outb(crtc_addr+1, 0xff);
3627	else
3628	    outb(crtc_addr+1, modetable[i+10]);
3629    }
3630    inb(crtc_addr+6);           		/* reset flip-flop */
3631    for (i=0; i<20; i++) {          		/* program attribute ctrl */
3632	outb(ATC, i);
3633	outb(ATC, modetable[i+35]);
3634    }
3635    for (i=0; i<9; i++) {           		/* program graph data ctrl */
3636	outb(GDCIDX, i);
3637	outb(GDCREG, modetable[i+55]);
3638    }
3639    inb(crtc_addr+6);           		/* reset flip-flop */
3640    outb(ATC, 0x20);            		/* enable palette */
3641    splx(s);
3642}
3643
3644static void
3645read_vgaregs(char *buf)
3646{
3647    int i, j;
3648    int s;
3649
3650    bzero(buf, 64);
3651
3652    s = splhigh();
3653
3654    outb(TSIDX, 0x00); outb(TSREG, 0x01);   	/* stop sequencer */
3655    outb(TSIDX, 0x07); outb(TSREG, 0x00);   	/* unlock registers */
3656    for (i=0, j=5; i<4; i++) {
3657	outb(TSIDX, i+1);
3658	buf[j++] = inb(TSREG);
3659    }
3660    buf[9] = inb(MISC + 10);      		/* dot-clock */
3661    outb(TSIDX, 0x00); outb(TSREG, 0x03);   	/* start sequencer */
3662
3663    for (i=0, j=10; i<25; i++) {       		/* crtc */
3664	outb(crtc_addr, i);
3665	buf[j++] = inb(crtc_addr+1);
3666    }
3667    for (i=0, j=35; i<20; i++) {          	/* attribute ctrl */
3668        inb(crtc_addr+6);           		/* reset flip-flop */
3669	outb(ATC, i);
3670	buf[j++] = inb(ATC + 1);
3671    }
3672    for (i=0, j=55; i<9; i++) {           	/* graph data ctrl */
3673	outb(GDCIDX, i);
3674	buf[j++] = inb(GDCREG);
3675    }
3676    inb(crtc_addr+6);           		/* reset flip-flop */
3677    outb(ATC, 0x20);            		/* enable palette */
3678
3679    buf[0] = *(char *)pa_to_va(0x44a);		/* COLS */
3680    buf[1] = *(char *)pa_to_va(0x484);		/* ROWS */
3681    buf[2] = *(char *)pa_to_va(0x485);		/* POINTS */
3682    buf[3] = *(char *)pa_to_va(0x44c);
3683    buf[4] = *(char *)pa_to_va(0x44d);
3684
3685    splx(s);
3686}
3687
3688static int
3689comp_vgaregs(u_char *buf1, u_char *buf2)
3690{
3691    int i;
3692
3693    for(i = 0; i < 20; ++i) {
3694	if (*buf1++ != *buf2++)
3695	    return 1;
3696    }
3697    buf1 += 2;  /* skip the cursor shape */
3698    buf2 += 2;
3699    for(i = 22; i < 24; ++i) {
3700	if (*buf1++ != *buf2++)
3701	    return 1;
3702    }
3703    buf1 += 2;  /* skip the cursor position */
3704    buf2 += 2;
3705    for(i = 26; i < 64; ++i) {
3706	if (*buf1++ != *buf2++)
3707	    return 1;
3708    }
3709    return 0;
3710}
3711
3712static void
3713dump_vgaregs(u_char *buf)
3714{
3715    int i;
3716
3717    for(i = 0; i < 64;) {
3718	printf("%02x ", buf[i]);
3719	if ((++i % 16) == 0)
3720	    printf("\n");
3721    }
3722}
3723
3724static void
3725set_font_mode()
3726{
3727    int s = splhigh();
3728
3729    /* setup vga for loading fonts (graphics plane mode) */
3730    inb(crtc_addr+6);           		/* reset flip-flop */
3731    outb(ATC, 0x10); outb(ATC, 0x01);
3732    inb(crtc_addr+6);               		/* reset flip-flop */
3733    outb(ATC, 0x20);            		/* enable palette */
3734
3735#if SLOW_VGA
3736    outb(TSIDX, 0x02); outb(TSREG, 0x04);
3737    outb(TSIDX, 0x04); outb(TSREG, 0x06);
3738    outb(GDCIDX, 0x04); outb(GDCREG, 0x02);
3739    outb(GDCIDX, 0x05); outb(GDCREG, 0x00);
3740    outb(GDCIDX, 0x06); outb(GDCREG, 0x05);
3741#else
3742    outw(TSIDX, 0x0402);
3743    outw(TSIDX, 0x0604);
3744    outw(GDCIDX, 0x0204);
3745    outw(GDCIDX, 0x0005);
3746    outw(GDCIDX, 0x0506);               /* addr = a0000, 64kb */
3747#endif
3748    splx(s);
3749}
3750
3751static void
3752set_normal_mode()
3753{
3754    char *modetable;
3755    int s = splhigh();
3756
3757    switch (cur_console->mode) {
3758    case M_VGA_M80x60:
3759    case M_VGA_M80x50:
3760    case M_VGA_M80x30:
3761	modetable = video_mode_ptr + (64*M_VGA_M80x25);
3762	break;
3763
3764    case M_VGA_C80x60:
3765    case M_VGA_C80x50:
3766    case M_VGA_C80x30:
3767	modetable = video_mode_ptr + (64*M_VGA_C80x25);
3768	break;
3769
3770    case M_ENH_B80x43:
3771	modetable = video_mode_ptr + (64*M_ENH_B80x25);
3772	break;
3773
3774    case M_ENH_C80x43:
3775	modetable = video_mode_ptr + (64*M_ENH_C80x25);
3776	break;
3777
3778    case M_VGA_C40x25: case M_VGA_C80x25:
3779    case M_VGA_M80x25:
3780    case M_B40x25:     case M_C40x25:
3781    case M_B80x25:     case M_C80x25:
3782    case M_ENH_B40x25: case M_ENH_C40x25:
3783    case M_ENH_B80x25: case M_ENH_C80x25:
3784    case M_EGAMONO80x25:
3785
3786    case M_BG320:     case M_CG320:     case M_BG640:
3787    case M_CG320_D:   case M_CG640_E:
3788    case M_CG640x350: case M_ENH_CG640:
3789    case M_BG640x480: case M_CG640x480: case M_VGA_CG320:
3790	modetable = video_mode_ptr + (cur_console->mode * 64);
3791	break;
3792
3793    default:
3794	modetable = video_mode_ptr + (64*M_VGA_C80x25);
3795    }
3796
3797    if (video_mode_ptr == NULL)
3798	modetable = vgaregs;
3799
3800    /* setup vga for normal operation mode again */
3801    inb(crtc_addr+6);           		/* reset flip-flop */
3802    outb(ATC, 0x10); outb(ATC, modetable[0x10+35]);
3803    inb(crtc_addr+6);               		/* reset flip-flop */
3804    outb(ATC, 0x20);            		/* enable palette */
3805#if SLOW_VGA
3806    outb(TSIDX, 0x02); outb(TSREG, modetable[0x02+4]);
3807    outb(TSIDX, 0x04); outb(TSREG, modetable[0x04+4]);
3808    outb(GDCIDX, 0x04); outb(GDCREG, modetable[0x04+55]);
3809    outb(GDCIDX, 0x05); outb(GDCREG, modetable[0x05+55]);
3810    outb(GDCIDX, 0x06); outb(GDCREG, modetable[0x06+55]);
3811    if (crtc_addr == MONO_BASE) {
3812	outb(GDCIDX, 0x06); outb(GDCREG,(modetable[0x06+55] & 0x03) | 0x08);
3813    }
3814    else {
3815	outb(GDCIDX, 0x06); outb(GDCREG,(modetable[0x06+55] & 0x03) | 0x0c);
3816    }
3817#else
3818    outw(TSIDX, 0x0002 | (modetable[0x02+4]<<8));
3819    outw(TSIDX, 0x0004 | (modetable[0x04+4]<<8));
3820    outw(GDCIDX, 0x0004 | (modetable[0x04+55]<<8));
3821    outw(GDCIDX, 0x0005 | (modetable[0x05+55]<<8));
3822    if (crtc_addr == MONO_BASE)
3823        outw(GDCIDX, 0x0006 | (((modetable[0x06+55] & 0x03) | 0x08)<<8));
3824    else
3825        outw(GDCIDX, 0x0006 | (((modetable[0x06+55] & 0x03) | 0x0c)<<8));
3826#endif
3827    splx(s);
3828}
3829
3830void
3831copy_font(int operation, int font_type, char* font_image)
3832{
3833    int ch, line, segment, fontsize;
3834    u_char val;
3835
3836    /* dont mess with console we dont know video mode on */
3837    if (cur_console->status & UNKNOWN_MODE)
3838	return;
3839
3840    switch (font_type) {
3841    default:
3842    case FONT_8:
3843	segment = 0x8000;
3844	fontsize = 8;
3845	break;
3846    case FONT_14:
3847	segment = 0x4000;
3848	fontsize = 14;
3849	break;
3850    case FONT_16:
3851	segment = 0x0000;
3852	fontsize = 16;
3853	break;
3854    }
3855    outb(TSIDX, 0x01); val = inb(TSREG);        /* disable screen */
3856    outb(TSIDX, 0x01); outb(TSREG, val | 0x20);
3857    set_font_mode();
3858    for (ch=0; ch < 256; ch++)
3859	for (line=0; line < fontsize; line++)
3860	if (operation)
3861	    *(char *)pa_to_va(VIDEOMEM+(segment)+(ch*32)+line) =
3862		    font_image[(ch*fontsize)+line];
3863	else
3864	    font_image[(ch*fontsize)+line] =
3865	    *(char *)pa_to_va(VIDEOMEM+(segment)+(ch*32)+line);
3866    set_normal_mode();
3867    outb(TSIDX, 0x01); outb(TSREG, val & 0xDF); /* enable screen */
3868}
3869
3870static void
3871set_destructive_cursor(scr_stat *scp)
3872{
3873    u_char cursor[32];
3874    caddr_t address;
3875    int i;
3876    char *font_buffer;
3877
3878
3879    if (scp->font_size < 14) {
3880	font_buffer = font_8;
3881	address = (caddr_t)VIDEOMEM + 0x8000;
3882    }
3883    else if (scp->font_size >= 16) {
3884	font_buffer = font_16;
3885	address = (caddr_t)VIDEOMEM;
3886    }
3887    else {
3888	font_buffer = font_14;
3889	address = (caddr_t)VIDEOMEM + 0x4000;
3890    }
3891
3892    if (scp->status & MOUSE_VISIBLE) {
3893	if ((scp->cursor_saveunder & 0xff) == 0xd0)
3894    	    bcopy(&scp->mouse_cursor[0], cursor, scp->font_size);
3895	else if ((scp->cursor_saveunder & 0xff) == 0xd1)
3896    	    bcopy(&scp->mouse_cursor[32], cursor, scp->font_size);
3897	else if ((scp->cursor_saveunder & 0xff) == 0xd2)
3898    	    bcopy(&scp->mouse_cursor[64], cursor, scp->font_size);
3899	else if ((scp->cursor_saveunder & 0xff) == 0xd3)
3900    	    bcopy(&scp->mouse_cursor[96], cursor, scp->font_size);
3901	else
3902	    bcopy(font_buffer+((scp->cursor_saveunder & 0xff)*scp->font_size),
3903 	       	   cursor, scp->font_size);
3904    }
3905    else
3906    	bcopy(font_buffer + ((scp->cursor_saveunder & 0xff) * scp->font_size),
3907 	       cursor, scp->font_size);
3908    for (i=0; i<32; i++)
3909	if ((i >= scp->cursor_start && i <= scp->cursor_end) ||
3910	    (scp->cursor_start >= scp->font_size && i == scp->font_size - 1))
3911	    cursor[i] |= 0xff;
3912#if 1
3913    while (!(inb(crtc_addr+6) & 0x08)) /* wait for vertical retrace */ ;
3914#endif
3915    set_font_mode();
3916    sc_bcopy(cursor, (char *)pa_to_va(address) + DEAD_CHAR * 32, 32);
3917    set_normal_mode();
3918}
3919
3920static void
3921set_mouse_pos(scr_stat *scp)
3922{
3923    static int last_xpos = -1, last_ypos = -1;
3924
3925    if (scp->mouse_xpos < 0)
3926	scp->mouse_xpos = 0;
3927    if (scp->mouse_ypos < 0)
3928	scp->mouse_ypos = 0;
3929    if (scp->status & UNKNOWN_MODE) {
3930        if (scp->mouse_xpos > scp->xpixel-1)
3931	    scp->mouse_xpos = scp->xpixel-1;
3932        if (scp->mouse_ypos > scp->ypixel-1)
3933	    scp->mouse_ypos = scp->ypixel-1;
3934	return;
3935    }
3936    if (scp->mouse_xpos > (scp->xsize*8)-1)
3937	scp->mouse_xpos = (scp->xsize*8)-1;
3938    if (scp->mouse_ypos > (scp->ysize*scp->font_size)-1)
3939	scp->mouse_ypos = (scp->ysize*scp->font_size)-1;
3940
3941    if (scp->mouse_xpos != last_xpos || scp->mouse_ypos != last_ypos) {
3942	scp->status |= MOUSE_MOVED;
3943
3944    	scp->mouse_pos = scp->scr_buf +
3945	    ((scp->mouse_ypos/scp->font_size)*scp->xsize + scp->mouse_xpos/8);
3946
3947	if ((scp->status & MOUSE_VISIBLE) && (scp->status & MOUSE_CUTTING)) {
3948	    u_short *ptr;
3949	    int i = 0;
3950
3951	    mark_for_update(scp, scp->mouse_cut_start - scp->scr_buf);
3952	    mark_for_update(scp, scp->mouse_cut_end - scp->scr_buf);
3953	    scp->mouse_cut_end = scp->mouse_pos;
3954	    for (ptr = (scp->mouse_cut_start > scp->mouse_cut_end
3955			? scp->mouse_cut_end : scp->mouse_cut_start);
3956		 ptr <= (scp->mouse_cut_start > scp->mouse_cut_end
3957			 ? scp->mouse_cut_start : scp->mouse_cut_end);
3958	    	 ptr++) {
3959	        cut_buffer[i++] = *ptr & 0xff;
3960	        if (((ptr - scp->scr_buf) % scp->xsize) == (scp->xsize - 1)) {
3961		    cut_buffer[i++] = '\n';
3962	        }
3963	    }
3964	    cut_buffer[i] = 0x00;
3965        }
3966    }
3967}
3968
3969static void
3970mouse_cut_start(scr_stat *scp)
3971{
3972    int i;
3973
3974    if (scp->status & MOUSE_VISIBLE) {
3975	if (scp->mouse_pos == scp->mouse_cut_start &&
3976	    scp->mouse_cut_start == scp->mouse_cut_end) {
3977	    cut_buffer[0] = 0x00;
3978	    remove_cutmarking(scp);
3979	}
3980	else {
3981	    scp->mouse_cut_start = scp->mouse_cut_end = scp->mouse_pos;
3982	    cut_buffer[0] = *scp->mouse_cut_start & 0xff;
3983	    cut_buffer[1] = 0x00;
3984	    scp->status |= MOUSE_CUTTING;
3985	}
3986    	mark_all(scp);
3987	/* delete all other screens cut markings */
3988	for (i=0; i<MAXCONS; i++) {
3989	    if (console[i] == NULL || console[i] == scp)
3990		continue;
3991	    remove_cutmarking(console[i]);
3992	}
3993    }
3994}
3995
3996static void
3997mouse_cut_end(scr_stat *scp)
3998{
3999    if (scp->status & MOUSE_VISIBLE) {
4000	scp->status &= ~MOUSE_CUTTING;
4001    }
4002}
4003
4004static void
4005mouse_paste(scr_stat *scp)
4006{
4007    if (scp->status & MOUSE_VISIBLE) {
4008	struct tty *tp;
4009	u_char *ptr = cut_buffer;
4010
4011	tp = VIRTUAL_TTY(get_scr_num());
4012	while (*ptr)
4013	    (*linesw[tp->t_line].l_rint)(scr_rmap[*ptr++], tp);
4014    }
4015}
4016
4017static void
4018draw_mouse_image(scr_stat *scp)
4019{
4020    caddr_t address;
4021    int i;
4022    char *font_buffer;
4023    u_short buffer[32];
4024    u_short xoffset, yoffset;
4025    u_short *crt_pos = Crtat + (scp->mouse_pos - scp->scr_buf);
4026    int font_size = scp->font_size;
4027
4028    if (font_size < 14) {
4029	font_buffer = font_8;
4030	address = (caddr_t)VIDEOMEM + 0x8000;
4031    }
4032    else if (font_size >= 16) {
4033	font_buffer = font_16;
4034	address = (caddr_t)VIDEOMEM;
4035    }
4036    else {
4037	font_buffer = font_14;
4038	address = (caddr_t)VIDEOMEM + 0x4000;
4039    }
4040    xoffset = scp->mouse_xpos % 8;
4041    yoffset = scp->mouse_ypos % font_size;
4042
4043    /* prepare mousepointer char's bitmaps */
4044    bcopy(font_buffer + ((*(scp->mouse_pos) & 0xff) * font_size),
4045	   &scp->mouse_cursor[0], font_size);
4046    bcopy(font_buffer + ((*(scp->mouse_pos+1) & 0xff) * font_size),
4047	   &scp->mouse_cursor[32], font_size);
4048    bcopy(font_buffer + ((*(scp->mouse_pos+scp->xsize) & 0xff) * font_size),
4049	   &scp->mouse_cursor[64], font_size);
4050    bcopy(font_buffer + ((*(scp->mouse_pos+scp->xsize+1) & 0xff) * font_size),
4051	   &scp->mouse_cursor[96], font_size);
4052    for (i=0; i<font_size; i++) {
4053	buffer[i] = scp->mouse_cursor[i]<<8 | scp->mouse_cursor[i+32];
4054	buffer[i+font_size]=scp->mouse_cursor[i+64]<<8|scp->mouse_cursor[i+96];
4055    }
4056
4057    /* now and-or in the mousepointer image */
4058    for (i=0; i<16; i++) {
4059	buffer[i+yoffset] =
4060	    ( buffer[i+yoffset] & ~(mouse_and_mask[i] >> xoffset))
4061	    | (mouse_or_mask[i] >> xoffset);
4062    }
4063    for (i=0; i<font_size; i++) {
4064	scp->mouse_cursor[i] = (buffer[i] & 0xff00) >> 8;
4065	scp->mouse_cursor[i+32] = buffer[i] & 0xff;
4066	scp->mouse_cursor[i+64] = (buffer[i+font_size] & 0xff00) >> 8;
4067	scp->mouse_cursor[i+96] = buffer[i+font_size] & 0xff;
4068    }
4069
4070    scp->mouse_oldpos = scp->mouse_pos;
4071
4072    /* wait for vertical retrace to avoid jitter on some videocards */
4073#if 1
4074    while (!(inb(crtc_addr+6) & 0x08)) /* idle */ ;
4075#endif
4076    set_font_mode();
4077    sc_bcopy(scp->mouse_cursor, (char *)pa_to_va(address) + 0xd0 * 32, 128);
4078    set_normal_mode();
4079    *(crt_pos) = (*(scp->mouse_pos)&0xff00)|0xd0;
4080    *(crt_pos+scp->xsize) = (*(scp->mouse_pos+scp->xsize)&0xff00)|0xd2;
4081    if (scp->mouse_xpos < (scp->xsize-1)*8) {
4082    	*(crt_pos+1) = (*(scp->mouse_pos+1)&0xff00)|0xd1;
4083    	*(crt_pos+scp->xsize+1) = (*(scp->mouse_pos+scp->xsize+1)&0xff00)|0xd3;
4084    }
4085    mark_for_update(scp, scp->mouse_pos - scp->scr_buf);
4086    mark_for_update(scp, scp->mouse_pos + scp->xsize + 1 - scp->scr_buf);
4087}
4088
4089static void
4090remove_mouse_image(scr_stat *scp)
4091{
4092    u_short *crt_pos = Crtat + (scp->mouse_oldpos - scp->scr_buf);
4093
4094    *(crt_pos) = *(scp->mouse_oldpos);
4095    *(crt_pos+1) = *(scp->mouse_oldpos+1);
4096    *(crt_pos+scp->xsize) = *(scp->mouse_oldpos+scp->xsize);
4097    *(crt_pos+scp->xsize+1) = *(scp->mouse_oldpos+scp->xsize+1);
4098    mark_for_update(scp, scp->mouse_oldpos - scp->scr_buf);
4099    mark_for_update(scp, scp->mouse_oldpos + scp->xsize + 1 - scp->scr_buf);
4100}
4101
4102static void
4103draw_cutmarking(scr_stat *scp)
4104{
4105    u_short *ptr;
4106    u_short och, nch;
4107
4108    for (ptr=scp->scr_buf; ptr<=(scp->scr_buf+(scp->xsize*scp->ysize)); ptr++) {
4109	nch = och = *(Crtat + (ptr - scp->scr_buf));
4110	/* are we outside the selected area ? */
4111	if ( ptr < (scp->mouse_cut_start > scp->mouse_cut_end ?
4112	            scp->mouse_cut_end : scp->mouse_cut_start) ||
4113	     ptr > (scp->mouse_cut_start > scp->mouse_cut_end ?
4114	            scp->mouse_cut_start : scp->mouse_cut_end)) {
4115	    if (ptr != scp->cursor_pos)
4116		nch = (och & 0xff) | (*ptr & 0xff00);
4117	}
4118	else {
4119	    /* are we clear of the cursor image ? */
4120	    if (ptr != scp->cursor_pos)
4121		nch = (och & 0x88ff) | (*ptr & 0x7000)>>4 | (*ptr & 0x0700)<<4;
4122	    else {
4123		if (flags & CHAR_CURSOR)
4124		    nch = (och & 0x88ff)|(*ptr & 0x7000)>>4|(*ptr & 0x0700)<<4;
4125		else
4126		    if (!(flags & BLINK_CURSOR))
4127		        nch = (och & 0xff) | (*ptr & 0xff00);
4128	    }
4129	}
4130	if (nch != och)
4131	    *(Crtat + (ptr - scp->scr_buf)) = nch;
4132    }
4133}
4134
4135static void
4136remove_cutmarking(scr_stat *scp)
4137{
4138    scp->mouse_cut_start = scp->mouse_cut_end = NULL;
4139    scp->status &= ~MOUSE_CUTTING;
4140    mark_all(scp);
4141}
4142
4143static void
4144save_palette(void)
4145{
4146    int i;
4147
4148    outb(PALRADR, 0x00);
4149    for (i=0x00; i<0x300; i++)
4150	palette[i] = inb(PALDATA);
4151    inb(crtc_addr+6);           /* reset flip/flop */
4152}
4153
4154void
4155load_palette(char *palette)
4156{
4157    int i;
4158
4159    outb(PIXMASK, 0xFF);            /* no pixelmask */
4160    outb(PALWADR, 0x00);
4161    for (i=0x00; i<0x300; i++)
4162	 outb(PALDATA, palette[i]);
4163    inb(crtc_addr+6);           /* reset flip/flop */
4164    outb(ATC, 0x20);            /* enable palette */
4165}
4166
4167static void
4168do_bell(scr_stat *scp, int pitch, int duration)
4169{
4170    if (flags & VISUAL_BELL) {
4171	if (blink_in_progress)
4172	    return;
4173	blink_in_progress = 4;
4174	if (scp != cur_console)
4175	    blink_in_progress += 2;
4176	blink_screen(cur_console);
4177    } else {
4178	if (scp != cur_console)
4179	    pitch *= 2;
4180	sysbeep(pitch, duration);
4181    }
4182}
4183
4184static void
4185blink_screen(void *arg)
4186{
4187    scr_stat *scp = arg;
4188
4189    if ((scp->status & UNKNOWN_MODE) || (blink_in_progress <= 1)) {
4190	blink_in_progress = FALSE;
4191    	mark_all(scp);
4192	if (delayed_next_scr)
4193	    switch_scr(scp, delayed_next_scr - 1);
4194    }
4195    else {
4196	if (blink_in_progress & 1)
4197	    fillw(kernel_default.std_color | scr_map[0x20],
4198		  Crtat, scp->xsize * scp->ysize);
4199	else
4200	    fillw(kernel_default.rev_color | scr_map[0x20],
4201		  Crtat, scp->xsize * scp->ysize);
4202	blink_in_progress--;
4203	timeout(blink_screen, scp, hz / 10);
4204    }
4205}
4206
4207#ifdef SC_SPLASH_SCREEN
4208static void
4209toggle_splash_screen(scr_stat *scp)
4210{
4211    static int toggle = 0;
4212    static u_char save_mode;
4213    int s;
4214
4215    if (video_mode_ptr == NULL)
4216	return;
4217
4218    s = splhigh();
4219    if (toggle) {
4220	scp->mode = save_mode;
4221	scp->status &= ~UNKNOWN_MODE;
4222	set_mode(scp);
4223	load_palette(palette);
4224	toggle = 0;
4225    }
4226    else {
4227	save_mode = scp->mode;
4228	scp->mode = M_VGA_CG320;
4229	scp->status |= UNKNOWN_MODE;
4230	set_mode(scp);
4231	/* load image */
4232	toggle = 1;
4233    }
4234    splx(s);
4235}
4236#endif
4237#endif /* NSC */
4238