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