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