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