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