syscons.c revision 29368
139232Sphk/*-
239232Sphk * Copyright (c) 1992-1997 S�ren Schmidt
339232Sphk * All rights reserved.
439232Sphk *
539232Sphk * Redistribution and use in source and binary forms, with or without
639232Sphk * modification, are permitted provided that the following conditions
739232Sphk * are met:
839232Sphk * 1. Redistributions of source code must retain the above copyright
939232Sphk *    notice, this list of conditions and the following disclaimer
1039232Sphk *    in this position and unchanged.
1139232Sphk * 2. Redistributions in binary form must reproduce the above copyright
1239232Sphk *    notice, this list of conditions and the following disclaimer in the
1339232Sphk *    documentation and/or other materials provided with the distribution.
1439232Sphk * 3. The name of the author may not be used to endorse or promote products
1539232Sphk *    derived from this software withough specific prior written permission
1639232Sphk *
1739232Sphk * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1839232Sphk * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1939232Sphk * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2039232Sphk * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
2139232Sphk * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2239232Sphk * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23119073Sobrien * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24119073Sobrien * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2539232Sphk * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2685473Sru * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 *  $Id: syscons.c,v 1.231 1997/09/04 23:01:03 yokota 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) {
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	    break;
2046#endif
2047	case 'c':   /* Clear screen & home */
2048	    clear_screen(scp);
2049	    break;
2050	}
2051    }
2052    else if (scp->term.esc == 2) {
2053	if (c >= '0' && c <= '9') {
2054	    if (scp->term.num_param < MAX_ESC_PAR) {
2055	    if (scp->term.last_param != scp->term.num_param) {
2056		scp->term.last_param = scp->term.num_param;
2057		scp->term.param[scp->term.num_param] = 0;
2058	    }
2059	    else
2060		scp->term.param[scp->term.num_param] *= 10;
2061	    scp->term.param[scp->term.num_param] += c - '0';
2062	    return;
2063	    }
2064	}
2065	scp->term.num_param = scp->term.last_param + 1;
2066	switch (c) {
2067
2068	case ';':
2069	    if (scp->term.num_param < MAX_ESC_PAR)
2070		return;
2071	    break;
2072
2073	case '=':
2074	    scp->term.esc = 3;
2075	    scp->term.last_param = -1;
2076	    for (i = scp->term.num_param; i < MAX_ESC_PAR; i++)
2077		scp->term.param[i] = 1;
2078	    scp->term.num_param = 0;
2079	    return;
2080
2081	case 'A':   /* up n rows */
2082	    n = scp->term.param[0]; if (n < 1) n = 1;
2083	    move_crsr(scp, scp->xpos, scp->ypos - n);
2084	    break;
2085
2086	case 'B':   /* down n rows */
2087	    n = scp->term.param[0]; if (n < 1) n = 1;
2088	    move_crsr(scp, scp->xpos, scp->ypos + n);
2089	    break;
2090
2091	case 'C':   /* right n columns */
2092	    n = scp->term.param[0]; if (n < 1) n = 1;
2093	    move_crsr(scp, scp->xpos + n, scp->ypos);
2094	    break;
2095
2096	case 'D':   /* left n columns */
2097	    n = scp->term.param[0]; if (n < 1) n = 1;
2098	    move_crsr(scp, scp->xpos - n, scp->ypos);
2099	    break;
2100
2101	case 'E':   /* cursor to start of line n lines down */
2102	    n = scp->term.param[0]; if (n < 1) n = 1;
2103	    move_crsr(scp, 0, scp->ypos + n);
2104	    break;
2105
2106	case 'F':   /* cursor to start of line n lines up */
2107	    n = scp->term.param[0]; if (n < 1) n = 1;
2108	    move_crsr(scp, 0, scp->ypos - n);
2109	    break;
2110
2111	case 'f':   /* Cursor move */
2112	case 'H':
2113	    if (scp->term.num_param == 0)
2114		move_crsr(scp, 0, 0);
2115	    else if (scp->term.num_param == 2)
2116		move_crsr(scp, scp->term.param[1] - 1, scp->term.param[0] - 1);
2117	    break;
2118
2119	case 'J':   /* Clear all or part of display */
2120	    if (scp->term.num_param == 0)
2121		n = 0;
2122	    else
2123		n = scp->term.param[0];
2124	    switch (n) {
2125	    case 0: /* clear form cursor to end of display */
2126		fillw(scp->term.cur_color | scr_map[0x20],
2127		      scp->cursor_pos,
2128		      scp->scr_buf + scp->xsize * scp->ysize - scp->cursor_pos);
2129    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2130    		mark_for_update(scp, scp->xsize * scp->ysize);
2131		remove_cutmarking(scp);
2132		break;
2133	    case 1: /* clear from beginning of display to cursor */
2134		fillw(scp->term.cur_color | scr_map[0x20],
2135		      scp->scr_buf,
2136		      scp->cursor_pos - scp->scr_buf);
2137    		mark_for_update(scp, 0);
2138    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2139		remove_cutmarking(scp);
2140		break;
2141	    case 2: /* clear entire display */
2142		fillw(scp->term.cur_color | scr_map[0x20], scp->scr_buf,
2143		      scp->xsize * scp->ysize);
2144		mark_all(scp);
2145		remove_cutmarking(scp);
2146		break;
2147	    }
2148	    break;
2149
2150	case 'K':   /* Clear all or part of line */
2151	    if (scp->term.num_param == 0)
2152		n = 0;
2153	    else
2154		n = scp->term.param[0];
2155	    switch (n) {
2156	    case 0: /* clear form cursor to end of line */
2157		fillw(scp->term.cur_color | scr_map[0x20],
2158		      scp->cursor_pos,
2159		      scp->xsize - scp->xpos);
2160    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2161    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf +
2162				scp->xsize - scp->xpos);
2163		break;
2164	    case 1: /* clear from beginning of line to cursor */
2165		fillw(scp->term.cur_color | scr_map[0x20],
2166		      scp->cursor_pos - scp->xpos,
2167		      scp->xpos + 1);
2168    		mark_for_update(scp, scp->ypos * scp->xsize);
2169    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2170		break;
2171	    case 2: /* clear entire line */
2172		fillw(scp->term.cur_color | scr_map[0x20],
2173		      scp->cursor_pos - scp->xpos,
2174		      scp->xsize);
2175    		mark_for_update(scp, scp->ypos * scp->xsize);
2176    		mark_for_update(scp, (scp->ypos + 1) * scp->xsize);
2177		break;
2178	    }
2179	    break;
2180
2181	case 'L':   /* Insert n lines */
2182	    n = scp->term.param[0]; if (n < 1) n = 1;
2183	    if (n > scp->ysize - scp->ypos)
2184		n = scp->ysize - scp->ypos;
2185	    src = scp->scr_buf + scp->ypos * scp->xsize;
2186	    dst = src + n * scp->xsize;
2187	    count = scp->ysize - (scp->ypos + n);
2188	    bcopy(src, dst, count * scp->xsize * sizeof(u_short));
2189	    fillw(scp->term.cur_color | scr_map[0x20], src,
2190		  n * scp->xsize);
2191	    mark_for_update(scp, scp->ypos * scp->xsize);
2192	    mark_for_update(scp, scp->xsize * scp->ysize);
2193	    break;
2194
2195	case 'M':   /* Delete n lines */
2196	    n = scp->term.param[0]; if (n < 1) n = 1;
2197	    if (n > scp->ysize - scp->ypos)
2198		n = scp->ysize - scp->ypos;
2199	    dst = scp->scr_buf + scp->ypos * scp->xsize;
2200	    src = dst + n * scp->xsize;
2201	    count = scp->ysize - (scp->ypos + n);
2202	    bcopy(src, dst, count * scp->xsize * sizeof(u_short));
2203	    src = dst + count * scp->xsize;
2204	    fillw(scp->term.cur_color | scr_map[0x20], src,
2205		  n * scp->xsize);
2206	    mark_for_update(scp, scp->ypos * scp->xsize);
2207	    mark_for_update(scp, scp->xsize * scp->ysize);
2208	    break;
2209
2210	case 'P':   /* Delete n chars */
2211	    n = scp->term.param[0]; if (n < 1) n = 1;
2212	    if (n > scp->xsize - scp->xpos)
2213		n = scp->xsize - scp->xpos;
2214	    dst = scp->cursor_pos;
2215	    src = dst + n;
2216	    count = scp->xsize - (scp->xpos + n);
2217	    bcopy(src, dst, count * sizeof(u_short));
2218	    src = dst + count;
2219	    fillw(scp->term.cur_color | scr_map[0x20], src, n);
2220	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2221	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n + count);
2222	    break;
2223
2224	case '@':   /* Insert n chars */
2225	    n = scp->term.param[0]; if (n < 1) n = 1;
2226	    if (n > scp->xsize - scp->xpos)
2227		n = scp->xsize - scp->xpos;
2228	    src = scp->cursor_pos;
2229	    dst = src + n;
2230	    count = scp->xsize - (scp->xpos + n);
2231	    bcopy(src, dst, count * sizeof(u_short));
2232	    fillw(scp->term.cur_color | scr_map[0x20], src, n);
2233	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2234	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n + count);
2235	    break;
2236
2237	case 'S':   /* scroll up n lines */
2238	    n = scp->term.param[0]; if (n < 1)  n = 1;
2239	    if (n > scp->ysize)
2240		n = scp->ysize;
2241	    bcopy(scp->scr_buf + (scp->xsize * n),
2242		   scp->scr_buf,
2243		   scp->xsize * (scp->ysize - n) * sizeof(u_short));
2244	    fillw(scp->term.cur_color | scr_map[0x20],
2245		  scp->scr_buf + scp->xsize * (scp->ysize - n),
2246		  scp->xsize * n);
2247    	    mark_all(scp);
2248	    break;
2249
2250	case 'T':   /* scroll down n lines */
2251	    n = scp->term.param[0]; if (n < 1)  n = 1;
2252	    if (n > scp->ysize)
2253		n = scp->ysize;
2254	    bcopy(scp->scr_buf,
2255		  scp->scr_buf + (scp->xsize * n),
2256		  scp->xsize * (scp->ysize - n) *
2257		  sizeof(u_short));
2258	    fillw(scp->term.cur_color | scr_map[0x20],
2259		  scp->scr_buf, scp->xsize * n);
2260    	    mark_all(scp);
2261	    break;
2262
2263	case 'X':   /* erase n characters in line */
2264	    n = scp->term.param[0]; if (n < 1)  n = 1;
2265	    if (n > scp->xsize - scp->xpos)
2266		n = scp->xsize - scp->xpos;
2267	    fillw(scp->term.cur_color | scr_map[0x20],
2268		  scp->cursor_pos, n);
2269	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2270	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n);
2271	    break;
2272
2273	case 'Z':   /* move n tabs backwards */
2274	    n = scp->term.param[0]; if (n < 1)  n = 1;
2275	    if ((i = scp->xpos & 0xf8) == scp->xpos)
2276		i -= 8*n;
2277	    else
2278		i -= 8*(n-1);
2279	    if (i < 0)
2280		i = 0;
2281	    move_crsr(scp, i, scp->ypos);
2282	    break;
2283
2284	case '`':   /* move cursor to column n */
2285	    n = scp->term.param[0]; if (n < 1)  n = 1;
2286	    move_crsr(scp, n - 1, scp->ypos);
2287	    break;
2288
2289	case 'a':   /* move cursor n columns to the right */
2290	    n = scp->term.param[0]; if (n < 1)  n = 1;
2291	    move_crsr(scp, scp->xpos + n, scp->ypos);
2292	    break;
2293
2294	case 'd':   /* move cursor to row n */
2295	    n = scp->term.param[0]; if (n < 1)  n = 1;
2296	    move_crsr(scp, scp->xpos, n - 1);
2297	    break;
2298
2299	case 'e':   /* move cursor n rows down */
2300	    n = scp->term.param[0]; if (n < 1)  n = 1;
2301	    move_crsr(scp, scp->xpos, scp->ypos + n);
2302	    break;
2303
2304	case 'm':   /* change attribute */
2305	    if (scp->term.num_param == 0) {
2306		scp->term.attr_mask = NORMAL_ATTR;
2307		scp->term.cur_attr =
2308		    scp->term.cur_color = scp->term.std_color;
2309		break;
2310	    }
2311	    for (i = 0; i < scp->term.num_param; i++) {
2312		switch (n = scp->term.param[i]) {
2313		case 0: /* back to normal */
2314		    scp->term.attr_mask = NORMAL_ATTR;
2315		    scp->term.cur_attr =
2316			scp->term.cur_color = scp->term.std_color;
2317		    break;
2318		case 1: /* bold */
2319		    scp->term.attr_mask |= BOLD_ATTR;
2320		    scp->term.cur_attr = mask2attr(&scp->term);
2321		    break;
2322		case 4: /* underline */
2323		    scp->term.attr_mask |= UNDERLINE_ATTR;
2324		    scp->term.cur_attr = mask2attr(&scp->term);
2325		    break;
2326		case 5: /* blink */
2327		    scp->term.attr_mask |= BLINK_ATTR;
2328		    scp->term.cur_attr = mask2attr(&scp->term);
2329		    break;
2330		case 7: /* reverse video */
2331		    scp->term.attr_mask |= REVERSE_ATTR;
2332		    scp->term.cur_attr = mask2attr(&scp->term);
2333		    break;
2334		case 30: case 31: /* set fg color */
2335		case 32: case 33: case 34:
2336		case 35: case 36: case 37:
2337		    scp->term.attr_mask |= FOREGROUND_CHANGED;
2338		    scp->term.cur_color =
2339			(scp->term.cur_color&0xF000) | (ansi_col[(n-30)&7]<<8);
2340		    scp->term.cur_attr = mask2attr(&scp->term);
2341		    break;
2342		case 40: case 41: /* set bg color */
2343		case 42: case 43: case 44:
2344		case 45: case 46: case 47:
2345		    scp->term.attr_mask |= BACKGROUND_CHANGED;
2346		    scp->term.cur_color =
2347			(scp->term.cur_color&0x0F00) | (ansi_col[(n-40)&7]<<12);
2348		    scp->term.cur_attr = mask2attr(&scp->term);
2349		    break;
2350		}
2351	    }
2352	    break;
2353
2354	case 's':   /* Save cursor position */
2355	    scp->saved_xpos = scp->xpos;
2356	    scp->saved_ypos = scp->ypos;
2357	    break;
2358
2359	case 'u':   /* Restore saved cursor position */
2360	    if (scp->saved_xpos >= 0 && scp->saved_ypos >= 0)
2361		move_crsr(scp, scp->saved_xpos, scp->saved_ypos);
2362	    break;
2363
2364	case 'x':
2365	    if (scp->term.num_param == 0)
2366		n = 0;
2367	    else
2368		n = scp->term.param[0];
2369	    switch (n) {
2370	    case 0:     /* reset attributes */
2371		scp->term.attr_mask = NORMAL_ATTR;
2372		scp->term.cur_attr =
2373		    scp->term.cur_color = scp->term.std_color =
2374		    current_default->std_color;
2375		scp->term.rev_color = current_default->rev_color;
2376		break;
2377	    case 1:     /* set ansi background */
2378		scp->term.attr_mask &= ~BACKGROUND_CHANGED;
2379		scp->term.cur_color = scp->term.std_color =
2380		    (scp->term.std_color & 0x0F00) |
2381		    (ansi_col[(scp->term.param[1])&0x0F]<<12);
2382		scp->term.cur_attr = mask2attr(&scp->term);
2383		break;
2384	    case 2:     /* set ansi foreground */
2385		scp->term.attr_mask &= ~FOREGROUND_CHANGED;
2386		scp->term.cur_color = scp->term.std_color =
2387		    (scp->term.std_color & 0xF000) |
2388		    (ansi_col[(scp->term.param[1])&0x0F]<<8);
2389		scp->term.cur_attr = mask2attr(&scp->term);
2390		break;
2391	    case 3:     /* set ansi attribute directly */
2392		scp->term.attr_mask &= ~(FOREGROUND_CHANGED|BACKGROUND_CHANGED);
2393		scp->term.cur_color = scp->term.std_color =
2394		    (scp->term.param[1]&0xFF)<<8;
2395		scp->term.cur_attr = mask2attr(&scp->term);
2396		break;
2397	    case 5:     /* set ansi reverse video background */
2398		scp->term.rev_color =
2399		    (scp->term.rev_color & 0x0F00) |
2400		    (ansi_col[(scp->term.param[1])&0x0F]<<12);
2401		scp->term.cur_attr = mask2attr(&scp->term);
2402		break;
2403	    case 6:     /* set ansi reverse video foreground */
2404		scp->term.rev_color =
2405		    (scp->term.rev_color & 0xF000) |
2406		    (ansi_col[(scp->term.param[1])&0x0F]<<8);
2407		scp->term.cur_attr = mask2attr(&scp->term);
2408		break;
2409	    case 7:     /* set ansi reverse video directly */
2410		scp->term.rev_color =
2411		    (scp->term.param[1]&0xFF)<<8;
2412		scp->term.cur_attr = mask2attr(&scp->term);
2413		break;
2414	    }
2415	    break;
2416
2417	case 'z':   /* switch to (virtual) console n */
2418	    if (scp->term.num_param == 1)
2419		switch_scr(scp, scp->term.param[0]);
2420	    break;
2421	}
2422    }
2423    else if (scp->term.esc == 3) {
2424	if (c >= '0' && c <= '9') {
2425	    if (scp->term.num_param < MAX_ESC_PAR) {
2426	    if (scp->term.last_param != scp->term.num_param) {
2427		scp->term.last_param = scp->term.num_param;
2428		scp->term.param[scp->term.num_param] = 0;
2429	    }
2430	    else
2431		scp->term.param[scp->term.num_param] *= 10;
2432	    scp->term.param[scp->term.num_param] += c - '0';
2433	    return;
2434	    }
2435	}
2436	scp->term.num_param = scp->term.last_param + 1;
2437	switch (c) {
2438
2439	case ';':
2440	    if (scp->term.num_param < MAX_ESC_PAR)
2441		return;
2442	    break;
2443
2444	case 'A':   /* set display border color */
2445	    if (scp->term.num_param == 1) {
2446		scp->border=scp->term.param[0] & 0xff;
2447		if (scp == cur_console)
2448		    set_border(scp->border);
2449            }
2450	    break;
2451
2452	case 'B':   /* set bell pitch and duration */
2453	    if (scp->term.num_param == 2) {
2454		scp->bell_pitch = scp->term.param[0];
2455		scp->bell_duration = scp->term.param[1]*10;
2456	    }
2457	    break;
2458
2459	case 'C':   /* set cursor type & shape */
2460	    if (scp->term.num_param == 1) {
2461		if (scp->term.param[0] & 0x01)
2462		    flags |= BLINK_CURSOR;
2463		else
2464		    flags &= ~BLINK_CURSOR;
2465		if ((scp->term.param[0] & 0x02) && crtc_vga)
2466		    flags |= CHAR_CURSOR;
2467		else
2468		    flags &= ~CHAR_CURSOR;
2469	    }
2470	    else if (scp->term.num_param == 2) {
2471		scp->cursor_start = scp->term.param[0] & 0x1F;
2472		scp->cursor_end = scp->term.param[1] & 0x1F;
2473	    }
2474	    /*
2475	     * The cursor shape is global property; all virtual consoles
2476	     * are affected. Update the cursor in the current console...
2477	     */
2478	    if (!(cur_console->status & UNKNOWN_MODE)) {
2479		remove_cursor_image(cur_console);
2480		if (crtc_vga && (flags & CHAR_CURSOR))
2481	            set_destructive_cursor(cur_console);
2482		draw_cursor_image(cur_console);
2483	    }
2484	    break;
2485
2486	case 'F':   /* set ansi foreground */
2487	    if (scp->term.num_param == 1) {
2488		scp->term.attr_mask &= ~FOREGROUND_CHANGED;
2489		scp->term.cur_color = scp->term.std_color =
2490		    (scp->term.std_color & 0xF000)
2491		    | ((scp->term.param[0] & 0x0F) << 8);
2492		scp->term.cur_attr = mask2attr(&scp->term);
2493	    }
2494	    break;
2495
2496	case 'G':   /* set ansi background */
2497	    if (scp->term.num_param == 1) {
2498		scp->term.attr_mask &= ~BACKGROUND_CHANGED;
2499		scp->term.cur_color = scp->term.std_color =
2500		    (scp->term.std_color & 0x0F00)
2501		    | ((scp->term.param[0] & 0x0F) << 12);
2502		scp->term.cur_attr = mask2attr(&scp->term);
2503	    }
2504	    break;
2505
2506	case 'H':   /* set ansi reverse video foreground */
2507	    if (scp->term.num_param == 1) {
2508		scp->term.rev_color =
2509		    (scp->term.rev_color & 0xF000)
2510		    | ((scp->term.param[0] & 0x0F) << 8);
2511		scp->term.cur_attr = mask2attr(&scp->term);
2512	    }
2513	    break;
2514
2515	case 'I':   /* set ansi reverse video background */
2516	    if (scp->term.num_param == 1) {
2517		scp->term.rev_color =
2518		    (scp->term.rev_color & 0x0F00)
2519		    | ((scp->term.param[0] & 0x0F) << 12);
2520		scp->term.cur_attr = mask2attr(&scp->term);
2521	    }
2522	    break;
2523	}
2524    }
2525    scp->term.esc = 0;
2526}
2527
2528static void
2529ansi_put(scr_stat *scp, u_char *buf, int len)
2530{
2531    u_char *ptr = buf;
2532
2533    /* make screensaver happy */
2534    if (scp == cur_console)
2535	scrn_time_stamp = mono_time.tv_sec;
2536
2537    write_in_progress++;
2538outloop:
2539    if (scp->term.esc) {
2540	scan_esc(scp, *ptr++);
2541	len--;
2542    }
2543    else if (PRINTABLE(*ptr)) {     /* Print only printables */
2544 	int cnt = len <= (scp->xsize-scp->xpos) ? len : (scp->xsize-scp->xpos);
2545 	u_short cur_attr = scp->term.cur_attr;
2546 	u_short *cursor_pos = scp->cursor_pos;
2547	do {
2548	    /*
2549	     * gcc-2.6.3 generates poor (un)sign extension code.  Casting the
2550	     * pointers in the following to volatile should have no effect,
2551	     * but in fact speeds up this inner loop from 26 to 18 cycles
2552	     * (+ cache misses) on i486's.
2553	     */
2554#define	UCVP(ucp)	((u_char volatile *)(ucp))
2555	    *cursor_pos++ = UCVP(scr_map)[*UCVP(ptr)] | cur_attr;
2556	    ptr++;
2557	    cnt--;
2558	} while (cnt && PRINTABLE(*ptr));
2559	len -= (cursor_pos - scp->cursor_pos);
2560	scp->xpos += (cursor_pos - scp->cursor_pos);
2561	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2562	mark_for_update(scp, cursor_pos - scp->scr_buf);
2563	scp->cursor_pos = cursor_pos;
2564	if (scp->xpos >= scp->xsize) {
2565	    scp->xpos = 0;
2566	    scp->ypos++;
2567	}
2568    }
2569    else  {
2570	switch(*ptr) {
2571	case 0x07:
2572	    do_bell(scp, scp->bell_pitch, scp->bell_duration);
2573	    break;
2574
2575	case 0x08:      /* non-destructive backspace */
2576	    if (scp->cursor_pos > scp->scr_buf) {
2577	    	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2578		scp->cursor_pos--;
2579	    	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2580		if (scp->xpos > 0)
2581		    scp->xpos--;
2582		else {
2583		    scp->xpos += scp->xsize - 1;
2584		    scp->ypos--;
2585		}
2586	    }
2587	    break;
2588
2589	case 0x09:  /* non-destructive tab */
2590	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2591	    scp->cursor_pos += (8 - scp->xpos % 8u);
2592	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2593	    if ((scp->xpos += (8 - scp->xpos % 8u)) >= scp->xsize) {
2594	        scp->xpos = 0;
2595	        scp->ypos++;
2596	    }
2597	    break;
2598
2599	case 0x0a:  /* newline, same pos */
2600	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2601	    scp->cursor_pos += scp->xsize;
2602	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2603	    scp->ypos++;
2604	    break;
2605
2606	case 0x0c:  /* form feed, clears screen */
2607	    clear_screen(scp);
2608	    break;
2609
2610	case 0x0d:  /* return, return to pos 0 */
2611	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2612	    scp->cursor_pos -= scp->xpos;
2613	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2614	    scp->xpos = 0;
2615	    break;
2616
2617	case 0x1b:  /* start escape sequence */
2618	    scp->term.esc = 1;
2619	    scp->term.num_param = 0;
2620	    break;
2621	}
2622	ptr++; len--;
2623    }
2624    /* do we have to scroll ?? */
2625    if (scp->cursor_pos >= scp->scr_buf + scp->ysize * scp->xsize) {
2626	remove_cutmarking(scp);
2627	if (scp->history) {
2628	    bcopy(scp->scr_buf, scp->history_head,
2629		   scp->xsize * sizeof(u_short));
2630	    scp->history_head += scp->xsize;
2631	    if (scp->history_head + scp->xsize >
2632		scp->history + scp->history_size)
2633		scp->history_head = scp->history;
2634	}
2635	bcopy(scp->scr_buf + scp->xsize, scp->scr_buf,
2636	       scp->xsize * (scp->ysize - 1) * sizeof(u_short));
2637	fillw(scp->term.cur_color | scr_map[0x20],
2638	      scp->scr_buf + scp->xsize * (scp->ysize - 1),
2639	      scp->xsize);
2640	scp->cursor_pos -= scp->xsize;
2641	scp->ypos--;
2642    	mark_all(scp);
2643    }
2644    if (len)
2645	goto outloop;
2646    write_in_progress--;
2647    if (delayed_next_scr)
2648	switch_scr(scp, delayed_next_scr - 1);
2649}
2650
2651static void
2652scinit(void)
2653{
2654    u_int hw_cursor;
2655    u_int i;
2656
2657    if (init_done != COLD)
2658	return;
2659    init_done = WARM;
2660
2661    /*
2662     * Ensure a zero start address.  This is mainly to recover after
2663     * switching from pcvt using userconfig().  The registers are w/o
2664     * for old hardware so it's too hard to relocate the active screen
2665     * memory.
2666     */
2667    outb(crtc_addr, 12);
2668    outb(crtc_addr + 1, 0);
2669    outb(crtc_addr, 13);
2670    outb(crtc_addr + 1, 0);
2671
2672    /* extract cursor location */
2673    outb(crtc_addr, 14);
2674    hw_cursor = inb(crtc_addr + 1) << 8;
2675    outb(crtc_addr, 15);
2676    hw_cursor |= inb(crtc_addr + 1);
2677
2678    /*
2679     * Validate cursor location.  It may be off the screen.  Then we must
2680     * not use it for the initial buffer offset.
2681     */
2682    if (hw_cursor >= ROW * COL)
2683	hw_cursor = (ROW - 1) * COL;
2684
2685    /* move hardware cursor out of the way */
2686    outb(crtc_addr, 14);
2687    outb(crtc_addr + 1, 0xff);
2688    outb(crtc_addr, 15);
2689    outb(crtc_addr + 1, 0xff);
2690
2691    /* set up the first console */
2692    current_default = &user_default;
2693    console[0] = &main_console;
2694    init_scp(console[0]);
2695    cur_console = console[0];
2696
2697    /* discard the video mode table if we are not familiar with it... */
2698    if (video_mode_ptr) {
2699        if (comp_vgaregs(vgaregs, video_mode_ptr + 64*console[0]->mode))
2700            video_mode_ptr = NULL;
2701    }
2702
2703    /* copy screen to temporary buffer */
2704    sc_bcopy(Crtat, sc_buffer,
2705	   console[0]->xsize * console[0]->ysize * sizeof(u_short));
2706
2707    console[0]->scr_buf = console[0]->mouse_pos = sc_buffer;
2708    console[0]->cursor_pos = console[0]->cursor_oldpos = sc_buffer + hw_cursor;
2709    console[0]->cursor_saveunder = *console[0]->cursor_pos;
2710    console[0]->xpos = hw_cursor % COL;
2711    console[0]->ypos = hw_cursor / COL;
2712    for (i=1; i<MAXCONS; i++)
2713	console[i] = NULL;
2714    kernel_console.esc = 0;
2715    kernel_console.attr_mask = NORMAL_ATTR;
2716    kernel_console.cur_attr =
2717	kernel_console.cur_color = kernel_console.std_color =
2718	kernel_default.std_color;
2719    kernel_console.rev_color = kernel_default.rev_color;
2720
2721    /* initialize mapscrn arrays to a one to one map */
2722    for (i=0; i<sizeof(scr_map); i++) {
2723	scr_map[i] = scr_rmap[i] = i;
2724    }
2725
2726    /* Save font and palette if VGA */
2727    if (crtc_vga) {
2728	if (fonts_loaded & FONT_16) {
2729		copy_font(LOAD, FONT_16, font_16);
2730	} else {
2731		copy_font(SAVE, FONT_16, font_16);
2732		fonts_loaded = FONT_16;
2733	}
2734	save_palette();
2735	set_destructive_cursor(console[0]);
2736    }
2737
2738#ifdef SC_SPLASH_SCREEN
2739    /*
2740     * Now put up a graphics image, and maybe cycle a
2741     * couble of palette entries for simple animation.
2742     */
2743    toggle_splash_screen(cur_console);
2744#endif
2745}
2746
2747static scr_stat
2748*alloc_scp()
2749{
2750    scr_stat *scp;
2751
2752    scp = (scr_stat *)malloc(sizeof(scr_stat), M_DEVBUF, M_WAITOK);
2753    init_scp(scp);
2754    scp->scr_buf = scp->cursor_pos = scp->cursor_oldpos =
2755	(u_short *)malloc(scp->xsize*scp->ysize*sizeof(u_short),
2756			  M_DEVBUF, M_WAITOK);
2757    scp->mouse_pos = scp->mouse_oldpos =
2758	scp->scr_buf + ((scp->mouse_ypos/scp->font_size)*scp->xsize +
2759			scp->mouse_xpos/8);
2760    scp->history_head = scp->history_pos = scp->history =
2761	(u_short *)malloc(scp->history_size*sizeof(u_short),
2762			  M_DEVBUF, M_WAITOK);
2763    bzero(scp->history_head, scp->history_size*sizeof(u_short));
2764/* SOS
2765    if (crtc_vga && video_mode_ptr)
2766	set_mode(scp);
2767*/
2768    clear_screen(scp);
2769    scp->cursor_saveunder = *scp->cursor_pos;
2770    return scp;
2771}
2772
2773static void
2774init_scp(scr_stat *scp)
2775{
2776    if (crtc_vga)
2777	if (crtc_addr == MONO_BASE)
2778	    scp->mode = M_VGA_M80x25;
2779	else
2780	    scp->mode = M_VGA_C80x25;
2781    else
2782	if (crtc_addr == MONO_BASE)
2783	    scp->mode = M_B80x25;
2784	else
2785	    scp->mode = M_C80x25;
2786
2787    scp->font_size = 16;
2788    scp->xsize = COL;
2789    scp->ysize = ROW;
2790    scp->xpos = scp->ypos = 0;
2791    scp->saved_xpos = scp->saved_ypos = -1;
2792    scp->start = scp->xsize * scp->ysize;
2793    scp->end = 0;
2794    scp->term.esc = 0;
2795    scp->term.attr_mask = NORMAL_ATTR;
2796    scp->term.cur_attr =
2797	scp->term.cur_color = scp->term.std_color =
2798	current_default->std_color;
2799    scp->term.rev_color = current_default->rev_color;
2800    scp->border = BG_BLACK;
2801    scp->cursor_start = *(char *)pa_to_va(0x461);
2802    scp->cursor_end = *(char *)pa_to_va(0x460);
2803    scp->mouse_xpos = scp->xsize*8/2;
2804    scp->mouse_ypos = scp->ysize*scp->font_size/2;
2805    scp->mouse_cut_start = scp->mouse_cut_end = NULL;
2806    scp->mouse_signal = 0;
2807    scp->mouse_pid = 0;
2808    scp->mouse_proc = NULL;
2809    scp->bell_pitch = BELL_PITCH;
2810    scp->bell_duration = BELL_DURATION;
2811    scp->status = (*(char *)pa_to_va(0x417) & 0x20) ? NLKED : 0;
2812    scp->status |= CURSOR_ENABLED;
2813    scp->pid = 0;
2814    scp->proc = NULL;
2815    scp->smode.mode = VT_AUTO;
2816    scp->history_head = scp->history_pos = scp->history = NULL;
2817    scp->history_size = max(HISTORY_SIZE, scp->xsize*scp->ysize);
2818}
2819
2820static u_char
2821*get_fstr(u_int c, u_int *len)
2822{
2823    u_int i;
2824
2825    if (!(c & FKEY))
2826	return(NULL);
2827    i = (c & 0xFF) - F_FN;
2828    if (i > n_fkey_tab)
2829	return(NULL);
2830    *len = fkey_tab[i].len;
2831    return(fkey_tab[i].str);
2832}
2833
2834static void
2835history_to_screen(scr_stat *scp)
2836{
2837    int i;
2838
2839    for (i=0; i<scp->ysize; i++)
2840	bcopy(scp->history + (((scp->history_pos - scp->history) +
2841	       scp->history_size-((i+1)*scp->xsize))%scp->history_size),
2842	       scp->scr_buf + (scp->xsize * (scp->ysize-1 - i)),
2843	       scp->xsize * sizeof(u_short));
2844    mark_all(scp);
2845}
2846
2847static int
2848history_up_line(scr_stat *scp)
2849{
2850    if (WRAPHIST(scp, scp->history_pos, -(scp->xsize*scp->ysize)) !=
2851	scp->history_head) {
2852	scp->history_pos = WRAPHIST(scp, scp->history_pos, -scp->xsize);
2853	history_to_screen(scp);
2854	return 0;
2855    }
2856    else
2857	return -1;
2858}
2859
2860static int
2861history_down_line(scr_stat *scp)
2862{
2863    if (scp->history_pos != scp->history_head) {
2864	scp->history_pos = WRAPHIST(scp, scp->history_pos, scp->xsize);
2865	history_to_screen(scp);
2866	return 0;
2867    }
2868    else
2869	return -1;
2870}
2871
2872/*
2873 * scgetc(flags) - get character from keyboard.
2874 * If flags & SCGETC_CN, then avoid harmful side effects.
2875 * If flags & SCGETC_NONBLOCK, then wait until a key is pressed, else
2876 * return NOKEY if there is nothing there.
2877 */
2878static u_int
2879scgetc(u_int flags)
2880{
2881    struct key_t *key;
2882    u_char scancode, keycode;
2883    u_int state, action;
2884    int c;
2885    static u_char esc_flag = 0, compose = 0;
2886    static u_int chr = 0;
2887
2888next_code:
2889    /* first see if there is something in the keyboard port */
2890    if (flags & SCGETC_NONBLOCK) {
2891	c = read_kbd_data_no_wait(sc_kbdc);
2892	if (c == -1)
2893	    return(NOKEY);
2894    } else {
2895	do {
2896	    c = read_kbd_data(sc_kbdc);
2897	} while(c == -1);
2898    }
2899    scancode = (u_char)c;
2900
2901    /* do the /dev/random device a favour */
2902    if (!(flags & SCGETC_CN))
2903	add_keyboard_randomness(scancode);
2904
2905    if (cur_console->status & KBD_RAW_MODE)
2906	return scancode;
2907
2908    keycode = scancode & 0x7F;
2909    switch (esc_flag) {
2910    case 0x00:      /* normal scancode */
2911	switch(scancode) {
2912	case 0xB8:  /* left alt (compose key) */
2913	    if (compose) {
2914		compose = 0;
2915		if (chr > 255) {
2916		    do_bell(cur_console,
2917			BELL_PITCH, BELL_DURATION);
2918		    chr = 0;
2919		}
2920	    }
2921	    break;
2922	case 0x38:
2923	    if (!compose) {
2924		compose = 1;
2925		chr = 0;
2926	    }
2927	    break;
2928	case 0xE0:
2929	case 0xE1:
2930	    esc_flag = scancode;
2931	    goto next_code;
2932	}
2933	break;
2934    case 0xE0:      /* 0xE0 prefix */
2935	esc_flag = 0;
2936	switch (keycode) {
2937	case 0x1C:  /* right enter key */
2938	    keycode = 0x59;
2939	    break;
2940	case 0x1D:  /* right ctrl key */
2941	    keycode = 0x5A;
2942	    break;
2943	case 0x35:  /* keypad divide key */
2944	    keycode = 0x5B;
2945	    break;
2946	case 0x37:  /* print scrn key */
2947	    keycode = 0x5C;
2948	    break;
2949	case 0x38:  /* right alt key (alt gr) */
2950	    keycode = 0x5D;
2951	    break;
2952	case 0x47:  /* grey home key */
2953	    keycode = 0x5E;
2954	    break;
2955	case 0x48:  /* grey up arrow key */
2956	    keycode = 0x5F;
2957	    break;
2958	case 0x49:  /* grey page up key */
2959	    keycode = 0x60;
2960	    break;
2961	case 0x4B:  /* grey left arrow key */
2962	    keycode = 0x61;
2963	    break;
2964	case 0x4D:  /* grey right arrow key */
2965	    keycode = 0x62;
2966	    break;
2967	case 0x4F:  /* grey end key */
2968	    keycode = 0x63;
2969	    break;
2970	case 0x50:  /* grey down arrow key */
2971	    keycode = 0x64;
2972	    break;
2973	case 0x51:  /* grey page down key */
2974	    keycode = 0x65;
2975	    break;
2976	case 0x52:  /* grey insert key */
2977	    keycode = 0x66;
2978	    break;
2979	case 0x53:  /* grey delete key */
2980	    keycode = 0x67;
2981	    break;
2982
2983	/* the following 3 are only used on the MS "Natural" keyboard */
2984	case 0x5b:  /* left Window key */
2985	    keycode = 0x69;
2986	    break;
2987	case 0x5c:  /* right Window key */
2988	    keycode = 0x6a;
2989	    break;
2990	case 0x5d:  /* menu key */
2991	    keycode = 0x6b;
2992	    break;
2993	default:    /* ignore everything else */
2994	    goto next_code;
2995	}
2996	break;
2997    case 0xE1:      /* 0xE1 prefix */
2998	esc_flag = 0;
2999	if (keycode == 0x1D)
3000	    esc_flag = 0x1D;
3001	goto next_code;
3002	/* NOT REACHED */
3003    case 0x1D:      /* pause / break */
3004	esc_flag = 0;
3005	if (keycode != 0x45)
3006	    goto next_code;
3007	keycode = 0x68;
3008	break;
3009    }
3010
3011    /* if scroll-lock pressed allow history browsing */
3012    if (cur_console->history && cur_console->status & SLKED) {
3013	int i;
3014
3015	cur_console->status &= ~CURSOR_ENABLED;
3016	if (!(cur_console->status & BUFFER_SAVED)) {
3017	    cur_console->status |= BUFFER_SAVED;
3018	    cur_console->history_save = cur_console->history_head;
3019
3020	    /* copy screen into top of history buffer */
3021	    for (i=0; i<cur_console->ysize; i++) {
3022		bcopy(cur_console->scr_buf + (cur_console->xsize * i),
3023		       cur_console->history_head,
3024		       cur_console->xsize * sizeof(u_short));
3025		cur_console->history_head += cur_console->xsize;
3026		if (cur_console->history_head + cur_console->xsize >
3027		    cur_console->history + cur_console->history_size)
3028		    cur_console->history_head=cur_console->history;
3029	    }
3030	    cur_console->history_pos = cur_console->history_head;
3031	    history_to_screen(cur_console);
3032	}
3033	switch (scancode) {
3034	case 0x47:  /* home key */
3035	    cur_console->history_pos = cur_console->history_head;
3036	    history_to_screen(cur_console);
3037	    goto next_code;
3038
3039	case 0x4F:  /* end key */
3040	    cur_console->history_pos =
3041		WRAPHIST(cur_console, cur_console->history_head,
3042			 cur_console->xsize*cur_console->ysize);
3043	    history_to_screen(cur_console);
3044	    goto next_code;
3045
3046	case 0x48:  /* up arrow key */
3047	    if (history_up_line(cur_console))
3048		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3049	    goto next_code;
3050
3051	case 0x50:  /* down arrow key */
3052	    if (history_down_line(cur_console))
3053		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3054	    goto next_code;
3055
3056	case 0x49:  /* page up key */
3057	    for (i=0; i<cur_console->ysize; i++)
3058	    if (history_up_line(cur_console)) {
3059		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3060		break;
3061	    }
3062	    goto next_code;
3063
3064	case 0x51:  /* page down key */
3065	    for (i=0; i<cur_console->ysize; i++)
3066	    if (history_down_line(cur_console)) {
3067		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3068		break;
3069	    }
3070	    goto next_code;
3071	}
3072    }
3073
3074    if (compose) {
3075	switch (scancode) {
3076	/* key pressed process it */
3077	case 0x47: case 0x48: case 0x49:    /* keypad 7,8,9 */
3078	    chr = (scancode - 0x40) + chr*10;
3079	    goto next_code;
3080	case 0x4B: case 0x4C: case 0x4D:    /* keypad 4,5,6 */
3081	    chr = (scancode - 0x47) + chr*10;
3082	    goto next_code;
3083	case 0x4F: case 0x50: case 0x51:    /* keypad 1,2,3 */
3084	    chr = (scancode - 0x4E) + chr*10;
3085	    goto next_code;
3086	case 0x52:              /* keypad 0 */
3087	    chr *= 10;
3088	    goto next_code;
3089
3090	/* key release, no interest here */
3091	case 0xC7: case 0xC8: case 0xC9:    /* keypad 7,8,9 */
3092	case 0xCB: case 0xCC: case 0xCD:    /* keypad 4,5,6 */
3093	case 0xCF: case 0xD0: case 0xD1:    /* keypad 1,2,3 */
3094	case 0xD2:              /* keypad 0 */
3095	    goto next_code;
3096
3097	case 0x38:              /* left alt key */
3098	    break;
3099	default:
3100	    if (chr) {
3101		compose = chr = 0;
3102		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3103		goto next_code;
3104	    }
3105	    break;
3106	}
3107    }
3108
3109    state = (shfts ? 1 : 0 ) | (2 * (ctls ? 1 : 0)) | (4 * (alts ? 1 : 0));
3110    if ((!agrs && (cur_console->status & ALKED))
3111	|| (agrs && !(cur_console->status & ALKED)))
3112	keycode += ALTGR_OFFSET;
3113    key = &key_map.key[keycode];
3114    if ( ((key->flgs & FLAG_LOCK_C) && (cur_console->status & CLKED))
3115	 || ((key->flgs & FLAG_LOCK_N) && (cur_console->status & NLKED)) )
3116	state ^= 1;
3117
3118    /* Check for make/break */
3119    action = key->map[state];
3120    if (scancode & 0x80) {      /* key released */
3121	if (key->spcl & (0x80>>state)) {
3122	    switch (action) {
3123	    case LSH:
3124		shfts &= ~1;
3125		break;
3126	    case RSH:
3127		shfts &= ~2;
3128		break;
3129	    case LCTR:
3130		ctls &= ~1;
3131		break;
3132	    case RCTR:
3133		ctls &= ~2;
3134		break;
3135	    case LALT:
3136		alts &= ~1;
3137		break;
3138	    case RALT:
3139		alts &= ~2;
3140		break;
3141	    case NLK:
3142		nlkcnt = 0;
3143		break;
3144	    case CLK:
3145		clkcnt = 0;
3146		break;
3147	    case SLK:
3148		slkcnt = 0;
3149		break;
3150	    case ASH:
3151		agrs = 0;
3152		break;
3153	    case ALK:
3154		alkcnt = 0;
3155		break;
3156	    case META:
3157		metas = 0;
3158		break;
3159	    }
3160	}
3161	if (chr && !compose) {
3162	    action = chr;
3163	    chr = 0;
3164	    return(action);
3165	}
3166    } else {
3167	/* key pressed */
3168	if (key->spcl & (0x80>>state)) {
3169	    switch (action) {
3170	    /* LOCKING KEYS */
3171	    case NLK:
3172#ifdef SC_SPLASH_SCREEN
3173		toggle_splash_screen(cur_console); /* SOS XXX */
3174#endif
3175		if (!nlkcnt) {
3176		    nlkcnt++;
3177		    if (cur_console->status & NLKED)
3178			cur_console->status &= ~NLKED;
3179		    else
3180			cur_console->status |= NLKED;
3181		    update_leds(cur_console->status);
3182		}
3183		break;
3184	    case CLK:
3185		if (!clkcnt) {
3186		    clkcnt++;
3187		    if (cur_console->status & CLKED)
3188			cur_console->status &= ~CLKED;
3189		    else
3190			cur_console->status |= CLKED;
3191		    update_leds(cur_console->status);
3192		}
3193		break;
3194	    case SLK:
3195		if (!slkcnt) {
3196		    slkcnt++;
3197		    if (cur_console->status & SLKED) {
3198			cur_console->status &= ~SLKED;
3199			if (cur_console->status & BUFFER_SAVED){
3200			    int i;
3201			    u_short *ptr = cur_console->history_save;
3202
3203			    for (i=0; i<cur_console->ysize; i++) {
3204				bcopy(ptr,
3205				       cur_console->scr_buf +
3206				       (cur_console->xsize*i),
3207				       cur_console->xsize * sizeof(u_short));
3208				ptr += cur_console->xsize;
3209				if (ptr + cur_console->xsize >
3210				    cur_console->history +
3211				    cur_console->history_size)
3212				    ptr = cur_console->history;
3213			    }
3214			    cur_console->status &= ~BUFFER_SAVED;
3215			    cur_console->history_head=cur_console->history_save;
3216			    cur_console->status |= CURSOR_ENABLED;
3217			    mark_all(cur_console);
3218			}
3219			scstart(VIRTUAL_TTY(get_scr_num()));
3220		    }
3221		    else
3222			cur_console->status |= SLKED;
3223		    update_leds(cur_console->status);
3224		}
3225		break;
3226	    case ALK:
3227		if (!alkcnt) {
3228		    alkcnt++;
3229		    if (cur_console->status & ALKED)
3230			cur_console->status &= ~ALKED;
3231		    else
3232			cur_console->status |= ALKED;
3233		    update_leds(cur_console->status);
3234		}
3235		break;
3236
3237	    /* NON-LOCKING KEYS */
3238	    case NOP:
3239		break;
3240	    case SPSC:
3241#ifdef SC_SPLASH_SCREEN
3242		toggle_splash_screen(cur_console);
3243#endif
3244		break;
3245	    case RBT:
3246		shutdown_nice();
3247		break;
3248	    case SUSP:
3249#if NAPM > 0
3250		apm_suspend();
3251#endif
3252		break;
3253
3254	    case DBG:
3255#ifdef DDB          /* try to switch to console 0 */
3256		if (cur_console->smode.mode == VT_AUTO &&
3257		    console[0]->smode.mode == VT_AUTO)
3258		    switch_scr(cur_console, 0);
3259		Debugger("manual escape to debugger");
3260#else
3261		printf("No debugger in kernel\n");
3262#endif
3263		break;
3264	    case LSH:
3265		shfts |= 1;
3266		break;
3267	    case RSH:
3268		shfts |= 2;
3269		break;
3270	    case LCTR:
3271		ctls |= 1;
3272		break;
3273	    case RCTR:
3274		ctls |= 2;
3275		break;
3276	    case LALT:
3277		alts |= 1;
3278		break;
3279	    case RALT:
3280		alts |= 2;
3281		break;
3282	    case ASH:
3283		agrs = 1;
3284		break;
3285	    case META:
3286		metas = 1;
3287		break;
3288	    case NEXT:
3289		{
3290		int next, this = get_scr_num();
3291		for (next = this+1; next != this; next = (next+1)%MAXCONS) {
3292		    struct tty *tp = VIRTUAL_TTY(next);
3293		    if (tp->t_state & TS_ISOPEN) {
3294			switch_scr(cur_console, next);
3295			break;
3296		    }
3297		}
3298		}
3299		break;
3300	    case BTAB:
3301		return(BKEY);
3302	    default:
3303		if (action >= F_SCR && action <= L_SCR) {
3304		    switch_scr(cur_console, action - F_SCR);
3305		    break;
3306		}
3307		if (action >= F_FN && action <= L_FN)
3308		    action |= FKEY;
3309		return(action);
3310	    }
3311	}
3312	else {
3313	    if (metas)
3314		action |= MKEY;
3315	    return(action);
3316	}
3317    }
3318    goto next_code;
3319}
3320
3321int
3322scmmap(dev_t dev, int offset, int nprot)
3323{
3324    if (offset > 0x20000 - PAGE_SIZE)
3325	return -1;
3326    return i386_btop((VIDEOMEM + offset));
3327}
3328
3329/*
3330 * Calculate hardware attributes word using logical attributes mask and
3331 * hardware colors
3332 */
3333
3334static int
3335mask2attr(struct term_stat *term)
3336{
3337    int attr, mask = term->attr_mask;
3338
3339    if (mask & REVERSE_ATTR) {
3340	attr = ((mask & FOREGROUND_CHANGED) ?
3341		((term->cur_color & 0xF000) >> 4) :
3342		(term->rev_color & 0x0F00)) |
3343	       ((mask & BACKGROUND_CHANGED) ?
3344		((term->cur_color & 0x0F00) << 4) :
3345		(term->rev_color & 0xF000));
3346    } else
3347	attr = term->cur_color;
3348
3349    /* XXX: underline mapping for Hercules adapter can be better */
3350    if (mask & (BOLD_ATTR | UNDERLINE_ATTR))
3351	attr ^= 0x0800;
3352    if (mask & BLINK_ATTR)
3353	attr ^= 0x8000;
3354
3355    return attr;
3356}
3357
3358static void
3359set_keyboard(int command, int data)
3360{
3361    int s;
3362    int c;
3363
3364    if (sc_kbdc == NULL)
3365	return;
3366
3367    /* prevent the timeout routine from polling the keyboard */
3368    if (!kbdc_lock(sc_kbdc, TRUE))
3369	return;
3370
3371    /* disable the keyboard and mouse interrupt */
3372    s = spltty();
3373#if 0
3374    c = get_controller_command_byte(sc_kbdc);
3375    if ((c == -1)
3376	|| !set_controller_command_byte(sc_kbdc,
3377            kbdc_get_device_mask(sc_kbdc),
3378            KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
3379                | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
3380	/* CONTROLLER ERROR */
3381        kbdc_lock(sc_kbdc, FALSE);
3382	splx(s);
3383	return;
3384    }
3385    /*
3386     * Now that the keyboard controller is told not to generate
3387     * the keyboard and mouse interrupts, call `splx()' to allow
3388     * the other tty interrupts. The clock interrupt may also occur,
3389     * but the timeout routine (`scrn_timer()') will be blocked
3390     * by the lock flag set via `kbdc_lock()'
3391     */
3392    splx(s);
3393#endif
3394
3395    if (send_kbd_command_and_data(sc_kbdc, command, data) != KBD_ACK)
3396        send_kbd_command(sc_kbdc, KBDC_ENABLE_KBD);
3397
3398#if 0
3399    /* restore the interrupts */
3400    if (!set_controller_command_byte(sc_kbdc,
3401            kbdc_get_device_mask(sc_kbdc),
3402	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
3403	/* CONTROLLER ERROR */
3404    }
3405#else
3406    splx(s);
3407#endif
3408    kbdc_lock(sc_kbdc, FALSE);
3409}
3410
3411static void
3412update_leds(int which)
3413{
3414    static u_char xlate_leds[8] = { 0, 4, 2, 6, 1, 5, 3, 7 };
3415
3416    /* replace CAPS led with ALTGR led for ALTGR keyboards */
3417    if (key_map.n_keys > ALTGR_OFFSET) {
3418	if (which & ALKED)
3419	    which |= CLKED;
3420	else
3421	    which &= ~CLKED;
3422    }
3423
3424    set_keyboard(KBDC_SET_LEDS, xlate_leds[which & LED_MASK]);
3425}
3426
3427void
3428set_mode(scr_stat *scp)
3429{
3430    char *modetable;
3431    char special_modetable[64];
3432
3433    if (scp != cur_console)
3434	return;
3435
3436    /* setup video hardware for the given mode */
3437    switch (scp->mode) {
3438    case M_VGA_M80x60:
3439	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3440	goto special_80x60;
3441
3442    case M_VGA_C80x60:
3443	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3444special_80x60:
3445	special_modetable[2]  = 0x08;
3446	special_modetable[19] = 0x47;
3447	goto special_480l;
3448
3449    case M_VGA_M80x30:
3450	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3451	goto special_80x30;
3452
3453    case M_VGA_C80x30:
3454	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3455special_80x30:
3456	special_modetable[19] = 0x4f;
3457special_480l:
3458	special_modetable[9] |= 0xc0;
3459	special_modetable[16] = 0x08;
3460	special_modetable[17] = 0x3e;
3461	special_modetable[26] = 0xea;
3462	special_modetable[28] = 0xdf;
3463	special_modetable[31] = 0xe7;
3464	special_modetable[32] = 0x04;
3465	modetable = special_modetable;
3466	goto setup_mode;
3467
3468    case M_ENH_B80x43:
3469	bcopy(video_mode_ptr+(64*M_ENH_B80x25), &special_modetable, 64);
3470	goto special_80x43;
3471
3472    case M_ENH_C80x43:
3473	bcopy(video_mode_ptr+(64*M_ENH_C80x25), &special_modetable, 64);
3474special_80x43:
3475	special_modetable[28] = 87;
3476	goto special_80x50;
3477
3478    case M_VGA_M80x50:
3479	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3480	goto special_80x50;
3481
3482    case M_VGA_C80x50:
3483	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3484special_80x50:
3485	special_modetable[2] = 8;
3486	special_modetable[19] = 7;
3487	modetable = special_modetable;
3488	goto setup_mode;
3489
3490    case M_VGA_C40x25: case M_VGA_C80x25:
3491    case M_VGA_M80x25:
3492    case M_B40x25:     case M_C40x25:
3493    case M_B80x25:     case M_C80x25:
3494    case M_ENH_B40x25: case M_ENH_C40x25:
3495    case M_ENH_B80x25: case M_ENH_C80x25:
3496    case M_EGAMONO80x25:
3497
3498	modetable = video_mode_ptr + (scp->mode * 64);
3499setup_mode:
3500	set_vgaregs(modetable);
3501	scp->font_size = *(modetable + 2);
3502
3503	/* set font type (size) */
3504	if (scp->font_size < 14) {
3505	    if (fonts_loaded & FONT_8)
3506		copy_font(LOAD, FONT_8, font_8);
3507	    outb(TSIDX, 0x03); outb(TSREG, 0x0A);   /* font 2 */
3508	} else if (scp->font_size >= 16) {
3509	    if (fonts_loaded & FONT_16)
3510		copy_font(LOAD, FONT_16, font_16);
3511	    outb(TSIDX, 0x03); outb(TSREG, 0x00);   /* font 0 */
3512	} else {
3513	    if (fonts_loaded & FONT_14)
3514		copy_font(LOAD, FONT_14, font_14);
3515	    outb(TSIDX, 0x03); outb(TSREG, 0x05);   /* font 1 */
3516	}
3517	if (flags & CHAR_CURSOR)
3518	    set_destructive_cursor(scp);
3519	mark_all(scp);
3520	break;
3521
3522    case M_VGA_MODEX:
3523	/* start out with std 320x200x256 mode */
3524	bcopy(video_mode_ptr+(64*M_VGA_CG320), &special_modetable, 64);
3525	/* "unchain" the VGA mode */
3526	special_modetable[5-1+0x04] &= 0xf7;
3527	special_modetable[5-1+0x04] |= 0x04;
3528	/* turn off doubleword mode */
3529	special_modetable[10+0x14] &= 0xbf;
3530	/* turn off word adressing */
3531	special_modetable[10+0x17] |= 0x40;
3532	/* set logical screen width */
3533	special_modetable[10+0x13] = 80;
3534	/* set 240 lines */
3535	special_modetable[10+0x11] = 0x2c;
3536	special_modetable[10+0x06] = 0x0d;
3537	special_modetable[10+0x07] = 0x3e;
3538	special_modetable[10+0x10] = 0xea;
3539	special_modetable[10+0x11] = 0xac;
3540	special_modetable[10+0x12] = 0xdf;
3541	special_modetable[10+0x15] = 0xe7;
3542	special_modetable[10+0x16] = 0x06;
3543	/* set vertical sync polarity to reflect aspect ratio */
3544	special_modetable[9] = 0xe3;
3545
3546	modetable = special_modetable;
3547	goto setup_grmode;
3548
3549    case M_BG320:     case M_CG320:     case M_BG640:
3550    case M_CG320_D:   case M_CG640_E:
3551    case M_CG640x350: case M_ENH_CG640:
3552    case M_BG640x480: case M_CG640x480: case M_VGA_CG320:
3553	modetable = video_mode_ptr + (scp->mode * 64);
3554setup_grmode:
3555	set_vgaregs(modetable);
3556	scp->font_size = FONT_NONE;
3557	break;
3558
3559    default:
3560	/* call user defined function XXX */
3561	break;
3562    }
3563
3564    /* set border color for this (virtual) console */
3565    set_border(scp->border);
3566    return;
3567}
3568
3569void
3570set_border(u_char color)
3571{
3572    switch (crtc_type) {
3573    case KD_EGA:
3574    case KD_VGA:
3575        inb(crtc_addr + 6);		/* reset flip-flop */
3576        outb(ATC, 0x11); outb(ATC, color);
3577        inb(crtc_addr + 6);		/* reset flip-flop */
3578        outb(ATC, 0x20);		/* enable Palette */
3579	break;
3580    case KD_CGA:
3581	outb(crtc_addr + 5, color & 0x0f); /* color select register */
3582	break;
3583    case KD_MONO:
3584    case KD_HERCULES:
3585    default:
3586	break;
3587    }
3588}
3589
3590static void
3591set_vgaregs(char *modetable)
3592{
3593    int i, s = splhigh();
3594
3595    outb(TSIDX, 0x00); outb(TSREG, 0x01);   	/* stop sequencer */
3596    outb(TSIDX, 0x07); outb(TSREG, 0x00);   	/* unlock registers */
3597    for (i=0; i<4; i++) {           		/* program sequencer */
3598	outb(TSIDX, i+1);
3599	outb(TSREG, modetable[i+5]);
3600    }
3601    outb(MISC, modetable[9]);       		/* set dot-clock */
3602    outb(TSIDX, 0x00); outb(TSREG, 0x03);   	/* start sequencer */
3603    outb(crtc_addr, 0x11);
3604    outb(crtc_addr+1, inb(crtc_addr+1) & 0x7F);
3605    for (i=0; i<25; i++) {          		/* program crtc */
3606	outb(crtc_addr, i);
3607	if (i == 14 || i == 15)     		/* no hardware cursor */
3608	    outb(crtc_addr+1, 0xff);
3609	else
3610	    outb(crtc_addr+1, modetable[i+10]);
3611    }
3612    inb(crtc_addr+6);           		/* reset flip-flop */
3613    for (i=0; i<20; i++) {          		/* program attribute ctrl */
3614	outb(ATC, i);
3615	outb(ATC, modetable[i+35]);
3616    }
3617    for (i=0; i<9; i++) {           		/* program graph data ctrl */
3618	outb(GDCIDX, i);
3619	outb(GDCREG, modetable[i+55]);
3620    }
3621    inb(crtc_addr+6);           		/* reset flip-flop */
3622    outb(ATC, 0x20);            		/* enable palette */
3623    splx(s);
3624}
3625
3626static void
3627read_vgaregs(char *buf)
3628{
3629    int i, j;
3630    int s;
3631
3632    bzero(buf, 64);
3633
3634    s = splhigh();
3635
3636    outb(TSIDX, 0x00); outb(TSREG, 0x01);   	/* stop sequencer */
3637    outb(TSIDX, 0x07); outb(TSREG, 0x00);   	/* unlock registers */
3638    for (i=0, j=5; i<4; i++) {
3639	outb(TSIDX, i+1);
3640	buf[j++] = inb(TSREG);
3641    }
3642    buf[9] = inb(MISC + 10);      		/* dot-clock */
3643    outb(TSIDX, 0x00); outb(TSREG, 0x03);   	/* start sequencer */
3644
3645    for (i=0, j=10; i<25; i++) {       		/* crtc */
3646	outb(crtc_addr, i);
3647	buf[j++] = inb(crtc_addr+1);
3648    }
3649    for (i=0, j=35; i<20; i++) {          	/* attribute ctrl */
3650        inb(crtc_addr+6);           		/* reset flip-flop */
3651	outb(ATC, i);
3652	buf[j++] = inb(ATC + 1);
3653    }
3654    for (i=0, j=55; i<9; i++) {           	/* graph data ctrl */
3655	outb(GDCIDX, i);
3656	buf[j++] = inb(GDCREG);
3657    }
3658    inb(crtc_addr+6);           		/* reset flip-flop */
3659    outb(ATC, 0x20);            		/* enable palette */
3660
3661    buf[0] = *(char *)pa_to_va(0x44a);		/* COLS */
3662    buf[1] = *(char *)pa_to_va(0x484);		/* ROWS */
3663    buf[2] = *(char *)pa_to_va(0x485);		/* POINTS */
3664    buf[3] = *(char *)pa_to_va(0x44c);
3665    buf[4] = *(char *)pa_to_va(0x44d);
3666
3667    splx(s);
3668}
3669
3670static int
3671comp_vgaregs(u_char *buf1, u_char *buf2)
3672{
3673    int i;
3674
3675    for(i = 0; i < 20; ++i) {
3676	if (*buf1++ != *buf2++)
3677	    return 1;
3678    }
3679    buf1 += 2;  /* skip the cursor shape */
3680    buf2 += 2;
3681    for(i = 22; i < 24; ++i) {
3682	if (*buf1++ != *buf2++)
3683	    return 1;
3684    }
3685    buf1 += 2;  /* skip the cursor position */
3686    buf2 += 2;
3687    for(i = 26; i < 64; ++i) {
3688	if (*buf1++ != *buf2++)
3689	    return 1;
3690    }
3691    return 0;
3692}
3693
3694static void
3695dump_vgaregs(u_char *buf)
3696{
3697    int i;
3698
3699    for(i = 0; i < 64;) {
3700	printf("%02x ", buf[i]);
3701	if ((++i % 16) == 0)
3702	    printf("\n");
3703    }
3704}
3705
3706static void
3707set_font_mode()
3708{
3709    int s = splhigh();
3710
3711    /* setup vga for loading fonts (graphics plane mode) */
3712    inb(crtc_addr+6);           		/* reset flip-flop */
3713    outb(ATC, 0x10); outb(ATC, 0x01);
3714    inb(crtc_addr+6);               		/* reset flip-flop */
3715    outb(ATC, 0x20);            		/* enable palette */
3716
3717#if SLOW_VGA
3718    outb(TSIDX, 0x02); outb(TSREG, 0x04);
3719    outb(TSIDX, 0x04); outb(TSREG, 0x06);
3720    outb(GDCIDX, 0x04); outb(GDCREG, 0x02);
3721    outb(GDCIDX, 0x05); outb(GDCREG, 0x00);
3722    outb(GDCIDX, 0x06); outb(GDCREG, 0x05);
3723#else
3724    outw(TSIDX, 0x0402);
3725    outw(TSIDX, 0x0604);
3726    outw(GDCIDX, 0x0204);
3727    outw(GDCIDX, 0x0005);
3728    outw(GDCIDX, 0x0506);               /* addr = a0000, 64kb */
3729#endif
3730    splx(s);
3731}
3732
3733static void
3734set_normal_mode()
3735{
3736    char *modetable;
3737    int s = splhigh();
3738
3739    switch (cur_console->mode) {
3740    case M_VGA_M80x60:
3741    case M_VGA_M80x50:
3742    case M_VGA_M80x30:
3743	modetable = video_mode_ptr + (64*M_VGA_M80x25);
3744	break;
3745
3746    case M_VGA_C80x60:
3747    case M_VGA_C80x50:
3748    case M_VGA_C80x30:
3749	modetable = video_mode_ptr + (64*M_VGA_C80x25);
3750	break;
3751
3752    case M_ENH_B80x43:
3753	modetable = video_mode_ptr + (64*M_ENH_B80x25);
3754	break;
3755
3756    case M_ENH_C80x43:
3757	modetable = video_mode_ptr + (64*M_ENH_C80x25);
3758	break;
3759
3760    case M_VGA_C40x25: case M_VGA_C80x25:
3761    case M_VGA_M80x25:
3762    case M_B40x25:     case M_C40x25:
3763    case M_B80x25:     case M_C80x25:
3764    case M_ENH_B40x25: case M_ENH_C40x25:
3765    case M_ENH_B80x25: case M_ENH_C80x25:
3766    case M_EGAMONO80x25:
3767
3768    case M_BG320:     case M_CG320:     case M_BG640:
3769    case M_CG320_D:   case M_CG640_E:
3770    case M_CG640x350: case M_ENH_CG640:
3771    case M_BG640x480: case M_CG640x480: case M_VGA_CG320:
3772	modetable = video_mode_ptr + (cur_console->mode * 64);
3773	break;
3774
3775    default:
3776	modetable = video_mode_ptr + (64*M_VGA_C80x25);
3777    }
3778
3779    if (video_mode_ptr == NULL)
3780	modetable = vgaregs;
3781
3782    /* setup vga for normal operation mode again */
3783    inb(crtc_addr+6);           		/* reset flip-flop */
3784    outb(ATC, 0x10); outb(ATC, modetable[0x10+35]);
3785    inb(crtc_addr+6);               		/* reset flip-flop */
3786    outb(ATC, 0x20);            		/* enable palette */
3787#if SLOW_VGA
3788    outb(TSIDX, 0x02); outb(TSREG, modetable[0x02+4]);
3789    outb(TSIDX, 0x04); outb(TSREG, modetable[0x04+4]);
3790    outb(GDCIDX, 0x04); outb(GDCREG, modetable[0x04+55]);
3791    outb(GDCIDX, 0x05); outb(GDCREG, modetable[0x05+55]);
3792    outb(GDCIDX, 0x06); outb(GDCREG, modetable[0x06+55]);
3793    if (crtc_addr == MONO_BASE) {
3794	outb(GDCIDX, 0x06); outb(GDCREG,(modetable[0x06+55] & 0x03) | 0x08);
3795    }
3796    else {
3797	outb(GDCIDX, 0x06); outb(GDCREG,(modetable[0x06+55] & 0x03) | 0x0c);
3798    }
3799#else
3800    outw(TSIDX, 0x0002 | (modetable[0x02+4]<<8));
3801    outw(TSIDX, 0x0004 | (modetable[0x04+4]<<8));
3802    outw(GDCIDX, 0x0004 | (modetable[0x04+55]<<8));
3803    outw(GDCIDX, 0x0005 | (modetable[0x05+55]<<8));
3804    if (crtc_addr == MONO_BASE)
3805        outw(GDCIDX, 0x0006 | (((modetable[0x06+55] & 0x03) | 0x08)<<8));
3806    else
3807        outw(GDCIDX, 0x0006 | (((modetable[0x06+55] & 0x03) | 0x0c)<<8));
3808#endif
3809    splx(s);
3810}
3811
3812void
3813copy_font(int operation, int font_type, char* font_image)
3814{
3815    int ch, line, segment, fontsize;
3816    u_char val;
3817
3818    /* dont mess with console we dont know video mode on */
3819    if (cur_console->status & UNKNOWN_MODE)
3820	return;
3821
3822    switch (font_type) {
3823    default:
3824    case FONT_8:
3825	segment = 0x8000;
3826	fontsize = 8;
3827	break;
3828    case FONT_14:
3829	segment = 0x4000;
3830	fontsize = 14;
3831	break;
3832    case FONT_16:
3833	segment = 0x0000;
3834	fontsize = 16;
3835	break;
3836    }
3837    outb(TSIDX, 0x01); val = inb(TSREG);        /* disable screen */
3838    outb(TSIDX, 0x01); outb(TSREG, val | 0x20);
3839    set_font_mode();
3840    for (ch=0; ch < 256; ch++)
3841	for (line=0; line < fontsize; line++)
3842	if (operation)
3843	    *(char *)pa_to_va(VIDEOMEM+(segment)+(ch*32)+line) =
3844		    font_image[(ch*fontsize)+line];
3845	else
3846	    font_image[(ch*fontsize)+line] =
3847	    *(char *)pa_to_va(VIDEOMEM+(segment)+(ch*32)+line);
3848    set_normal_mode();
3849    outb(TSIDX, 0x01); outb(TSREG, val & 0xDF); /* enable screen */
3850}
3851
3852static void
3853set_destructive_cursor(scr_stat *scp)
3854{
3855    u_char cursor[32];
3856    caddr_t address;
3857    int i;
3858    char *font_buffer;
3859
3860
3861    if (scp->font_size < 14) {
3862	font_buffer = font_8;
3863	address = (caddr_t)VIDEOMEM + 0x8000;
3864    }
3865    else if (scp->font_size >= 16) {
3866	font_buffer = font_16;
3867	address = (caddr_t)VIDEOMEM;
3868    }
3869    else {
3870	font_buffer = font_14;
3871	address = (caddr_t)VIDEOMEM + 0x4000;
3872    }
3873
3874    if (scp->status & MOUSE_VISIBLE) {
3875	if ((scp->cursor_saveunder & 0xff) == 0xd0)
3876    	    bcopy(&scp->mouse_cursor[0], cursor, scp->font_size);
3877	else if ((scp->cursor_saveunder & 0xff) == 0xd1)
3878    	    bcopy(&scp->mouse_cursor[32], cursor, scp->font_size);
3879	else if ((scp->cursor_saveunder & 0xff) == 0xd2)
3880    	    bcopy(&scp->mouse_cursor[64], cursor, scp->font_size);
3881	else if ((scp->cursor_saveunder & 0xff) == 0xd3)
3882    	    bcopy(&scp->mouse_cursor[96], cursor, scp->font_size);
3883	else
3884	    bcopy(font_buffer+((scp->cursor_saveunder & 0xff)*scp->font_size),
3885 	       	   cursor, scp->font_size);
3886    }
3887    else
3888    	bcopy(font_buffer + ((scp->cursor_saveunder & 0xff) * scp->font_size),
3889 	       cursor, scp->font_size);
3890    for (i=0; i<32; i++)
3891	if ((i >= scp->cursor_start && i <= scp->cursor_end) ||
3892	    (scp->cursor_start >= scp->font_size && i == scp->font_size - 1))
3893	    cursor[i] |= 0xff;
3894#if 1
3895    while (!(inb(crtc_addr+6) & 0x08)) /* wait for vertical retrace */ ;
3896#endif
3897    set_font_mode();
3898    sc_bcopy(cursor, (char *)pa_to_va(address) + DEAD_CHAR * 32, 32);
3899    set_normal_mode();
3900}
3901
3902static void
3903set_mouse_pos(scr_stat *scp)
3904{
3905    static int last_xpos = -1, last_ypos = -1;
3906
3907    if (scp->mouse_xpos < 0)
3908	scp->mouse_xpos = 0;
3909    if (scp->mouse_ypos < 0)
3910	scp->mouse_ypos = 0;
3911    if (scp->status & UNKNOWN_MODE) {
3912        if (scp->mouse_xpos > scp->xpixel-1)
3913	    scp->mouse_xpos = scp->xpixel-1;
3914        if (scp->mouse_ypos > scp->ypixel-1)
3915	    scp->mouse_ypos = scp->ypixel-1;
3916	return;
3917    }
3918    if (scp->mouse_xpos > (scp->xsize*8)-1)
3919	scp->mouse_xpos = (scp->xsize*8)-1;
3920    if (scp->mouse_ypos > (scp->ysize*scp->font_size)-1)
3921	scp->mouse_ypos = (scp->ysize*scp->font_size)-1;
3922
3923    if (scp->mouse_xpos != last_xpos || scp->mouse_ypos != last_ypos) {
3924	scp->status |= MOUSE_MOVED;
3925
3926    	scp->mouse_pos = scp->scr_buf +
3927	    ((scp->mouse_ypos/scp->font_size)*scp->xsize + scp->mouse_xpos/8);
3928
3929	if ((scp->status & MOUSE_VISIBLE) && (scp->status & MOUSE_CUTTING)) {
3930	    u_short *ptr;
3931	    int i = 0;
3932
3933	    mark_for_update(scp, scp->mouse_cut_start - scp->scr_buf);
3934	    mark_for_update(scp, scp->mouse_cut_end - scp->scr_buf);
3935	    scp->mouse_cut_end = scp->mouse_pos;
3936	    for (ptr = (scp->mouse_cut_start > scp->mouse_cut_end
3937			? scp->mouse_cut_end : scp->mouse_cut_start);
3938		 ptr <= (scp->mouse_cut_start > scp->mouse_cut_end
3939			 ? scp->mouse_cut_start : scp->mouse_cut_end);
3940	    	 ptr++) {
3941	        cut_buffer[i++] = *ptr & 0xff;
3942	        if (((ptr - scp->scr_buf) % scp->xsize) == (scp->xsize - 1)) {
3943		    cut_buffer[i++] = '\n';
3944	        }
3945	    }
3946	    cut_buffer[i] = 0x00;
3947        }
3948    }
3949}
3950
3951static void
3952mouse_cut_start(scr_stat *scp)
3953{
3954    int i;
3955
3956    if (scp->status & MOUSE_VISIBLE) {
3957	if (scp->mouse_pos == scp->mouse_cut_start &&
3958	    scp->mouse_cut_start == scp->mouse_cut_end) {
3959	    cut_buffer[0] = 0x00;
3960	    remove_cutmarking(scp);
3961	}
3962	else {
3963	    scp->mouse_cut_start = scp->mouse_cut_end = scp->mouse_pos;
3964	    cut_buffer[0] = *scp->mouse_cut_start & 0xff;
3965	    cut_buffer[1] = 0x00;
3966	    scp->status |= MOUSE_CUTTING;
3967	}
3968    	mark_all(scp);
3969	/* delete all other screens cut markings */
3970	for (i=0; i<MAXCONS; i++) {
3971	    if (console[i] == NULL || console[i] == scp)
3972		continue;
3973	    remove_cutmarking(console[i]);
3974	}
3975    }
3976}
3977
3978static void
3979mouse_cut_end(scr_stat *scp)
3980{
3981    if (scp->status & MOUSE_VISIBLE) {
3982	scp->status &= ~MOUSE_CUTTING;
3983    }
3984}
3985
3986static void
3987mouse_paste(scr_stat *scp)
3988{
3989    if (scp->status & MOUSE_VISIBLE) {
3990	struct tty *tp;
3991	u_char *ptr = cut_buffer;
3992
3993	tp = VIRTUAL_TTY(get_scr_num());
3994	while (*ptr)
3995	    (*linesw[tp->t_line].l_rint)(scr_rmap[*ptr++], tp);
3996    }
3997}
3998
3999static void
4000draw_mouse_image(scr_stat *scp)
4001{
4002    caddr_t address;
4003    int i;
4004    char *font_buffer;
4005    u_short buffer[32];
4006    u_short xoffset, yoffset;
4007    u_short *crt_pos = Crtat + (scp->mouse_pos - scp->scr_buf);
4008    int font_size = scp->font_size;
4009
4010    if (font_size < 14) {
4011	font_buffer = font_8;
4012	address = (caddr_t)VIDEOMEM + 0x8000;
4013    }
4014    else if (font_size >= 16) {
4015	font_buffer = font_16;
4016	address = (caddr_t)VIDEOMEM;
4017    }
4018    else {
4019	font_buffer = font_14;
4020	address = (caddr_t)VIDEOMEM + 0x4000;
4021    }
4022    xoffset = scp->mouse_xpos % 8;
4023    yoffset = scp->mouse_ypos % font_size;
4024
4025    /* prepare mousepointer char's bitmaps */
4026    bcopy(font_buffer + ((*(scp->mouse_pos) & 0xff) * font_size),
4027	   &scp->mouse_cursor[0], font_size);
4028    bcopy(font_buffer + ((*(scp->mouse_pos+1) & 0xff) * font_size),
4029	   &scp->mouse_cursor[32], font_size);
4030    bcopy(font_buffer + ((*(scp->mouse_pos+scp->xsize) & 0xff) * font_size),
4031	   &scp->mouse_cursor[64], font_size);
4032    bcopy(font_buffer + ((*(scp->mouse_pos+scp->xsize+1) & 0xff) * font_size),
4033	   &scp->mouse_cursor[96], font_size);
4034    for (i=0; i<font_size; i++) {
4035	buffer[i] = scp->mouse_cursor[i]<<8 | scp->mouse_cursor[i+32];
4036	buffer[i+font_size]=scp->mouse_cursor[i+64]<<8|scp->mouse_cursor[i+96];
4037    }
4038
4039    /* now and-or in the mousepointer image */
4040    for (i=0; i<16; i++) {
4041	buffer[i+yoffset] =
4042	    ( buffer[i+yoffset] & ~(mouse_and_mask[i] >> xoffset))
4043	    | (mouse_or_mask[i] >> xoffset);
4044    }
4045    for (i=0; i<font_size; i++) {
4046	scp->mouse_cursor[i] = (buffer[i] & 0xff00) >> 8;
4047	scp->mouse_cursor[i+32] = buffer[i] & 0xff;
4048	scp->mouse_cursor[i+64] = (buffer[i+font_size] & 0xff00) >> 8;
4049	scp->mouse_cursor[i+96] = buffer[i+font_size] & 0xff;
4050    }
4051
4052    scp->mouse_oldpos = scp->mouse_pos;
4053
4054    /* wait for vertical retrace to avoid jitter on some videocards */
4055#if 1
4056    while (!(inb(crtc_addr+6) & 0x08)) /* idle */ ;
4057#endif
4058    set_font_mode();
4059    sc_bcopy(scp->mouse_cursor, (char *)pa_to_va(address) + 0xd0 * 32, 128);
4060    set_normal_mode();
4061    *(crt_pos) = (*(scp->mouse_pos)&0xff00)|0xd0;
4062    *(crt_pos+scp->xsize) = (*(scp->mouse_pos+scp->xsize)&0xff00)|0xd2;
4063    if (scp->mouse_xpos < (scp->xsize-1)*8) {
4064    	*(crt_pos+1) = (*(scp->mouse_pos+1)&0xff00)|0xd1;
4065    	*(crt_pos+scp->xsize+1) = (*(scp->mouse_pos+scp->xsize+1)&0xff00)|0xd3;
4066    }
4067    mark_for_update(scp, scp->mouse_pos - scp->scr_buf);
4068    mark_for_update(scp, scp->mouse_pos + scp->xsize + 1 - scp->scr_buf);
4069}
4070
4071static void
4072remove_mouse_image(scr_stat *scp)
4073{
4074    u_short *crt_pos = Crtat + (scp->mouse_oldpos - scp->scr_buf);
4075
4076    *(crt_pos) = *(scp->mouse_oldpos);
4077    *(crt_pos+1) = *(scp->mouse_oldpos+1);
4078    *(crt_pos+scp->xsize) = *(scp->mouse_oldpos+scp->xsize);
4079    *(crt_pos+scp->xsize+1) = *(scp->mouse_oldpos+scp->xsize+1);
4080    mark_for_update(scp, scp->mouse_oldpos - scp->scr_buf);
4081    mark_for_update(scp, scp->mouse_oldpos + scp->xsize + 1 - scp->scr_buf);
4082}
4083
4084static void
4085draw_cutmarking(scr_stat *scp)
4086{
4087    u_short *ptr;
4088    u_short och, nch;
4089
4090    for (ptr=scp->scr_buf; ptr<=(scp->scr_buf+(scp->xsize*scp->ysize)); ptr++) {
4091	nch = och = *(Crtat + (ptr - scp->scr_buf));
4092	/* are we outside the selected area ? */
4093	if ( ptr < (scp->mouse_cut_start > scp->mouse_cut_end ?
4094	            scp->mouse_cut_end : scp->mouse_cut_start) ||
4095	     ptr > (scp->mouse_cut_start > scp->mouse_cut_end ?
4096	            scp->mouse_cut_start : scp->mouse_cut_end)) {
4097	    if (ptr != scp->cursor_pos)
4098		nch = (och & 0xff) | (*ptr & 0xff00);
4099	}
4100	else {
4101	    /* are we clear of the cursor image ? */
4102	    if (ptr != scp->cursor_pos)
4103		nch = (och & 0x88ff) | (*ptr & 0x7000)>>4 | (*ptr & 0x0700)<<4;
4104	    else {
4105		if (flags & CHAR_CURSOR)
4106		    nch = (och & 0x88ff)|(*ptr & 0x7000)>>4|(*ptr & 0x0700)<<4;
4107		else
4108		    if (!(flags & BLINK_CURSOR))
4109		        nch = (och & 0xff) | (*ptr & 0xff00);
4110	    }
4111	}
4112	if (nch != och)
4113	    *(Crtat + (ptr - scp->scr_buf)) = nch;
4114    }
4115}
4116
4117static void
4118remove_cutmarking(scr_stat *scp)
4119{
4120    scp->mouse_cut_start = scp->mouse_cut_end = NULL;
4121    scp->status &= ~MOUSE_CUTTING;
4122    mark_all(scp);
4123}
4124
4125static void
4126save_palette(void)
4127{
4128    int i;
4129
4130    outb(PALRADR, 0x00);
4131    for (i=0x00; i<0x300; i++)
4132	palette[i] = inb(PALDATA);
4133    inb(crtc_addr+6);           /* reset flip/flop */
4134}
4135
4136void
4137load_palette(char *palette)
4138{
4139    int i;
4140
4141    outb(PIXMASK, 0xFF);            /* no pixelmask */
4142    outb(PALWADR, 0x00);
4143    for (i=0x00; i<0x300; i++)
4144	 outb(PALDATA, palette[i]);
4145    inb(crtc_addr+6);           /* reset flip/flop */
4146    outb(ATC, 0x20);            /* enable palette */
4147}
4148
4149static void
4150do_bell(scr_stat *scp, int pitch, int duration)
4151{
4152    if (flags & VISUAL_BELL) {
4153	if (blink_in_progress)
4154	    return;
4155	blink_in_progress = 4;
4156	if (scp != cur_console)
4157	    blink_in_progress += 2;
4158	blink_screen(cur_console);
4159    } else {
4160	if (scp != cur_console)
4161	    pitch *= 2;
4162	sysbeep(pitch, duration);
4163    }
4164}
4165
4166static void
4167blink_screen(void *arg)
4168{
4169    scr_stat *scp = arg;
4170
4171    if ((scp->status & UNKNOWN_MODE) || (blink_in_progress <= 1)) {
4172	blink_in_progress = FALSE;
4173    	mark_all(scp);
4174	if (delayed_next_scr)
4175	    switch_scr(scp, delayed_next_scr - 1);
4176    }
4177    else {
4178	if (blink_in_progress & 1)
4179	    fillw(kernel_default.std_color | scr_map[0x20],
4180		  Crtat, scp->xsize * scp->ysize);
4181	else
4182	    fillw(kernel_default.rev_color | scr_map[0x20],
4183		  Crtat, scp->xsize * scp->ysize);
4184	blink_in_progress--;
4185	timeout(blink_screen, scp, hz / 10);
4186    }
4187}
4188
4189#ifdef SC_SPLASH_SCREEN
4190static void
4191toggle_splash_screen(scr_stat *scp)
4192{
4193    static int toggle = 0;
4194    static u_char save_mode;
4195    int s;
4196
4197    if (video_mode_ptr == NULL)
4198	return;
4199
4200    s = splhigh();
4201    if (toggle) {
4202	scp->mode = save_mode;
4203	scp->status &= ~UNKNOWN_MODE;
4204	set_mode(scp);
4205	load_palette(palette);
4206	toggle = 0;
4207    }
4208    else {
4209	save_mode = scp->mode;
4210	scp->mode = M_VGA_CG320;
4211	scp->status |= UNKNOWN_MODE;
4212	set_mode(scp);
4213	/* load image */
4214	toggle = 1;
4215    }
4216    splx(s);
4217}
4218#endif
4219#endif /* NSC */
4220