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