syscons.c revision 28022
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.229 1997/08/08 22:52:30 sos 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	    if (cur_console->mouse_signal) {
1055		cur_console->mouse_buttons = mouse->u.data.buttons;
1056    		/* has controlling process died? */
1057		if (cur_console->mouse_proc &&
1058		    (cur_console->mouse_proc != pfind(cur_console->mouse_pid))){
1059		    	cur_console->mouse_signal = 0;
1060			cur_console->mouse_proc = NULL;
1061			cur_console->mouse_pid = 0;
1062		}
1063		else
1064		    psignal(cur_console->mouse_proc, cur_console->mouse_signal);
1065	    }
1066	    else {
1067		/* process button presses */
1068		if (cur_console->mouse_buttons != mouse->u.data.buttons) {
1069		    cur_console->mouse_buttons = mouse->u.data.buttons;
1070		    if (!(cur_console->status & UNKNOWN_MODE)) {
1071			if (cur_console->mouse_buttons & LEFT_BUTTON)
1072			    mouse_cut_start(cur_console);
1073			else
1074			    mouse_cut_end(cur_console);
1075			if (cur_console->mouse_buttons & RIGHT_BUTTON ||
1076			    cur_console->mouse_buttons & MIDDLE_BUTTON)
1077			    mouse_paste(cur_console);
1078		    }
1079		}
1080	    }
1081	    if (mouse->u.data.x != 0 || mouse->u.data.y != 0) {
1082	    	cur_console->mouse_xpos += mouse->u.data.x;
1083	    	cur_console->mouse_ypos += mouse->u.data.y;
1084		set_mouse_pos(cur_console);
1085	    }
1086	    break;
1087
1088	default:
1089	    return EINVAL;
1090	}
1091	/* make screensaver happy */
1092	scrn_time_stamp = mono_time.tv_sec;
1093	return 0;
1094    }
1095
1096    case CONS_GETINFO:  	/* get current (virtual) console info */
1097    {
1098	vid_info_t *ptr = (vid_info_t*)data;
1099	if (ptr->size == sizeof(struct vid_info)) {
1100	    ptr->m_num = get_scr_num();
1101	    ptr->mv_col = scp->xpos;
1102	    ptr->mv_row = scp->ypos;
1103	    ptr->mv_csz = scp->xsize;
1104	    ptr->mv_rsz = scp->ysize;
1105	    ptr->mv_norm.fore = (scp->term.std_color & 0x0f00)>>8;
1106	    ptr->mv_norm.back = (scp->term.std_color & 0xf000)>>12;
1107	    ptr->mv_rev.fore = (scp->term.rev_color & 0x0f00)>>8;
1108	    ptr->mv_rev.back = (scp->term.rev_color & 0xf000)>>12;
1109	    ptr->mv_grfc.fore = 0;      /* not supported */
1110	    ptr->mv_grfc.back = 0;      /* not supported */
1111	    ptr->mv_ovscan = scp->border;
1112	    ptr->mk_keylock = scp->status & LOCK_KEY_MASK;
1113	    return 0;
1114	}
1115	return EINVAL;
1116    }
1117
1118    case CONS_GETVERS:  	/* get version number */
1119	*(int*)data = 0x200;    /* version 2.0 */
1120	return 0;
1121
1122    /* VGA TEXT MODES */
1123    case SW_VGA_C40x25:
1124    case SW_VGA_C80x25: case SW_VGA_M80x25:
1125    case SW_VGA_C80x30: case SW_VGA_M80x30:
1126    case SW_VGA_C80x50: case SW_VGA_M80x50:
1127    case SW_VGA_C80x60: case SW_VGA_M80x60:
1128    case SW_B40x25:     case SW_C40x25:
1129    case SW_B80x25:     case SW_C80x25:
1130    case SW_ENH_B40x25: case SW_ENH_C40x25:
1131    case SW_ENH_B80x25: case SW_ENH_C80x25:
1132    case SW_ENH_B80x43: case SW_ENH_C80x43:
1133    case SW_EGAMONO80x25:
1134
1135	if (!crtc_vga || video_mode_ptr == NULL)
1136	    return ENXIO;
1137	switch (cmd & 0xff) {
1138	case M_VGA_C80x60: case M_VGA_M80x60:
1139	    if (!(fonts_loaded & FONT_8))
1140		return EINVAL;
1141	    scp->xsize = 80;
1142	    scp->ysize = 60;
1143	    break;
1144	case M_VGA_C80x50: case M_VGA_M80x50:
1145	    if (!(fonts_loaded & FONT_8))
1146		return EINVAL;
1147	    scp->xsize = 80;
1148	    scp->ysize = 50;
1149	    break;
1150	case M_ENH_B80x43: case M_ENH_C80x43:
1151	    if (!(fonts_loaded & FONT_8))
1152		return EINVAL;
1153	    scp->xsize = 80;
1154	    scp->ysize = 43;
1155	    break;
1156	case M_VGA_C80x30: case M_VGA_M80x30:
1157	    scp->xsize = 80;
1158	    scp->ysize = 30;
1159	    break;
1160	case M_ENH_C40x25: case M_ENH_B40x25:
1161	case M_ENH_C80x25: case M_ENH_B80x25:
1162	case M_EGAMONO80x25:
1163	    if (!(fonts_loaded & FONT_14))
1164		return EINVAL;
1165	    /* FALL THROUGH */
1166	default:
1167	    if ((cmd & 0xff) > M_VGA_CG320)
1168		return EINVAL;
1169	    else
1170		scp->xsize = *(video_mode_ptr+((cmd&0xff)*64));
1171		scp->ysize = *(video_mode_ptr+((cmd&0xff)*64)+1)+1;
1172	    break;
1173	}
1174	scp->mode = cmd & 0xff;
1175	free(scp->scr_buf, M_DEVBUF);
1176	scp->scr_buf = (u_short *)
1177	    malloc(scp->xsize*scp->ysize*sizeof(u_short), M_DEVBUF, M_WAITOK);
1178    	scp->cursor_pos = scp->cursor_oldpos =
1179	    scp->scr_buf + scp->xpos + scp->ypos * scp->xsize;
1180    	scp->mouse_pos = scp->mouse_oldpos =
1181	    scp->scr_buf + ((scp->mouse_ypos/scp->font_size)*scp->xsize +
1182	    scp->mouse_xpos/8);
1183	free(cut_buffer, M_DEVBUF);
1184    	cut_buffer = (char *)malloc(scp->xsize*scp->ysize, M_DEVBUF, M_NOWAIT);
1185	cut_buffer[0] = 0x00;
1186	if (scp == cur_console)
1187	    set_mode(scp);
1188	scp->status &= ~UNKNOWN_MODE;
1189	clear_screen(scp);
1190	if (tp->t_winsize.ws_col != scp->xsize
1191	    || tp->t_winsize.ws_row != scp->ysize) {
1192	    tp->t_winsize.ws_col = scp->xsize;
1193	    tp->t_winsize.ws_row = scp->ysize;
1194	    pgsignal(tp->t_pgrp, SIGWINCH, 1);
1195	}
1196	return 0;
1197
1198    /* GRAPHICS MODES */
1199    case SW_BG320:     case SW_BG640:
1200    case SW_CG320:     case SW_CG320_D:   case SW_CG640_E:
1201    case SW_CG640x350: case SW_ENH_CG640:
1202    case SW_BG640x480: case SW_CG640x480: case SW_VGA_CG320:
1203
1204	if (!crtc_vga || video_mode_ptr == NULL)
1205	    return ENXIO;
1206	scp->mode = cmd & 0xFF;
1207	scp->xpixel = (*(video_mode_ptr + (scp->mode*64))) * 8;
1208	scp->ypixel = (*(video_mode_ptr + (scp->mode*64) + 1) + 1) *
1209		     (*(video_mode_ptr + (scp->mode*64) + 2));
1210	if (scp == cur_console)
1211	    set_mode(scp);
1212	scp->status |= UNKNOWN_MODE;    /* graphics mode */
1213	/* clear_graphics();*/
1214
1215	if (tp->t_winsize.ws_xpixel != scp->xpixel
1216	    || tp->t_winsize.ws_ypixel != scp->ypixel) {
1217	    tp->t_winsize.ws_xpixel = scp->xpixel;
1218	    tp->t_winsize.ws_ypixel = scp->ypixel;
1219	    pgsignal(tp->t_pgrp, SIGWINCH, 1);
1220	}
1221	return 0;
1222
1223    case SW_VGA_MODEX:
1224	if (!crtc_vga || video_mode_ptr == NULL)
1225	    return ENXIO;
1226	scp->mode = cmd & 0xFF;
1227	if (scp == cur_console)
1228	    set_mode(scp);
1229	scp->status |= UNKNOWN_MODE;    /* graphics mode */
1230	/* clear_graphics();*/
1231	scp->xpixel = 320;
1232	scp->ypixel = 240;
1233	if (tp->t_winsize.ws_xpixel != scp->xpixel
1234	    || tp->t_winsize.ws_ypixel != scp->ypixel) {
1235	    tp->t_winsize.ws_xpixel = scp->xpixel;
1236	    tp->t_winsize.ws_ypixel = scp->ypixel;
1237	    pgsignal(tp->t_pgrp, SIGWINCH, 1);
1238	}
1239	return 0;
1240
1241    case VT_SETMODE:    	/* set screen switcher mode */
1242    {
1243	struct vt_mode *mode;
1244
1245	mode = (struct vt_mode *)data;
1246	if (ISSIGVALID(mode->relsig) && ISSIGVALID(mode->acqsig) &&
1247	    ISSIGVALID(mode->frsig)) {
1248	    bcopy(data, &scp->smode, sizeof(struct vt_mode));
1249	    if (scp->smode.mode == VT_PROCESS) {
1250		scp->proc = p;
1251		scp->pid = scp->proc->p_pid;
1252	    }
1253	    return 0;
1254	} else
1255	    return EINVAL;
1256    }
1257
1258    case VT_GETMODE:    	/* get screen switcher mode */
1259	bcopy(&scp->smode, data, sizeof(struct vt_mode));
1260	return 0;
1261
1262    case VT_RELDISP:    	/* screen switcher ioctl */
1263	switch(*data) {
1264	case VT_FALSE:  	/* user refuses to release screen, abort */
1265	    if (scp == old_scp && (scp->status & SWITCH_WAIT_REL)) {
1266		old_scp->status &= ~SWITCH_WAIT_REL;
1267		switch_in_progress = FALSE;
1268		return 0;
1269	    }
1270	    return EINVAL;
1271
1272	case VT_TRUE:   	/* user has released screen, go on */
1273	    if (scp == old_scp && (scp->status & SWITCH_WAIT_REL)) {
1274		scp->status &= ~SWITCH_WAIT_REL;
1275		exchange_scr();
1276		if (new_scp->smode.mode == VT_PROCESS) {
1277		    new_scp->status |= SWITCH_WAIT_ACQ;
1278		    psignal(new_scp->proc, new_scp->smode.acqsig);
1279		}
1280		else
1281		    switch_in_progress = FALSE;
1282		return 0;
1283	    }
1284	    return EINVAL;
1285
1286	case VT_ACKACQ: 	/* acquire acknowledged, switch completed */
1287	    if (scp == new_scp && (scp->status & SWITCH_WAIT_ACQ)) {
1288		scp->status &= ~SWITCH_WAIT_ACQ;
1289		switch_in_progress = FALSE;
1290		return 0;
1291	    }
1292	    return EINVAL;
1293
1294	default:
1295	    return EINVAL;
1296	}
1297	/* NOT REACHED */
1298
1299    case VT_OPENQRY:    	/* return free virtual console */
1300	for (i = 0; i < MAXCONS; i++) {
1301	    tp = VIRTUAL_TTY(i);
1302	    if (!(tp->t_state & TS_ISOPEN)) {
1303		*data = i + 1;
1304		return 0;
1305	    }
1306	}
1307	return EINVAL;
1308
1309    case VT_ACTIVATE:   	/* switch to screen *data */
1310	return switch_scr(scp, (*data) - 1);
1311
1312    case VT_WAITACTIVE: 	/* wait for switch to occur */
1313	if (*data > MAXCONS || *data < 0)
1314	    return EINVAL;
1315	if (minor(dev) == (*data) - 1)
1316	    return 0;
1317	if (*data == 0) {
1318	    if (scp == cur_console)
1319		return 0;
1320	}
1321	else
1322	    scp = console[(*data) - 1];
1323	while ((error=tsleep((caddr_t)&scp->smode, PZERO|PCATCH,
1324			     "waitvt", 0)) == ERESTART) ;
1325	return error;
1326
1327    case VT_GETACTIVE:
1328	*data = get_scr_num()+1;
1329	return 0;
1330
1331    case KDENABIO:      	/* allow io operations */
1332	error = suser(p->p_ucred, &p->p_acflag);
1333	if (error != 0)
1334	    return error;
1335	if (securelevel > 0)
1336	    return EPERM;
1337	p->p_md.md_regs->tf_eflags |= PSL_IOPL;
1338	return 0;
1339
1340    case KDDISABIO:     	/* disallow io operations (default) */
1341	p->p_md.md_regs->tf_eflags &= ~PSL_IOPL;
1342	return 0;
1343
1344    case KDSETMODE:     	/* set current mode of this (virtual) console */
1345	switch (*data) {
1346	case KD_TEXT:   	/* switch to TEXT (known) mode */
1347	    /* restore fonts & palette ! */
1348	    if (crtc_vga) {
1349		if (fonts_loaded & FONT_8)
1350		    copy_font(LOAD, FONT_8, font_8);
1351		if (fonts_loaded & FONT_14)
1352		    copy_font(LOAD, FONT_14, font_14);
1353		if (fonts_loaded & FONT_16)
1354		    copy_font(LOAD, FONT_16, font_16);
1355		load_palette(palette);
1356	    }
1357	    /* FALL THROUGH */
1358
1359	case KD_TEXT1:  	/* switch to TEXT (known) mode */
1360	    /* no restore fonts & palette */
1361	    if (crtc_vga && video_mode_ptr)
1362		set_mode(scp);
1363	    scp->status &= ~UNKNOWN_MODE;
1364	    clear_screen(scp);
1365	    return 0;
1366
1367	case KD_GRAPHICS:	/* switch to GRAPHICS (unknown) mode */
1368	    scp->status |= UNKNOWN_MODE;
1369	    return 0;
1370	default:
1371	    return EINVAL;
1372	}
1373	/* NOT REACHED */
1374
1375    case KDGETMODE:     	/* get current mode of this (virtual) console */
1376	*data = (scp->status & UNKNOWN_MODE) ? KD_GRAPHICS : KD_TEXT;
1377	return 0;
1378
1379    case KDSBORDER:     	/* set border color of this (virtual) console */
1380	scp->border = *data;
1381	if (scp == cur_console)
1382	    set_border(scp->border);
1383	return 0;
1384
1385    case KDSKBSTATE:    	/* set keyboard state (locks) */
1386	if (*data >= 0 && *data <= LOCK_KEY_MASK) {
1387	    scp->status &= ~LOCK_KEY_MASK;
1388	    scp->status |= *data;
1389	    if (scp == cur_console)
1390		update_leds(scp->status);
1391	    return 0;
1392	}
1393	return EINVAL;
1394
1395    case KDGKBSTATE:    	/* get keyboard state (locks) */
1396	*data = scp->status & LOCK_KEY_MASK;
1397	return 0;
1398
1399    case KDSETRAD:      	/* set keyboard repeat & delay rates */
1400	if (*data & 0x80)
1401	    return EINVAL;
1402	if (sc_kbdc != NULL)
1403	    set_keyboard(KBDC_SET_TYPEMATIC, *data);
1404	return 0;
1405
1406    case KDSKBMODE:     	/* set keyboard mode */
1407	switch (*data) {
1408	case K_RAW: 		/* switch to RAW scancode mode */
1409	    scp->status |= KBD_RAW_MODE;
1410	    return 0;
1411
1412	case K_XLATE:   	/* switch to XLT ascii mode */
1413	    if (scp == cur_console && scp->status & KBD_RAW_MODE)
1414		shfts = ctls = alts = agrs = metas = 0;
1415	    scp->status &= ~KBD_RAW_MODE;
1416	    return 0;
1417	default:
1418	    return EINVAL;
1419	}
1420	/* NOT REACHED */
1421
1422    case KDGKBMODE:     	/* get keyboard mode */
1423	*data = (scp->status & KBD_RAW_MODE) ? K_RAW : K_XLATE;
1424	return 0;
1425
1426    case KDMKTONE:      	/* sound the bell */
1427	if (*(int*)data)
1428	    do_bell(scp, (*(int*)data)&0xffff,
1429		    (((*(int*)data)>>16)&0xffff)*hz/1000);
1430	else
1431	    do_bell(scp, scp->bell_pitch, scp->bell_duration);
1432	return 0;
1433
1434    case KIOCSOUND:     	/* make tone (*data) hz */
1435	if (scp == cur_console) {
1436	    if (*(int*)data) {
1437		int pitch = timer_freq / *(int*)data;
1438
1439		/* set command for counter 2, 2 byte write */
1440		if (acquire_timer2(TIMER_16BIT|TIMER_SQWAVE))
1441		    return EBUSY;
1442
1443		/* set pitch */
1444		outb(TIMER_CNTR2, pitch);
1445		outb(TIMER_CNTR2, (pitch>>8));
1446
1447		/* enable counter 2 output to speaker */
1448		outb(IO_PPI, inb(IO_PPI) | 3);
1449	    }
1450	    else {
1451		/* disable counter 2 output to speaker */
1452		outb(IO_PPI, inb(IO_PPI) & 0xFC);
1453		release_timer2();
1454	    }
1455	}
1456	return 0;
1457
1458    case KDGKBTYPE:     	/* get keyboard type */
1459	*data = 0;  		/* type not known (yet) */
1460	return 0;
1461
1462    case KDSETLED:      	/* set keyboard LED status */
1463	if (*data >= 0 && *data <= LED_MASK) {
1464	    scp->status &= ~LED_MASK;
1465	    scp->status |= *data;
1466	    if (scp == cur_console)
1467		update_leds(scp->status);
1468	    return 0;
1469	}
1470	return EINVAL;
1471
1472    case KDGETLED:      	/* get keyboard LED status */
1473	*data = scp->status & LED_MASK;
1474	return 0;
1475
1476    case GETFKEY:       	/* get functionkey string */
1477	if (*(u_short*)data < n_fkey_tab) {
1478	    fkeyarg_t *ptr = (fkeyarg_t*)data;
1479	    bcopy(&fkey_tab[ptr->keynum].str, ptr->keydef,
1480		  fkey_tab[ptr->keynum].len);
1481	    ptr->flen = fkey_tab[ptr->keynum].len;
1482	    return 0;
1483	}
1484	else
1485	    return EINVAL;
1486
1487    case SETFKEY:       	/* set functionkey string */
1488	if (*(u_short*)data < n_fkey_tab) {
1489	    fkeyarg_t *ptr = (fkeyarg_t*)data;
1490	    bcopy(ptr->keydef, &fkey_tab[ptr->keynum].str,
1491		  min(ptr->flen, MAXFK));
1492	    fkey_tab[ptr->keynum].len = min(ptr->flen, MAXFK);
1493	    return 0;
1494	}
1495	else
1496	    return EINVAL;
1497
1498    case GIO_SCRNMAP:   	/* get output translation table */
1499	bcopy(&scr_map, data, sizeof(scr_map));
1500	return 0;
1501
1502    case PIO_SCRNMAP:   	/* set output translation table */
1503	bcopy(data, &scr_map, sizeof(scr_map));
1504	for (i=0; i<sizeof(scr_map); i++)
1505	    scr_rmap[scr_map[i]] = i;
1506	return 0;
1507
1508    case GIO_KEYMAP:    	/* get keyboard translation table */
1509	bcopy(&key_map, data, sizeof(key_map));
1510	return 0;
1511
1512    case PIO_KEYMAP:    	/* set keyboard translation table */
1513	bcopy(data, &key_map, sizeof(key_map));
1514	return 0;
1515
1516    case PIO_FONT8x8:   	/* set 8x8 dot font */
1517	if (!crtc_vga)
1518	    return ENXIO;
1519	bcopy(data, font_8, 8*256);
1520	fonts_loaded |= FONT_8;
1521	if (!(cur_console->status & UNKNOWN_MODE)) {
1522	    copy_font(LOAD, FONT_8, font_8);
1523	    if (flags & CHAR_CURSOR)
1524	        set_destructive_cursor(cur_console);
1525	}
1526	return 0;
1527
1528    case GIO_FONT8x8:   	/* get 8x8 dot font */
1529	if (!crtc_vga)
1530	    return ENXIO;
1531	if (fonts_loaded & FONT_8) {
1532	    bcopy(font_8, data, 8*256);
1533	    return 0;
1534	}
1535	else
1536	    return ENXIO;
1537
1538    case PIO_FONT8x14:  	/* set 8x14 dot font */
1539	if (!crtc_vga)
1540	    return ENXIO;
1541	bcopy(data, font_14, 14*256);
1542	fonts_loaded |= FONT_14;
1543	if (!(cur_console->status & UNKNOWN_MODE)) {
1544	    copy_font(LOAD, FONT_14, font_14);
1545	    if (flags & CHAR_CURSOR)
1546	        set_destructive_cursor(cur_console);
1547	}
1548	return 0;
1549
1550    case GIO_FONT8x14:  	/* get 8x14 dot font */
1551	if (!crtc_vga)
1552	    return ENXIO;
1553	if (fonts_loaded & FONT_14) {
1554	    bcopy(font_14, data, 14*256);
1555	    return 0;
1556	}
1557	else
1558	    return ENXIO;
1559
1560    case PIO_FONT8x16:  	/* set 8x16 dot font */
1561	if (!crtc_vga)
1562	    return ENXIO;
1563	bcopy(data, font_16, 16*256);
1564	fonts_loaded |= FONT_16;
1565	if (!(cur_console->status & UNKNOWN_MODE)) {
1566	    copy_font(LOAD, FONT_16, font_16);
1567	    if (flags & CHAR_CURSOR)
1568	        set_destructive_cursor(cur_console);
1569	}
1570	return 0;
1571
1572    case GIO_FONT8x16:  	/* get 8x16 dot font */
1573	if (!crtc_vga)
1574	    return ENXIO;
1575	if (fonts_loaded & FONT_16) {
1576	    bcopy(font_16, data, 16*256);
1577	    return 0;
1578	}
1579	else
1580	    return ENXIO;
1581    default:
1582	break;
1583    }
1584
1585    error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
1586    if (error >= 0)
1587	return(error);
1588    error = ttioctl(tp, cmd, data, flag);
1589    if (error >= 0)
1590	return(error);
1591    return(ENOTTY);
1592}
1593
1594static void
1595scstart(struct tty *tp)
1596{
1597    struct clist *rbp;
1598    int s, len;
1599    u_char buf[PCBURST];
1600    scr_stat *scp = get_scr_stat(tp->t_dev);
1601
1602    if (scp->status & SLKED || blink_in_progress)
1603	return; /* XXX who repeats the call when the above flags are cleared? */
1604    s = spltty();
1605    if (!(tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP))) {
1606	tp->t_state |= TS_BUSY;
1607	rbp = &tp->t_outq;
1608	while (rbp->c_cc) {
1609	    len = q_to_b(rbp, buf, PCBURST);
1610	    splx(s);
1611	    ansi_put(scp, buf, len);
1612	    s = spltty();
1613	}
1614	tp->t_state &= ~TS_BUSY;
1615	ttwwakeup(tp);
1616    }
1617    splx(s);
1618}
1619
1620static void
1621scmousestart(struct tty *tp)
1622{
1623    struct clist *rbp;
1624    int s;
1625    u_char buf[PCBURST];
1626
1627    s = spltty();
1628    if (!(tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP))) {
1629	tp->t_state |= TS_BUSY;
1630	rbp = &tp->t_outq;
1631	while (rbp->c_cc) {
1632	    q_to_b(rbp, buf, PCBURST);
1633	}
1634	tp->t_state &= ~TS_BUSY;
1635	ttwwakeup(tp);
1636    }
1637    splx(s);
1638}
1639
1640void
1641sccnprobe(struct consdev *cp)
1642{
1643    struct isa_device *dvp;
1644
1645    /*
1646     * Take control if we are the highest priority enabled display device.
1647     */
1648    dvp = find_display();
1649    if (dvp == NULL || dvp->id_driver != &scdriver) {
1650	cp->cn_pri = CN_DEAD;
1651	return;
1652    }
1653
1654    if (!scvidprobe(dvp->id_unit, dvp->id_flags)) {
1655	cp->cn_pri = CN_DEAD;
1656	return;
1657    }
1658
1659    /* initialize required fields */
1660    cp->cn_dev = makedev(CDEV_MAJOR, SC_CONSOLE);
1661    cp->cn_pri = CN_INTERNAL;
1662
1663    sc_kbdc = kbdc_open(sc_port);
1664}
1665
1666void
1667sccninit(struct consdev *cp)
1668{
1669    scinit();
1670}
1671
1672void
1673sccnputc(dev_t dev, int c)
1674{
1675    u_char buf[1];
1676    int s;
1677    scr_stat *scp = console[0];
1678    term_stat save = scp->term;
1679
1680    scp->term = kernel_console;
1681    current_default = &kernel_default;
1682    if (scp == cur_console && !(scp->status & UNKNOWN_MODE))
1683	remove_cursor_image(scp);
1684    buf[0] = c;
1685    ansi_put(scp, buf, 1);
1686    kernel_console = scp->term;
1687    current_default = &user_default;
1688    scp->term = save;
1689    s = splclock();
1690    if (scp == cur_console && !(scp->status & UNKNOWN_MODE)) {
1691	if (/* timer not running && */ (scp->start <= scp->end)) {
1692	    sc_bcopy(scp->scr_buf + scp->start, Crtat + scp->start,
1693		   (1 + scp->end - scp->start) * sizeof(u_short));
1694	    scp->start = scp->xsize * scp->ysize;
1695	    scp->end = 0;
1696	}
1697    	scp->cursor_oldpos = scp->cursor_pos;
1698	draw_cursor_image(scp);
1699    }
1700    splx(s);
1701}
1702
1703int
1704sccngetc(dev_t dev)
1705{
1706    int s = spltty();	/* block scintr and scrn_timer while we poll */
1707    int c;
1708
1709    /*
1710     * Stop the screen saver if necessary.
1711     * What if we have been running in the screen saver code... XXX
1712     */
1713    if (scrn_blanked > 0)
1714        stop_scrn_saver(current_saver);
1715
1716    c = scgetc(SCGETC_CN);
1717
1718    /* make sure the screen saver won't be activated soon */
1719    scrn_time_stamp = mono_time.tv_sec;
1720    splx(s);
1721    return(c);
1722}
1723
1724int
1725sccncheckc(dev_t dev)
1726{
1727    int c, s;
1728
1729    s = spltty();
1730    if (scrn_blanked > 0)
1731        stop_scrn_saver(current_saver);
1732    c = scgetc(SCGETC_CN | SCGETC_NONBLOCK);
1733    if (c != NOKEY)
1734        scrn_time_stamp = mono_time.tv_sec;
1735    splx(s);
1736    return(c == NOKEY ? -1 : c);	/* c == -1 can't happen */
1737}
1738
1739static scr_stat
1740*get_scr_stat(dev_t dev)
1741{
1742    int unit = minor(dev);
1743
1744    if (unit == SC_CONSOLE)
1745	return console[0];
1746    if (unit >= MAXCONS || unit < 0)
1747	return(NULL);
1748    return console[unit];
1749}
1750
1751static int
1752get_scr_num()
1753{
1754    int i = 0;
1755
1756    while ((i < MAXCONS) && (cur_console != console[i]))
1757	i++;
1758    return i < MAXCONS ? i : 0;
1759}
1760
1761static void
1762scrn_timer(void *arg)
1763{
1764    scr_stat *scp = cur_console;
1765    int s = spltty();
1766
1767    /*
1768     * With release 2.1 of the Xaccel server, the keyboard is left
1769     * hanging pretty often. Apparently an interrupt from the
1770     * keyboard is lost, and I don't know why (yet).
1771     * This ugly hack calls scintr if input is ready for the keyboard
1772     * and conveniently hides the problem.			XXX
1773     */
1774    /* Try removing anything stuck in the keyboard controller; whether
1775     * it's a keyboard scan code or mouse data. `scintr()' doesn't
1776     * read the mouse data directly, but `kbdio' routines will, as a
1777     * side effect.
1778     */
1779    if (kbdc_lock(sc_kbdc, TRUE)) {
1780	/*
1781	 * We have seen the lock flag is not set. Let's reset the flag early;
1782	 * otherwise `update_led()' failes which may want the lock
1783	 * during `scintr()'.
1784	 */
1785	kbdc_lock(sc_kbdc, FALSE);
1786	if (kbdc_data_ready(sc_kbdc))
1787	    scintr(0);
1788    }
1789
1790    /* should we just return ? */
1791    if ((scp->status&UNKNOWN_MODE) || blink_in_progress || switch_in_progress) {
1792	timeout(scrn_timer, NULL, hz / 10);
1793	splx(s);
1794	return;
1795    }
1796
1797    /* should we stop the screen saver? */
1798    if (mono_time.tv_sec <= scrn_time_stamp + scrn_blank_time)
1799	if (scrn_blanked > 0)
1800            stop_scrn_saver(current_saver);
1801
1802    if (scrn_blanked <= 0) {
1803	/* update screen image */
1804	if (scp->start <= scp->end) {
1805	    sc_bcopy(scp->scr_buf + scp->start, Crtat + scp->start,
1806		   (1 + scp->end - scp->start) * sizeof(u_short));
1807	}
1808
1809	/* update "pseudo" mouse pointer image */
1810	if ((scp->status & MOUSE_VISIBLE) && crtc_vga) {
1811	    /* did mouse move since last time ? */
1812	    if (scp->status & MOUSE_MOVED) {
1813		/* do we need to remove old mouse pointer image ? */
1814		if (scp->mouse_cut_start != NULL ||
1815		    (scp->mouse_pos-scp->scr_buf) <= scp->start ||
1816		    (scp->mouse_pos+scp->xsize+1-scp->scr_buf) >= scp->end) {
1817		    remove_mouse_image(scp);
1818		}
1819		scp->status &= ~MOUSE_MOVED;
1820		draw_mouse_image(scp);
1821	    }
1822	    else {
1823		/* mouse didn't move, has it been overwritten ? */
1824		if ((scp->mouse_pos+scp->xsize+1-scp->scr_buf) >= scp->start &&
1825		    (scp->mouse_pos - scp->scr_buf) <= scp->end) {
1826		    draw_mouse_image(scp);
1827		}
1828	    }
1829	}
1830
1831	/* update cursor image */
1832	if (scp->status & CURSOR_ENABLED) {
1833	    /* did cursor move since last time ? */
1834	    if (scp->cursor_pos != scp->cursor_oldpos) {
1835		/* do we need to remove old cursor image ? */
1836		if ((scp->cursor_oldpos - scp->scr_buf) < scp->start ||
1837		    ((scp->cursor_oldpos - scp->scr_buf) > scp->end)) {
1838		    remove_cursor_image(scp);
1839		}
1840    		scp->cursor_oldpos = scp->cursor_pos;
1841		draw_cursor_image(scp);
1842	    }
1843	    else {
1844		/* cursor didn't move, has it been overwritten ? */
1845		if (scp->cursor_pos - scp->scr_buf >= scp->start &&
1846		    scp->cursor_pos - scp->scr_buf <= scp->end) {
1847		    	draw_cursor_image(scp);
1848		} else {
1849		    /* if its a blinking cursor, we may have to update it */
1850		    if (flags & BLINK_CURSOR)
1851			draw_cursor_image(scp);
1852		}
1853	    }
1854	    blinkrate++;
1855	}
1856
1857	if (scp->mouse_cut_start != NULL)
1858	    draw_cutmarking(scp);
1859
1860	scp->end = 0;
1861	scp->start = scp->xsize*scp->ysize;
1862    }
1863
1864    /* should we activate the screen saver? */
1865    if ((scrn_blank_time != 0)
1866	    && (mono_time.tv_sec > scrn_time_stamp + scrn_blank_time))
1867	(*current_saver)(TRUE);
1868
1869    timeout(scrn_timer, NULL, hz / 25);
1870    splx(s);
1871}
1872
1873int
1874add_scrn_saver(void (*this_saver)(int))
1875{
1876    if (current_saver != none_saver)
1877	return EBUSY;
1878    current_saver = this_saver;
1879    return 0;
1880}
1881
1882int
1883remove_scrn_saver(void (*this_saver)(int))
1884{
1885    if (current_saver != this_saver)
1886	return EINVAL;
1887
1888    /*
1889     * In order to prevent `current_saver' from being called by
1890     * the timeout routine `scrn_timer()' while we manipulate
1891     * the saver list, we shall set `current_saver' to `none_saver'
1892     * before stopping the current saver, rather than blocking by `splXX()'.
1893     */
1894    current_saver = none_saver;
1895    if (scrn_blanked > 0)
1896        stop_scrn_saver(this_saver);
1897
1898    return 0;
1899}
1900
1901static void
1902stop_scrn_saver(void (*saver)(int))
1903{
1904    (*saver)(FALSE);
1905    scrn_time_stamp = mono_time.tv_sec;
1906    mark_all(cur_console);
1907}
1908
1909static void
1910clear_screen(scr_stat *scp)
1911{
1912    move_crsr(scp, 0, 0);
1913    scp->cursor_oldpos = scp->cursor_pos;
1914    fillw(scp->term.cur_color | scr_map[0x20], scp->scr_buf,
1915	  scp->xsize * scp->ysize);
1916    mark_all(scp);
1917    remove_cutmarking(scp);
1918}
1919
1920static int
1921switch_scr(scr_stat *scp, u_int next_scr)
1922{
1923    if (switch_in_progress && (cur_console->proc != pfind(cur_console->pid)))
1924	switch_in_progress = FALSE;
1925
1926    if (next_scr >= MAXCONS || switch_in_progress ||
1927	(cur_console->smode.mode == VT_AUTO
1928	 && cur_console->status & UNKNOWN_MODE)) {
1929	do_bell(scp, BELL_PITCH, BELL_DURATION);
1930	return EINVAL;
1931    }
1932
1933    /* is the wanted virtual console open ? */
1934    if (next_scr) {
1935	struct tty *tp = VIRTUAL_TTY(next_scr);
1936	if (!(tp->t_state & TS_ISOPEN)) {
1937	    do_bell(scp, BELL_PITCH, BELL_DURATION);
1938	    return EINVAL;
1939	}
1940    }
1941    /* delay switch if actively updating screen */
1942    if (write_in_progress || blink_in_progress) {
1943	delayed_next_scr = next_scr+1;
1944	return 0;
1945    }
1946    switch_in_progress = TRUE;
1947    old_scp = cur_console;
1948    new_scp = console[next_scr];
1949    wakeup((caddr_t)&new_scp->smode);
1950    if (new_scp == old_scp) {
1951	switch_in_progress = FALSE;
1952	delayed_next_scr = FALSE;
1953	return 0;
1954    }
1955
1956    /* has controlling process died? */
1957    if (old_scp->proc && (old_scp->proc != pfind(old_scp->pid)))
1958	old_scp->smode.mode = VT_AUTO;
1959    if (new_scp->proc && (new_scp->proc != pfind(new_scp->pid)))
1960	new_scp->smode.mode = VT_AUTO;
1961
1962    /* check the modes and switch appropriately */
1963    if (old_scp->smode.mode == VT_PROCESS) {
1964	old_scp->status |= SWITCH_WAIT_REL;
1965	psignal(old_scp->proc, old_scp->smode.relsig);
1966    }
1967    else {
1968	exchange_scr();
1969	if (new_scp->smode.mode == VT_PROCESS) {
1970	    new_scp->status |= SWITCH_WAIT_ACQ;
1971	    psignal(new_scp->proc, new_scp->smode.acqsig);
1972	}
1973	else
1974	    switch_in_progress = FALSE;
1975    }
1976    return 0;
1977}
1978
1979static void
1980exchange_scr(void)
1981{
1982    move_crsr(old_scp, old_scp->xpos, old_scp->ypos);
1983    cur_console = new_scp;
1984    if (old_scp->mode != new_scp->mode || (old_scp->status & UNKNOWN_MODE)){
1985	if (crtc_vga && video_mode_ptr)
1986	    set_mode(new_scp);
1987    }
1988    move_crsr(new_scp, new_scp->xpos, new_scp->ypos);
1989    if (!(new_scp->status & UNKNOWN_MODE) && (flags & CHAR_CURSOR))
1990	set_destructive_cursor(new_scp);
1991    if ((old_scp->status & UNKNOWN_MODE) && crtc_vga)
1992	load_palette(palette);
1993    if (old_scp->status & KBD_RAW_MODE || new_scp->status & KBD_RAW_MODE)
1994	shfts = ctls = alts = agrs = metas = 0;
1995    update_leds(new_scp->status);
1996    delayed_next_scr = FALSE;
1997    mark_all(new_scp);
1998}
1999
2000static void
2001scan_esc(scr_stat *scp, u_char c)
2002{
2003    static u_char ansi_col[16] =
2004	{0, 4, 2, 6, 1, 5, 3, 7, 8, 12, 10, 14, 9, 13, 11, 15};
2005    int i, n;
2006    u_short *src, *dst, count;
2007
2008    if (scp->term.esc == 1) {
2009	switch (c) {
2010
2011	case '7':   /* Save cursor position */
2012	    scp->saved_xpos = scp->xpos;
2013	    scp->saved_ypos = scp->ypos;
2014	    break;
2015
2016	case '8':   /* Restore saved cursor position */
2017	    if (scp->saved_xpos >= 0 && scp->saved_ypos >= 0)
2018		move_crsr(scp, scp->saved_xpos, scp->saved_ypos);
2019	    break;
2020
2021	case '[':   /* Start ESC [ sequence */
2022	    scp->term.esc = 2;
2023	    scp->term.last_param = -1;
2024	    for (i = scp->term.num_param; i < MAX_ESC_PAR; i++)
2025		scp->term.param[i] = 1;
2026	    scp->term.num_param = 0;
2027	    return;
2028
2029	case 'M':   /* Move cursor up 1 line, scroll if at top */
2030	    if (scp->ypos > 0)
2031		move_crsr(scp, scp->xpos, scp->ypos - 1);
2032	    else {
2033		bcopy(scp->scr_buf, scp->scr_buf + scp->xsize,
2034		       (scp->ysize - 1) * scp->xsize * sizeof(u_short));
2035		fillw(scp->term.cur_color | scr_map[0x20],
2036		      scp->scr_buf, scp->xsize);
2037    		mark_all(scp);
2038	    }
2039	    break;
2040#if notyet
2041	case 'Q':
2042	    scp->term.esc = 4;
2043	    break;
2044#endif
2045	case 'c':   /* Clear screen & home */
2046	    clear_screen(scp);
2047	    break;
2048	}
2049    }
2050    else if (scp->term.esc == 2) {
2051	if (c >= '0' && c <= '9') {
2052	    if (scp->term.num_param < MAX_ESC_PAR) {
2053	    if (scp->term.last_param != scp->term.num_param) {
2054		scp->term.last_param = scp->term.num_param;
2055		scp->term.param[scp->term.num_param] = 0;
2056	    }
2057	    else
2058		scp->term.param[scp->term.num_param] *= 10;
2059	    scp->term.param[scp->term.num_param] += c - '0';
2060	    return;
2061	    }
2062	}
2063	scp->term.num_param = scp->term.last_param + 1;
2064	switch (c) {
2065
2066	case ';':
2067	    if (scp->term.num_param < MAX_ESC_PAR)
2068		return;
2069	    break;
2070
2071	case '=':
2072	    scp->term.esc = 3;
2073	    scp->term.last_param = -1;
2074	    for (i = scp->term.num_param; i < MAX_ESC_PAR; i++)
2075		scp->term.param[i] = 1;
2076	    scp->term.num_param = 0;
2077	    return;
2078
2079	case 'A':   /* up n rows */
2080	    n = scp->term.param[0]; if (n < 1) n = 1;
2081	    move_crsr(scp, scp->xpos, scp->ypos - n);
2082	    break;
2083
2084	case 'B':   /* down n rows */
2085	    n = scp->term.param[0]; if (n < 1) n = 1;
2086	    move_crsr(scp, scp->xpos, scp->ypos + n);
2087	    break;
2088
2089	case 'C':   /* right n columns */
2090	    n = scp->term.param[0]; if (n < 1) n = 1;
2091	    move_crsr(scp, scp->xpos + n, scp->ypos);
2092	    break;
2093
2094	case 'D':   /* left n columns */
2095	    n = scp->term.param[0]; if (n < 1) n = 1;
2096	    move_crsr(scp, scp->xpos - n, scp->ypos);
2097	    break;
2098
2099	case 'E':   /* cursor to start of line n lines down */
2100	    n = scp->term.param[0]; if (n < 1) n = 1;
2101	    move_crsr(scp, 0, scp->ypos + n);
2102	    break;
2103
2104	case 'F':   /* cursor to start of line n lines up */
2105	    n = scp->term.param[0]; if (n < 1) n = 1;
2106	    move_crsr(scp, 0, scp->ypos - n);
2107	    break;
2108
2109	case 'f':   /* Cursor move */
2110	case 'H':
2111	    if (scp->term.num_param == 0)
2112		move_crsr(scp, 0, 0);
2113	    else if (scp->term.num_param == 2)
2114		move_crsr(scp, scp->term.param[1] - 1, scp->term.param[0] - 1);
2115	    break;
2116
2117	case 'J':   /* Clear all or part of display */
2118	    if (scp->term.num_param == 0)
2119		n = 0;
2120	    else
2121		n = scp->term.param[0];
2122	    switch (n) {
2123	    case 0: /* clear form cursor to end of display */
2124		fillw(scp->term.cur_color | scr_map[0x20],
2125		      scp->cursor_pos,
2126		      scp->scr_buf + scp->xsize * scp->ysize - scp->cursor_pos);
2127    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2128    		mark_for_update(scp, scp->xsize * scp->ysize);
2129		remove_cutmarking(scp);
2130		break;
2131	    case 1: /* clear from beginning of display to cursor */
2132		fillw(scp->term.cur_color | scr_map[0x20],
2133		      scp->scr_buf,
2134		      scp->cursor_pos - scp->scr_buf);
2135    		mark_for_update(scp, 0);
2136    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2137		remove_cutmarking(scp);
2138		break;
2139	    case 2: /* clear entire display */
2140		fillw(scp->term.cur_color | scr_map[0x20], scp->scr_buf,
2141		      scp->xsize * scp->ysize);
2142		mark_all(scp);
2143		remove_cutmarking(scp);
2144		break;
2145	    }
2146	    break;
2147
2148	case 'K':   /* Clear all or part of line */
2149	    if (scp->term.num_param == 0)
2150		n = 0;
2151	    else
2152		n = scp->term.param[0];
2153	    switch (n) {
2154	    case 0: /* clear form cursor to end of line */
2155		fillw(scp->term.cur_color | scr_map[0x20],
2156		      scp->cursor_pos,
2157		      scp->xsize - scp->xpos);
2158    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2159    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf +
2160				scp->xsize - scp->xpos);
2161		break;
2162	    case 1: /* clear from beginning of line to cursor */
2163		fillw(scp->term.cur_color | scr_map[0x20],
2164		      scp->cursor_pos - scp->xpos,
2165		      scp->xpos + 1);
2166    		mark_for_update(scp, scp->ypos * scp->xsize);
2167    		mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2168		break;
2169	    case 2: /* clear entire line */
2170		fillw(scp->term.cur_color | scr_map[0x20],
2171		      scp->cursor_pos - scp->xpos,
2172		      scp->xsize);
2173    		mark_for_update(scp, scp->ypos * scp->xsize);
2174    		mark_for_update(scp, (scp->ypos + 1) * scp->xsize);
2175		break;
2176	    }
2177	    break;
2178
2179	case 'L':   /* Insert n lines */
2180	    n = scp->term.param[0]; if (n < 1) n = 1;
2181	    if (n > scp->ysize - scp->ypos)
2182		n = scp->ysize - scp->ypos;
2183	    src = scp->scr_buf + scp->ypos * scp->xsize;
2184	    dst = src + n * scp->xsize;
2185	    count = scp->ysize - (scp->ypos + n);
2186	    bcopy(src, dst, count * scp->xsize * sizeof(u_short));
2187	    fillw(scp->term.cur_color | scr_map[0x20], src,
2188		  n * scp->xsize);
2189	    mark_for_update(scp, scp->ypos * scp->xsize);
2190	    mark_for_update(scp, scp->xsize * scp->ysize);
2191	    break;
2192
2193	case 'M':   /* Delete n lines */
2194	    n = scp->term.param[0]; if (n < 1) n = 1;
2195	    if (n > scp->ysize - scp->ypos)
2196		n = scp->ysize - scp->ypos;
2197	    dst = scp->scr_buf + scp->ypos * scp->xsize;
2198	    src = dst + n * scp->xsize;
2199	    count = scp->ysize - (scp->ypos + n);
2200	    bcopy(src, dst, count * scp->xsize * sizeof(u_short));
2201	    src = dst + count * scp->xsize;
2202	    fillw(scp->term.cur_color | scr_map[0x20], src,
2203		  n * scp->xsize);
2204	    mark_for_update(scp, scp->ypos * scp->xsize);
2205	    mark_for_update(scp, scp->xsize * scp->ysize);
2206	    break;
2207
2208	case 'P':   /* Delete n chars */
2209	    n = scp->term.param[0]; if (n < 1) n = 1;
2210	    if (n > scp->xsize - scp->xpos)
2211		n = scp->xsize - scp->xpos;
2212	    dst = scp->cursor_pos;
2213	    src = dst + n;
2214	    count = scp->xsize - (scp->xpos + n);
2215	    bcopy(src, dst, count * sizeof(u_short));
2216	    src = dst + count;
2217	    fillw(scp->term.cur_color | scr_map[0x20], src, n);
2218	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2219	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n + count);
2220	    break;
2221
2222	case '@':   /* Insert n chars */
2223	    n = scp->term.param[0]; if (n < 1) n = 1;
2224	    if (n > scp->xsize - scp->xpos)
2225		n = scp->xsize - scp->xpos;
2226	    src = scp->cursor_pos;
2227	    dst = src + n;
2228	    count = scp->xsize - (scp->xpos + n);
2229	    bcopy(src, dst, count * sizeof(u_short));
2230	    fillw(scp->term.cur_color | scr_map[0x20], src, n);
2231	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2232	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n + count);
2233	    break;
2234
2235	case 'S':   /* scroll up n lines */
2236	    n = scp->term.param[0]; if (n < 1)  n = 1;
2237	    if (n > scp->ysize)
2238		n = scp->ysize;
2239	    bcopy(scp->scr_buf + (scp->xsize * n),
2240		   scp->scr_buf,
2241		   scp->xsize * (scp->ysize - n) * sizeof(u_short));
2242	    fillw(scp->term.cur_color | scr_map[0x20],
2243		  scp->scr_buf + scp->xsize * (scp->ysize - n),
2244		  scp->xsize * n);
2245    	    mark_all(scp);
2246	    break;
2247
2248	case 'T':   /* scroll down n lines */
2249	    n = scp->term.param[0]; if (n < 1)  n = 1;
2250	    if (n > scp->ysize)
2251		n = scp->ysize;
2252	    bcopy(scp->scr_buf,
2253		  scp->scr_buf + (scp->xsize * n),
2254		  scp->xsize * (scp->ysize - n) *
2255		  sizeof(u_short));
2256	    fillw(scp->term.cur_color | scr_map[0x20],
2257		  scp->scr_buf, scp->xsize * n);
2258    	    mark_all(scp);
2259	    break;
2260
2261	case 'X':   /* erase n characters in line */
2262	    n = scp->term.param[0]; if (n < 1)  n = 1;
2263	    if (n > scp->xsize - scp->xpos)
2264		n = scp->xsize - scp->xpos;
2265	    fillw(scp->term.cur_color | scr_map[0x20],
2266		  scp->cursor_pos, n);
2267	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2268	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf + n);
2269	    break;
2270
2271	case 'Z':   /* move n tabs backwards */
2272	    n = scp->term.param[0]; if (n < 1)  n = 1;
2273	    if ((i = scp->xpos & 0xf8) == scp->xpos)
2274		i -= 8*n;
2275	    else
2276		i -= 8*(n-1);
2277	    if (i < 0)
2278		i = 0;
2279	    move_crsr(scp, i, scp->ypos);
2280	    break;
2281
2282	case '`':   /* move cursor to column n */
2283	    n = scp->term.param[0]; if (n < 1)  n = 1;
2284	    move_crsr(scp, n - 1, scp->ypos);
2285	    break;
2286
2287	case 'a':   /* move cursor n columns to the right */
2288	    n = scp->term.param[0]; if (n < 1)  n = 1;
2289	    move_crsr(scp, scp->xpos + n, scp->ypos);
2290	    break;
2291
2292	case 'd':   /* move cursor to row n */
2293	    n = scp->term.param[0]; if (n < 1)  n = 1;
2294	    move_crsr(scp, scp->xpos, n - 1);
2295	    break;
2296
2297	case 'e':   /* move cursor n rows down */
2298	    n = scp->term.param[0]; if (n < 1)  n = 1;
2299	    move_crsr(scp, scp->xpos, scp->ypos + n);
2300	    break;
2301
2302	case 'm':   /* change attribute */
2303	    if (scp->term.num_param == 0) {
2304		scp->term.attr_mask = NORMAL_ATTR;
2305		scp->term.cur_attr =
2306		    scp->term.cur_color = scp->term.std_color;
2307		break;
2308	    }
2309	    for (i = 0; i < scp->term.num_param; i++) {
2310		switch (n = scp->term.param[i]) {
2311		case 0: /* back to normal */
2312		    scp->term.attr_mask = NORMAL_ATTR;
2313		    scp->term.cur_attr =
2314			scp->term.cur_color = scp->term.std_color;
2315		    break;
2316		case 1: /* bold */
2317		    scp->term.attr_mask |= BOLD_ATTR;
2318		    scp->term.cur_attr = mask2attr(&scp->term);
2319		    break;
2320		case 4: /* underline */
2321		    scp->term.attr_mask |= UNDERLINE_ATTR;
2322		    scp->term.cur_attr = mask2attr(&scp->term);
2323		    break;
2324		case 5: /* blink */
2325		    scp->term.attr_mask |= BLINK_ATTR;
2326		    scp->term.cur_attr = mask2attr(&scp->term);
2327		    break;
2328		case 7: /* reverse video */
2329		    scp->term.attr_mask |= REVERSE_ATTR;
2330		    scp->term.cur_attr = mask2attr(&scp->term);
2331		    break;
2332		case 30: case 31: /* set fg color */
2333		case 32: case 33: case 34:
2334		case 35: case 36: case 37:
2335		    scp->term.attr_mask |= FOREGROUND_CHANGED;
2336		    scp->term.cur_color =
2337			(scp->term.cur_color&0xF000) | (ansi_col[(n-30)&7]<<8);
2338		    scp->term.cur_attr = mask2attr(&scp->term);
2339		    break;
2340		case 40: case 41: /* set bg color */
2341		case 42: case 43: case 44:
2342		case 45: case 46: case 47:
2343		    scp->term.attr_mask |= BACKGROUND_CHANGED;
2344		    scp->term.cur_color =
2345			(scp->term.cur_color&0x0F00) | (ansi_col[(n-40)&7]<<12);
2346		    scp->term.cur_attr = mask2attr(&scp->term);
2347		    break;
2348		}
2349	    }
2350	    break;
2351
2352	case 's':   /* Save cursor position */
2353	    scp->saved_xpos = scp->xpos;
2354	    scp->saved_ypos = scp->ypos;
2355	    break;
2356
2357	case 'u':   /* Restore saved cursor position */
2358	    if (scp->saved_xpos >= 0 && scp->saved_ypos >= 0)
2359		move_crsr(scp, scp->saved_xpos, scp->saved_ypos);
2360	    break;
2361
2362	case 'x':
2363	    if (scp->term.num_param == 0)
2364		n = 0;
2365	    else
2366		n = scp->term.param[0];
2367	    switch (n) {
2368	    case 0:     /* reset attributes */
2369		scp->term.attr_mask = NORMAL_ATTR;
2370		scp->term.cur_attr =
2371		    scp->term.cur_color = scp->term.std_color =
2372		    current_default->std_color;
2373		scp->term.rev_color = current_default->rev_color;
2374		break;
2375	    case 1:     /* set ansi background */
2376		scp->term.attr_mask &= ~BACKGROUND_CHANGED;
2377		scp->term.cur_color = scp->term.std_color =
2378		    (scp->term.std_color & 0x0F00) |
2379		    (ansi_col[(scp->term.param[1])&0x0F]<<12);
2380		scp->term.cur_attr = mask2attr(&scp->term);
2381		break;
2382	    case 2:     /* set ansi foreground */
2383		scp->term.attr_mask &= ~FOREGROUND_CHANGED;
2384		scp->term.cur_color = scp->term.std_color =
2385		    (scp->term.std_color & 0xF000) |
2386		    (ansi_col[(scp->term.param[1])&0x0F]<<8);
2387		scp->term.cur_attr = mask2attr(&scp->term);
2388		break;
2389	    case 3:     /* set ansi attribute directly */
2390		scp->term.attr_mask &= ~(FOREGROUND_CHANGED|BACKGROUND_CHANGED);
2391		scp->term.cur_color = scp->term.std_color =
2392		    (scp->term.param[1]&0xFF)<<8;
2393		scp->term.cur_attr = mask2attr(&scp->term);
2394		break;
2395	    case 5:     /* set ansi reverse video background */
2396		scp->term.rev_color =
2397		    (scp->term.rev_color & 0x0F00) |
2398		    (ansi_col[(scp->term.param[1])&0x0F]<<12);
2399		scp->term.cur_attr = mask2attr(&scp->term);
2400		break;
2401	    case 6:     /* set ansi reverse video foreground */
2402		scp->term.rev_color =
2403		    (scp->term.rev_color & 0xF000) |
2404		    (ansi_col[(scp->term.param[1])&0x0F]<<8);
2405		scp->term.cur_attr = mask2attr(&scp->term);
2406		break;
2407	    case 7:     /* set ansi reverse video directly */
2408		scp->term.rev_color =
2409		    (scp->term.param[1]&0xFF)<<8;
2410		scp->term.cur_attr = mask2attr(&scp->term);
2411		break;
2412	    }
2413	    break;
2414
2415	case 'z':   /* switch to (virtual) console n */
2416	    if (scp->term.num_param == 1)
2417		switch_scr(scp, scp->term.param[0]);
2418	    break;
2419	}
2420    }
2421    else if (scp->term.esc == 3) {
2422	if (c >= '0' && c <= '9') {
2423	    if (scp->term.num_param < MAX_ESC_PAR) {
2424	    if (scp->term.last_param != scp->term.num_param) {
2425		scp->term.last_param = scp->term.num_param;
2426		scp->term.param[scp->term.num_param] = 0;
2427	    }
2428	    else
2429		scp->term.param[scp->term.num_param] *= 10;
2430	    scp->term.param[scp->term.num_param] += c - '0';
2431	    return;
2432	    }
2433	}
2434	scp->term.num_param = scp->term.last_param + 1;
2435	switch (c) {
2436
2437	case ';':
2438	    if (scp->term.num_param < MAX_ESC_PAR)
2439		return;
2440	    break;
2441
2442	case 'A':   /* set display border color */
2443	    if (scp->term.num_param == 1) {
2444		scp->border=scp->term.param[0] & 0xff;
2445		if (scp == cur_console)
2446		    set_border(scp->border);
2447            }
2448	    break;
2449
2450	case 'B':   /* set bell pitch and duration */
2451	    if (scp->term.num_param == 2) {
2452		scp->bell_pitch = scp->term.param[0];
2453		scp->bell_duration = scp->term.param[1]*10;
2454	    }
2455	    break;
2456
2457	case 'C':   /* set cursor type & shape */
2458	    if (scp->term.num_param == 1) {
2459		if (scp->term.param[0] & 0x01)
2460		    flags |= BLINK_CURSOR;
2461		else
2462		    flags &= ~BLINK_CURSOR;
2463		if ((scp->term.param[0] & 0x02) && crtc_vga)
2464		    flags |= CHAR_CURSOR;
2465		else
2466		    flags &= ~CHAR_CURSOR;
2467	    }
2468	    else if (scp->term.num_param == 2) {
2469		scp->cursor_start = scp->term.param[0] & 0x1F;
2470		scp->cursor_end = scp->term.param[1] & 0x1F;
2471	    }
2472	    /*
2473	     * The cursor shape is global property; all virtual consoles
2474	     * are affected. Update the cursor in the current console...
2475	     */
2476	    if (!(cur_console->status & UNKNOWN_MODE)) {
2477		remove_cursor_image(cur_console);
2478		if (crtc_vga && (flags & CHAR_CURSOR))
2479	            set_destructive_cursor(cur_console);
2480		draw_cursor_image(cur_console);
2481	    }
2482	    break;
2483
2484	case 'F':   /* set ansi foreground */
2485	    if (scp->term.num_param == 1) {
2486		scp->term.attr_mask &= ~FOREGROUND_CHANGED;
2487		scp->term.cur_color = scp->term.std_color =
2488		    (scp->term.std_color & 0xF000)
2489		    | ((scp->term.param[0] & 0x0F) << 8);
2490		scp->term.cur_attr = mask2attr(&scp->term);
2491	    }
2492	    break;
2493
2494	case 'G':   /* set ansi background */
2495	    if (scp->term.num_param == 1) {
2496		scp->term.attr_mask &= ~BACKGROUND_CHANGED;
2497		scp->term.cur_color = scp->term.std_color =
2498		    (scp->term.std_color & 0x0F00)
2499		    | ((scp->term.param[0] & 0x0F) << 12);
2500		scp->term.cur_attr = mask2attr(&scp->term);
2501	    }
2502	    break;
2503
2504	case 'H':   /* set ansi reverse video foreground */
2505	    if (scp->term.num_param == 1) {
2506		scp->term.rev_color =
2507		    (scp->term.rev_color & 0xF000)
2508		    | ((scp->term.param[0] & 0x0F) << 8);
2509		scp->term.cur_attr = mask2attr(&scp->term);
2510	    }
2511	    break;
2512
2513	case 'I':   /* set ansi reverse video background */
2514	    if (scp->term.num_param == 1) {
2515		scp->term.rev_color =
2516		    (scp->term.rev_color & 0x0F00)
2517		    | ((scp->term.param[0] & 0x0F) << 12);
2518		scp->term.cur_attr = mask2attr(&scp->term);
2519	    }
2520	    break;
2521	}
2522    }
2523    scp->term.esc = 0;
2524}
2525
2526static void
2527ansi_put(scr_stat *scp, u_char *buf, int len)
2528{
2529    u_char *ptr = buf;
2530
2531    /* make screensaver happy */
2532    if (scp == cur_console)
2533	scrn_time_stamp = mono_time.tv_sec;
2534
2535    write_in_progress++;
2536outloop:
2537    if (scp->term.esc) {
2538	scan_esc(scp, *ptr++);
2539	len--;
2540    }
2541    else if (PRINTABLE(*ptr)) {     /* Print only printables */
2542 	int cnt = len <= (scp->xsize-scp->xpos) ? len : (scp->xsize-scp->xpos);
2543 	u_short cur_attr = scp->term.cur_attr;
2544 	u_short *cursor_pos = scp->cursor_pos;
2545	do {
2546	    /*
2547	     * gcc-2.6.3 generates poor (un)sign extension code.  Casting the
2548	     * pointers in the following to volatile should have no effect,
2549	     * but in fact speeds up this inner loop from 26 to 18 cycles
2550	     * (+ cache misses) on i486's.
2551	     */
2552#define	UCVP(ucp)	((u_char volatile *)(ucp))
2553	    *cursor_pos++ = UCVP(scr_map)[*UCVP(ptr)] | cur_attr;
2554	    ptr++;
2555	    cnt--;
2556	} while (cnt && PRINTABLE(*ptr));
2557	len -= (cursor_pos - scp->cursor_pos);
2558	scp->xpos += (cursor_pos - scp->cursor_pos);
2559	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2560	mark_for_update(scp, cursor_pos - scp->scr_buf);
2561	scp->cursor_pos = cursor_pos;
2562	if (scp->xpos >= scp->xsize) {
2563	    scp->xpos = 0;
2564	    scp->ypos++;
2565	}
2566    }
2567    else  {
2568	switch(*ptr) {
2569	case 0x07:
2570	    do_bell(scp, scp->bell_pitch, scp->bell_duration);
2571	    break;
2572
2573	case 0x08:      /* non-destructive backspace */
2574	    if (scp->cursor_pos > scp->scr_buf) {
2575	    	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2576		scp->cursor_pos--;
2577	    	mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2578		if (scp->xpos > 0)
2579		    scp->xpos--;
2580		else {
2581		    scp->xpos += scp->xsize - 1;
2582		    scp->ypos--;
2583		}
2584	    }
2585	    break;
2586
2587	case 0x09:  /* non-destructive tab */
2588	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2589	    scp->cursor_pos += (8 - scp->xpos % 8u);
2590	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2591	    if ((scp->xpos += (8 - scp->xpos % 8u)) >= scp->xsize) {
2592	        scp->xpos = 0;
2593	        scp->ypos++;
2594	    }
2595	    break;
2596
2597	case 0x0a:  /* newline, same pos */
2598	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2599	    scp->cursor_pos += scp->xsize;
2600	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2601	    scp->ypos++;
2602	    break;
2603
2604	case 0x0c:  /* form feed, clears screen */
2605	    clear_screen(scp);
2606	    break;
2607
2608	case 0x0d:  /* return, return to pos 0 */
2609	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2610	    scp->cursor_pos -= scp->xpos;
2611	    mark_for_update(scp, scp->cursor_pos - scp->scr_buf);
2612	    scp->xpos = 0;
2613	    break;
2614
2615	case 0x1b:  /* start escape sequence */
2616	    scp->term.esc = 1;
2617	    scp->term.num_param = 0;
2618	    break;
2619	}
2620	ptr++; len--;
2621    }
2622    /* do we have to scroll ?? */
2623    if (scp->cursor_pos >= scp->scr_buf + scp->ysize * scp->xsize) {
2624	remove_cutmarking(scp);
2625	if (scp->history) {
2626	    bcopy(scp->scr_buf, scp->history_head,
2627		   scp->xsize * sizeof(u_short));
2628	    scp->history_head += scp->xsize;
2629	    if (scp->history_head + scp->xsize >
2630		scp->history + scp->history_size)
2631		scp->history_head = scp->history;
2632	}
2633	bcopy(scp->scr_buf + scp->xsize, scp->scr_buf,
2634	       scp->xsize * (scp->ysize - 1) * sizeof(u_short));
2635	fillw(scp->term.cur_color | scr_map[0x20],
2636	      scp->scr_buf + scp->xsize * (scp->ysize - 1),
2637	      scp->xsize);
2638	scp->cursor_pos -= scp->xsize;
2639	scp->ypos--;
2640    	mark_all(scp);
2641    }
2642    if (len)
2643	goto outloop;
2644    write_in_progress--;
2645    if (delayed_next_scr)
2646	switch_scr(scp, delayed_next_scr - 1);
2647}
2648
2649static void
2650scinit(void)
2651{
2652    u_int hw_cursor;
2653    u_int i;
2654
2655    if (init_done != COLD)
2656	return;
2657    init_done = WARM;
2658
2659    /*
2660     * Ensure a zero start address.  This is mainly to recover after
2661     * switching from pcvt using userconfig().  The registers are w/o
2662     * for old hardware so it's too hard to relocate the active screen
2663     * memory.
2664     */
2665    outb(crtc_addr, 12);
2666    outb(crtc_addr + 1, 0);
2667    outb(crtc_addr, 13);
2668    outb(crtc_addr + 1, 0);
2669
2670    /* extract cursor location */
2671    outb(crtc_addr, 14);
2672    hw_cursor = inb(crtc_addr + 1) << 8;
2673    outb(crtc_addr, 15);
2674    hw_cursor |= inb(crtc_addr + 1);
2675
2676    /*
2677     * Validate cursor location.  It may be off the screen.  Then we must
2678     * not use it for the initial buffer offset.
2679     */
2680    if (hw_cursor >= ROW * COL)
2681	hw_cursor = (ROW - 1) * COL;
2682
2683    /* move hardware cursor out of the way */
2684    outb(crtc_addr, 14);
2685    outb(crtc_addr + 1, 0xff);
2686    outb(crtc_addr, 15);
2687    outb(crtc_addr + 1, 0xff);
2688
2689    /* set up the first console */
2690    current_default = &user_default;
2691    console[0] = &main_console;
2692    init_scp(console[0]);
2693    cur_console = console[0];
2694
2695    /* discard the video mode table if we are not familiar with it... */
2696    if (video_mode_ptr) {
2697        if (comp_vgaregs(vgaregs, video_mode_ptr + 64*console[0]->mode))
2698            video_mode_ptr = NULL;
2699    }
2700
2701    /* copy screen to temporary buffer */
2702    sc_bcopy(Crtat, sc_buffer,
2703	   console[0]->xsize * console[0]->ysize * sizeof(u_short));
2704
2705    console[0]->scr_buf = console[0]->mouse_pos = sc_buffer;
2706    console[0]->cursor_pos = console[0]->cursor_oldpos = sc_buffer + hw_cursor;
2707    console[0]->cursor_saveunder = *console[0]->cursor_pos;
2708    console[0]->xpos = hw_cursor % COL;
2709    console[0]->ypos = hw_cursor / COL;
2710    for (i=1; i<MAXCONS; i++)
2711	console[i] = NULL;
2712    kernel_console.esc = 0;
2713    kernel_console.attr_mask = NORMAL_ATTR;
2714    kernel_console.cur_attr =
2715	kernel_console.cur_color = kernel_console.std_color =
2716	kernel_default.std_color;
2717    kernel_console.rev_color = kernel_default.rev_color;
2718
2719    /* initialize mapscrn arrays to a one to one map */
2720    for (i=0; i<sizeof(scr_map); i++) {
2721	scr_map[i] = scr_rmap[i] = i;
2722    }
2723
2724    /* Save font and palette if VGA */
2725    if (crtc_vga) {
2726	if (fonts_loaded & FONT_16) {
2727		copy_font(LOAD, FONT_16, font_16);
2728	} else {
2729		copy_font(SAVE, FONT_16, font_16);
2730		fonts_loaded = FONT_16;
2731	}
2732	save_palette();
2733	set_destructive_cursor(console[0]);
2734    }
2735
2736#ifdef SC_SPLASH_SCREEN
2737    /*
2738     * Now put up a graphics image, and maybe cycle a
2739     * couble of palette entries for simple animation.
2740     */
2741    toggle_splash_screen(cur_console);
2742#endif
2743}
2744
2745static scr_stat
2746*alloc_scp()
2747{
2748    scr_stat *scp;
2749
2750    scp = (scr_stat *)malloc(sizeof(scr_stat), M_DEVBUF, M_WAITOK);
2751    init_scp(scp);
2752    scp->scr_buf = scp->cursor_pos = scp->cursor_oldpos =
2753	(u_short *)malloc(scp->xsize*scp->ysize*sizeof(u_short),
2754			  M_DEVBUF, M_WAITOK);
2755    scp->mouse_pos = scp->mouse_oldpos =
2756	scp->scr_buf + ((scp->mouse_ypos/scp->font_size)*scp->xsize +
2757			scp->mouse_xpos/8);
2758    scp->history_head = scp->history_pos = scp->history =
2759	(u_short *)malloc(scp->history_size*sizeof(u_short),
2760			  M_DEVBUF, M_WAITOK);
2761    bzero(scp->history_head, scp->history_size*sizeof(u_short));
2762/* SOS
2763    if (crtc_vga && video_mode_ptr)
2764	set_mode(scp);
2765*/
2766    clear_screen(scp);
2767    scp->cursor_saveunder = *scp->cursor_pos;
2768    return scp;
2769}
2770
2771static void
2772init_scp(scr_stat *scp)
2773{
2774    if (crtc_vga)
2775	if (crtc_addr == MONO_BASE)
2776	    scp->mode = M_VGA_M80x25;
2777	else
2778	    scp->mode = M_VGA_C80x25;
2779    else
2780	if (crtc_addr == MONO_BASE)
2781	    scp->mode = M_B80x25;
2782	else
2783	    scp->mode = M_C80x25;
2784
2785    scp->font_size = 16;
2786    scp->xsize = COL;
2787    scp->ysize = ROW;
2788    scp->xpos = scp->ypos = 0;
2789    scp->saved_xpos = scp->saved_ypos = -1;
2790    scp->start = scp->xsize * scp->ysize;
2791    scp->end = 0;
2792    scp->term.esc = 0;
2793    scp->term.attr_mask = NORMAL_ATTR;
2794    scp->term.cur_attr =
2795	scp->term.cur_color = scp->term.std_color =
2796	current_default->std_color;
2797    scp->term.rev_color = current_default->rev_color;
2798    scp->border = BG_BLACK;
2799    scp->cursor_start = *(char *)pa_to_va(0x461);
2800    scp->cursor_end = *(char *)pa_to_va(0x460);
2801    scp->mouse_xpos = scp->xsize*8/2;
2802    scp->mouse_ypos = scp->ysize*scp->font_size/2;
2803    scp->mouse_cut_start = scp->mouse_cut_end = NULL;
2804    scp->mouse_signal = 0;
2805    scp->mouse_pid = 0;
2806    scp->mouse_proc = NULL;
2807    scp->bell_pitch = BELL_PITCH;
2808    scp->bell_duration = BELL_DURATION;
2809    scp->status = (*(char *)pa_to_va(0x417) & 0x20) ? NLKED : 0;
2810    scp->status |= CURSOR_ENABLED;
2811    scp->pid = 0;
2812    scp->proc = NULL;
2813    scp->smode.mode = VT_AUTO;
2814    scp->history_head = scp->history_pos = scp->history = NULL;
2815    scp->history_size = HISTORY_SIZE;
2816}
2817
2818static u_char
2819*get_fstr(u_int c, u_int *len)
2820{
2821    u_int i;
2822
2823    if (!(c & FKEY))
2824	return(NULL);
2825    i = (c & 0xFF) - F_FN;
2826    if (i > n_fkey_tab)
2827	return(NULL);
2828    *len = fkey_tab[i].len;
2829    return(fkey_tab[i].str);
2830}
2831
2832static void
2833history_to_screen(scr_stat *scp)
2834{
2835    int i;
2836
2837    for (i=0; i<scp->ysize; i++)
2838	bcopy(scp->history + (((scp->history_pos - scp->history) +
2839	       scp->history_size-((i+1)*scp->xsize))%scp->history_size),
2840	       scp->scr_buf + (scp->xsize * (scp->ysize-1 - i)),
2841	       scp->xsize * sizeof(u_short));
2842    mark_all(scp);
2843}
2844
2845static int
2846history_up_line(scr_stat *scp)
2847{
2848    if (WRAPHIST(scp, scp->history_pos, -(scp->xsize*scp->ysize)) !=
2849	scp->history_head) {
2850	scp->history_pos = WRAPHIST(scp, scp->history_pos, -scp->xsize);
2851	history_to_screen(scp);
2852	return 0;
2853    }
2854    else
2855	return -1;
2856}
2857
2858static int
2859history_down_line(scr_stat *scp)
2860{
2861    if (scp->history_pos != scp->history_head) {
2862	scp->history_pos = WRAPHIST(scp, scp->history_pos, scp->xsize);
2863	history_to_screen(scp);
2864	return 0;
2865    }
2866    else
2867	return -1;
2868}
2869
2870/*
2871 * scgetc(flags) - get character from keyboard.
2872 * If flags & SCGETC_CN, then avoid harmful side effects.
2873 * If flags & SCGETC_NONBLOCK, then wait until a key is pressed, else
2874 * return NOKEY if there is nothing there.
2875 */
2876static u_int
2877scgetc(u_int flags)
2878{
2879    struct key_t *key;
2880    u_char scancode, keycode;
2881    u_int state, action;
2882    int c;
2883    static u_char esc_flag = 0, compose = 0;
2884    static u_int chr = 0;
2885
2886next_code:
2887    /* first see if there is something in the keyboard port */
2888    if (flags & SCGETC_NONBLOCK) {
2889	c = read_kbd_data_no_wait(sc_kbdc);
2890	if (c == -1)
2891	    return(NOKEY);
2892    } else {
2893	do {
2894	    c = read_kbd_data(sc_kbdc);
2895	} while(c == -1);
2896    }
2897    scancode = (u_char)c;
2898
2899    /* do the /dev/random device a favour */
2900    if (!(flags & SCGETC_CN))
2901	add_keyboard_randomness(scancode);
2902
2903    if (cur_console->status & KBD_RAW_MODE)
2904	return scancode;
2905
2906    keycode = scancode & 0x7F;
2907    switch (esc_flag) {
2908    case 0x00:      /* normal scancode */
2909	switch(scancode) {
2910	case 0xB8:  /* left alt (compose key) */
2911	    if (compose) {
2912		compose = 0;
2913		if (chr > 255) {
2914		    do_bell(cur_console,
2915			BELL_PITCH, BELL_DURATION);
2916		    chr = 0;
2917		}
2918	    }
2919	    break;
2920	case 0x38:
2921	    if (!compose) {
2922		compose = 1;
2923		chr = 0;
2924	    }
2925	    break;
2926	case 0xE0:
2927	case 0xE1:
2928	    esc_flag = scancode;
2929	    goto next_code;
2930	}
2931	break;
2932    case 0xE0:      /* 0xE0 prefix */
2933	esc_flag = 0;
2934	switch (keycode) {
2935	case 0x1C:  /* right enter key */
2936	    keycode = 0x59;
2937	    break;
2938	case 0x1D:  /* right ctrl key */
2939	    keycode = 0x5A;
2940	    break;
2941	case 0x35:  /* keypad divide key */
2942	    keycode = 0x5B;
2943	    break;
2944	case 0x37:  /* print scrn key */
2945	    keycode = 0x5C;
2946	    break;
2947	case 0x38:  /* right alt key (alt gr) */
2948	    keycode = 0x5D;
2949	    break;
2950	case 0x47:  /* grey home key */
2951	    keycode = 0x5E;
2952	    break;
2953	case 0x48:  /* grey up arrow key */
2954	    keycode = 0x5F;
2955	    break;
2956	case 0x49:  /* grey page up key */
2957	    keycode = 0x60;
2958	    break;
2959	case 0x4B:  /* grey left arrow key */
2960	    keycode = 0x61;
2961	    break;
2962	case 0x4D:  /* grey right arrow key */
2963	    keycode = 0x62;
2964	    break;
2965	case 0x4F:  /* grey end key */
2966	    keycode = 0x63;
2967	    break;
2968	case 0x50:  /* grey down arrow key */
2969	    keycode = 0x64;
2970	    break;
2971	case 0x51:  /* grey page down key */
2972	    keycode = 0x65;
2973	    break;
2974	case 0x52:  /* grey insert key */
2975	    keycode = 0x66;
2976	    break;
2977	case 0x53:  /* grey delete key */
2978	    keycode = 0x67;
2979	    break;
2980
2981	/* the following 3 are only used on the MS "Natural" keyboard */
2982	case 0x5b:  /* left Window key */
2983	    keycode = 0x69;
2984	    break;
2985	case 0x5c:  /* right Window key */
2986	    keycode = 0x6a;
2987	    break;
2988	case 0x5d:  /* menu key */
2989	    keycode = 0x6b;
2990	    break;
2991	default:    /* ignore everything else */
2992	    goto next_code;
2993	}
2994	break;
2995    case 0xE1:      /* 0xE1 prefix */
2996	esc_flag = 0;
2997	if (keycode == 0x1D)
2998	    esc_flag = 0x1D;
2999	goto next_code;
3000	/* NOT REACHED */
3001    case 0x1D:      /* pause / break */
3002	esc_flag = 0;
3003	if (keycode != 0x45)
3004	    goto next_code;
3005	keycode = 0x68;
3006	break;
3007    }
3008
3009    /* if scroll-lock pressed allow history browsing */
3010    if (cur_console->history && cur_console->status & SLKED) {
3011	int i;
3012
3013	cur_console->status &= ~CURSOR_ENABLED;
3014	if (!(cur_console->status & BUFFER_SAVED)) {
3015	    cur_console->status |= BUFFER_SAVED;
3016	    cur_console->history_save = cur_console->history_head;
3017
3018	    /* copy screen into top of history buffer */
3019	    for (i=0; i<cur_console->ysize; i++) {
3020		bcopy(cur_console->scr_buf + (cur_console->xsize * i),
3021		       cur_console->history_head,
3022		       cur_console->xsize * sizeof(u_short));
3023		cur_console->history_head += cur_console->xsize;
3024		if (cur_console->history_head + cur_console->xsize >
3025		    cur_console->history + cur_console->history_size)
3026		    cur_console->history_head=cur_console->history;
3027	    }
3028	    cur_console->history_pos = cur_console->history_head;
3029	    history_to_screen(cur_console);
3030	}
3031	switch (scancode) {
3032	case 0x47:  /* home key */
3033	    cur_console->history_pos = cur_console->history_head;
3034	    history_to_screen(cur_console);
3035	    goto next_code;
3036
3037	case 0x4F:  /* end key */
3038	    cur_console->history_pos =
3039		WRAPHIST(cur_console, cur_console->history_head,
3040			 cur_console->xsize*cur_console->ysize);
3041	    history_to_screen(cur_console);
3042	    goto next_code;
3043
3044	case 0x48:  /* up arrow key */
3045	    if (history_up_line(cur_console))
3046		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3047	    goto next_code;
3048
3049	case 0x50:  /* down arrow key */
3050	    if (history_down_line(cur_console))
3051		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3052	    goto next_code;
3053
3054	case 0x49:  /* page up key */
3055	    for (i=0; i<cur_console->ysize; i++)
3056	    if (history_up_line(cur_console)) {
3057		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3058		break;
3059	    }
3060	    goto next_code;
3061
3062	case 0x51:  /* page down key */
3063	    for (i=0; i<cur_console->ysize; i++)
3064	    if (history_down_line(cur_console)) {
3065		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3066		break;
3067	    }
3068	    goto next_code;
3069	}
3070    }
3071
3072    if (compose) {
3073	switch (scancode) {
3074	/* key pressed process it */
3075	case 0x47: case 0x48: case 0x49:    /* keypad 7,8,9 */
3076	    chr = (scancode - 0x40) + chr*10;
3077	    goto next_code;
3078	case 0x4B: case 0x4C: case 0x4D:    /* keypad 4,5,6 */
3079	    chr = (scancode - 0x47) + chr*10;
3080	    goto next_code;
3081	case 0x4F: case 0x50: case 0x51:    /* keypad 1,2,3 */
3082	    chr = (scancode - 0x4E) + chr*10;
3083	    goto next_code;
3084	case 0x52:              /* keypad 0 */
3085	    chr *= 10;
3086	    goto next_code;
3087
3088	/* key release, no interest here */
3089	case 0xC7: case 0xC8: case 0xC9:    /* keypad 7,8,9 */
3090	case 0xCB: case 0xCC: case 0xCD:    /* keypad 4,5,6 */
3091	case 0xCF: case 0xD0: case 0xD1:    /* keypad 1,2,3 */
3092	case 0xD2:              /* keypad 0 */
3093	    goto next_code;
3094
3095	case 0x38:              /* left alt key */
3096	    break;
3097	default:
3098	    if (chr) {
3099		compose = chr = 0;
3100		do_bell(cur_console, BELL_PITCH, BELL_DURATION);
3101		goto next_code;
3102	    }
3103	    break;
3104	}
3105    }
3106
3107    state = (shfts ? 1 : 0 ) | (2 * (ctls ? 1 : 0)) | (4 * (alts ? 1 : 0));
3108    if ((!agrs && (cur_console->status & ALKED))
3109	|| (agrs && !(cur_console->status & ALKED)))
3110	keycode += ALTGR_OFFSET;
3111    key = &key_map.key[keycode];
3112    if ( ((key->flgs & FLAG_LOCK_C) && (cur_console->status & CLKED))
3113	 || ((key->flgs & FLAG_LOCK_N) && (cur_console->status & NLKED)) )
3114	state ^= 1;
3115
3116    /* Check for make/break */
3117    action = key->map[state];
3118    if (scancode & 0x80) {      /* key released */
3119	if (key->spcl & (0x80>>state)) {
3120	    switch (action) {
3121	    case LSH:
3122		shfts &= ~1;
3123		break;
3124	    case RSH:
3125		shfts &= ~2;
3126		break;
3127	    case LCTR:
3128		ctls &= ~1;
3129		break;
3130	    case RCTR:
3131		ctls &= ~2;
3132		break;
3133	    case LALT:
3134		alts &= ~1;
3135		break;
3136	    case RALT:
3137		alts &= ~2;
3138		break;
3139	    case NLK:
3140		nlkcnt = 0;
3141		break;
3142	    case CLK:
3143		clkcnt = 0;
3144		break;
3145	    case SLK:
3146		slkcnt = 0;
3147		break;
3148	    case ASH:
3149		agrs = 0;
3150		break;
3151	    case ALK:
3152		alkcnt = 0;
3153		break;
3154	    case META:
3155		metas = 0;
3156		break;
3157	    }
3158	}
3159	if (chr && !compose) {
3160	    action = chr;
3161	    chr = 0;
3162	    return(action);
3163	}
3164    } else {
3165	/* key pressed */
3166	if (key->spcl & (0x80>>state)) {
3167	    switch (action) {
3168	    /* LOCKING KEYS */
3169	    case NLK:
3170#ifdef SC_SPLASH_SCREEN
3171		toggle_splash_screen(cur_console); /* SOS XXX */
3172#endif
3173		if (!nlkcnt) {
3174		    nlkcnt++;
3175		    if (cur_console->status & NLKED)
3176			cur_console->status &= ~NLKED;
3177		    else
3178			cur_console->status |= NLKED;
3179		    update_leds(cur_console->status);
3180		}
3181		break;
3182	    case CLK:
3183		if (!clkcnt) {
3184		    clkcnt++;
3185		    if (cur_console->status & CLKED)
3186			cur_console->status &= ~CLKED;
3187		    else
3188			cur_console->status |= CLKED;
3189		    update_leds(cur_console->status);
3190		}
3191		break;
3192	    case SLK:
3193		if (!slkcnt) {
3194		    slkcnt++;
3195		    if (cur_console->status & SLKED) {
3196			cur_console->status &= ~SLKED;
3197			if (cur_console->status & BUFFER_SAVED){
3198			    int i;
3199			    u_short *ptr = cur_console->history_save;
3200
3201			    for (i=0; i<cur_console->ysize; i++) {
3202				bcopy(ptr,
3203				       cur_console->scr_buf +
3204				       (cur_console->xsize*i),
3205				       cur_console->xsize * sizeof(u_short));
3206				ptr += cur_console->xsize;
3207				if (ptr + cur_console->xsize >
3208				    cur_console->history +
3209				    cur_console->history_size)
3210				    ptr = cur_console->history;
3211			    }
3212			    cur_console->status &= ~BUFFER_SAVED;
3213			    cur_console->history_head=cur_console->history_save;
3214			    cur_console->status |= CURSOR_ENABLED;
3215			    mark_all(cur_console);
3216			}
3217			scstart(VIRTUAL_TTY(get_scr_num()));
3218		    }
3219		    else
3220			cur_console->status |= SLKED;
3221		    update_leds(cur_console->status);
3222		}
3223		break;
3224	    case ALK:
3225		if (!alkcnt) {
3226		    alkcnt++;
3227		    if (cur_console->status & ALKED)
3228			cur_console->status &= ~ALKED;
3229		    else
3230			cur_console->status |= ALKED;
3231		    update_leds(cur_console->status);
3232		}
3233		break;
3234
3235	    /* NON-LOCKING KEYS */
3236	    case NOP:
3237		break;
3238	    case SPSC:
3239#ifdef SC_SPLASH_SCREEN
3240		toggle_splash_screen(cur_console);
3241#endif
3242		break;
3243	    case RBT:
3244		shutdown_nice();
3245		break;
3246	    case SUSP:
3247#if NAPM > 0
3248		apm_suspend();
3249#endif
3250		break;
3251
3252	    case DBG:
3253#ifdef DDB          /* try to switch to console 0 */
3254		if (cur_console->smode.mode == VT_AUTO &&
3255		    console[0]->smode.mode == VT_AUTO)
3256		    switch_scr(cur_console, 0);
3257		Debugger("manual escape to debugger");
3258#else
3259		printf("No debugger in kernel\n");
3260#endif
3261		break;
3262	    case LSH:
3263		shfts |= 1;
3264		break;
3265	    case RSH:
3266		shfts |= 2;
3267		break;
3268	    case LCTR:
3269		ctls |= 1;
3270		break;
3271	    case RCTR:
3272		ctls |= 2;
3273		break;
3274	    case LALT:
3275		alts |= 1;
3276		break;
3277	    case RALT:
3278		alts |= 2;
3279		break;
3280	    case ASH:
3281		agrs = 1;
3282		break;
3283	    case META:
3284		metas = 1;
3285		break;
3286	    case NEXT:
3287		{
3288		int next, this = get_scr_num();
3289		for (next = this+1; next != this; next = (next+1)%MAXCONS) {
3290		    struct tty *tp = VIRTUAL_TTY(next);
3291		    if (tp->t_state & TS_ISOPEN) {
3292			switch_scr(cur_console, next);
3293			break;
3294		    }
3295		}
3296		}
3297		break;
3298	    case BTAB:
3299		return(BKEY);
3300	    default:
3301		if (action >= F_SCR && action <= L_SCR) {
3302		    switch_scr(cur_console, action - F_SCR);
3303		    break;
3304		}
3305		if (action >= F_FN && action <= L_FN)
3306		    action |= FKEY;
3307		return(action);
3308	    }
3309	}
3310	else {
3311	    if (metas)
3312		action |= MKEY;
3313	    return(action);
3314	}
3315    }
3316    goto next_code;
3317}
3318
3319int
3320scmmap(dev_t dev, int offset, int nprot)
3321{
3322    if (offset > 0x20000 - PAGE_SIZE)
3323	return -1;
3324    return i386_btop((VIDEOMEM + offset));
3325}
3326
3327/*
3328 * Calculate hardware attributes word using logical attributes mask and
3329 * hardware colors
3330 */
3331
3332static int
3333mask2attr(struct term_stat *term)
3334{
3335    int attr, mask = term->attr_mask;
3336
3337    if (mask & REVERSE_ATTR) {
3338	attr = ((mask & FOREGROUND_CHANGED) ?
3339		((term->cur_color & 0xF000) >> 4) :
3340		(term->rev_color & 0x0F00)) |
3341	       ((mask & BACKGROUND_CHANGED) ?
3342		((term->cur_color & 0x0F00) << 4) :
3343		(term->rev_color & 0xF000));
3344    } else
3345	attr = term->cur_color;
3346
3347    /* XXX: underline mapping for Hercules adapter can be better */
3348    if (mask & (BOLD_ATTR | UNDERLINE_ATTR))
3349	attr ^= 0x0800;
3350    if (mask & BLINK_ATTR)
3351	attr ^= 0x8000;
3352
3353    return attr;
3354}
3355
3356static void
3357set_keyboard(int command, int data)
3358{
3359    int s;
3360    int c;
3361
3362    if (sc_kbdc == NULL)
3363	return;
3364
3365    /* prevent the timeout routine from polling the keyboard */
3366    if (!kbdc_lock(sc_kbdc, TRUE))
3367	return;
3368
3369    /* disable the keyboard and mouse interrupt */
3370    s = spltty();
3371#if 0
3372    c = get_controller_command_byte(sc_kbdc);
3373    if ((c == -1)
3374	|| !set_controller_command_byte(sc_kbdc,
3375            kbdc_get_device_mask(sc_kbdc),
3376            KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
3377                | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
3378	/* CONTROLLER ERROR */
3379        kbdc_lock(sc_kbdc, FALSE);
3380	splx(s);
3381	return;
3382    }
3383    /*
3384     * Now that the keyboard controller is told not to generate
3385     * the keyboard and mouse interrupts, call `splx()' to allow
3386     * the other tty interrupts. The clock interrupt may also occur,
3387     * but the timeout routine (`scrn_timer()') will be blocked
3388     * by the lock flag set via `kbdc_lock()'
3389     */
3390    splx(s);
3391#endif
3392
3393    if (send_kbd_command_and_data(sc_kbdc, command, data) != KBD_ACK)
3394        send_kbd_command(sc_kbdc, KBDC_ENABLE_KBD);
3395
3396#if 0
3397    /* restore the interrupts */
3398    if (!set_controller_command_byte(sc_kbdc,
3399            kbdc_get_device_mask(sc_kbdc),
3400	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
3401	/* CONTROLLER ERROR */
3402    }
3403#else
3404    splx(s);
3405#endif
3406    kbdc_lock(sc_kbdc, FALSE);
3407}
3408
3409static void
3410update_leds(int which)
3411{
3412    static u_char xlate_leds[8] = { 0, 4, 2, 6, 1, 5, 3, 7 };
3413
3414    /* replace CAPS led with ALTGR led for ALTGR keyboards */
3415    if (key_map.n_keys > ALTGR_OFFSET) {
3416	if (which & ALKED)
3417	    which |= CLKED;
3418	else
3419	    which &= ~CLKED;
3420    }
3421
3422    set_keyboard(KBDC_SET_LEDS, xlate_leds[which & LED_MASK]);
3423}
3424
3425void
3426set_mode(scr_stat *scp)
3427{
3428    char *modetable;
3429    char special_modetable[64];
3430
3431    if (scp != cur_console)
3432	return;
3433
3434    /* setup video hardware for the given mode */
3435    switch (scp->mode) {
3436    case M_VGA_M80x60:
3437	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3438	goto special_80x60;
3439
3440    case M_VGA_C80x60:
3441	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3442special_80x60:
3443	special_modetable[2]  = 0x08;
3444	special_modetable[19] = 0x47;
3445	goto special_480l;
3446
3447    case M_VGA_M80x30:
3448	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3449	goto special_80x30;
3450
3451    case M_VGA_C80x30:
3452	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3453special_80x30:
3454	special_modetable[19] = 0x4f;
3455special_480l:
3456	special_modetable[9] |= 0xc0;
3457	special_modetable[16] = 0x08;
3458	special_modetable[17] = 0x3e;
3459	special_modetable[26] = 0xea;
3460	special_modetable[28] = 0xdf;
3461	special_modetable[31] = 0xe7;
3462	special_modetable[32] = 0x04;
3463	modetable = special_modetable;
3464	goto setup_mode;
3465
3466    case M_ENH_B80x43:
3467	bcopy(video_mode_ptr+(64*M_ENH_B80x25), &special_modetable, 64);
3468	goto special_80x43;
3469
3470    case M_ENH_C80x43:
3471	bcopy(video_mode_ptr+(64*M_ENH_C80x25), &special_modetable, 64);
3472special_80x43:
3473	special_modetable[28] = 87;
3474	goto special_80x50;
3475
3476    case M_VGA_M80x50:
3477	bcopy(video_mode_ptr+(64*M_VGA_M80x25), &special_modetable, 64);
3478	goto special_80x50;
3479
3480    case M_VGA_C80x50:
3481	bcopy(video_mode_ptr+(64*M_VGA_C80x25), &special_modetable, 64);
3482special_80x50:
3483	special_modetable[2] = 8;
3484	special_modetable[19] = 7;
3485	modetable = special_modetable;
3486	goto setup_mode;
3487
3488    case M_VGA_C40x25: case M_VGA_C80x25:
3489    case M_VGA_M80x25:
3490    case M_B40x25:     case M_C40x25:
3491    case M_B80x25:     case M_C80x25:
3492    case M_ENH_B40x25: case M_ENH_C40x25:
3493    case M_ENH_B80x25: case M_ENH_C80x25:
3494    case M_EGAMONO80x25:
3495
3496	modetable = video_mode_ptr + (scp->mode * 64);
3497setup_mode:
3498	set_vgaregs(modetable);
3499	scp->font_size = *(modetable + 2);
3500
3501	/* set font type (size) */
3502	if (scp->font_size < 14) {
3503	    if (fonts_loaded & FONT_8)
3504		copy_font(LOAD, FONT_8, font_8);
3505	    outb(TSIDX, 0x03); outb(TSREG, 0x0A);   /* font 2 */
3506	} else if (scp->font_size >= 16) {
3507	    if (fonts_loaded & FONT_16)
3508		copy_font(LOAD, FONT_16, font_16);
3509	    outb(TSIDX, 0x03); outb(TSREG, 0x00);   /* font 0 */
3510	} else {
3511	    if (fonts_loaded & FONT_14)
3512		copy_font(LOAD, FONT_14, font_14);
3513	    outb(TSIDX, 0x03); outb(TSREG, 0x05);   /* font 1 */
3514	}
3515	if (flags & CHAR_CURSOR)
3516	    set_destructive_cursor(scp);
3517	mark_all(scp);
3518	break;
3519
3520    case M_VGA_MODEX:
3521	/* start out with std 320x200x256 mode */
3522	bcopy(video_mode_ptr+(64*M_VGA_CG320), &special_modetable, 64);
3523	/* "unchain" the VGA mode */
3524	special_modetable[5-1+0x04] &= 0xf7;
3525	special_modetable[5-1+0x04] |= 0x04;
3526	/* turn off doubleword mode */
3527	special_modetable[10+0x14] &= 0xbf;
3528	/* turn off word adressing */
3529	special_modetable[10+0x17] |= 0x40;
3530	/* set logical screen width */
3531	special_modetable[10+0x13] = 80;
3532	/* set 240 lines */
3533	special_modetable[10+0x11] = 0x2c;
3534	special_modetable[10+0x06] = 0x0d;
3535	special_modetable[10+0x07] = 0x3e;
3536	special_modetable[10+0x10] = 0xea;
3537	special_modetable[10+0x11] = 0xac;
3538	special_modetable[10+0x12] = 0xdf;
3539	special_modetable[10+0x15] = 0xe7;
3540	special_modetable[10+0x16] = 0x06;
3541	/* set vertical sync polarity to reflect aspect ratio */
3542	special_modetable[9] = 0xe3;
3543
3544	modetable = special_modetable;
3545	goto setup_grmode;
3546
3547    case M_BG320:     case M_CG320:     case M_BG640:
3548    case M_CG320_D:   case M_CG640_E:
3549    case M_CG640x350: case M_ENH_CG640:
3550    case M_BG640x480: case M_CG640x480: case M_VGA_CG320:
3551	modetable = video_mode_ptr + (scp->mode * 64);
3552setup_grmode:
3553	set_vgaregs(modetable);
3554	scp->font_size = FONT_NONE;
3555	break;
3556
3557    default:
3558	/* call user defined function XXX */
3559	break;
3560    }
3561
3562    /* set border color for this (virtual) console */
3563    set_border(scp->border);
3564    return;
3565}
3566
3567void
3568set_border(u_char color)
3569{
3570    switch (crtc_type) {
3571    case KD_EGA:
3572    case KD_VGA:
3573        inb(crtc_addr + 6);		/* reset flip-flop */
3574        outb(ATC, 0x11); outb(ATC, color);
3575        inb(crtc_addr + 6);		/* reset flip-flop */
3576        outb(ATC, 0x20);		/* enable Palette */
3577	break;
3578    case KD_CGA:
3579	outb(crtc_addr + 5, color & 0x0f); /* color select register */
3580	break;
3581    case KD_MONO:
3582    case KD_HERCULES:
3583    default:
3584	break;
3585    }
3586}
3587
3588static void
3589set_vgaregs(char *modetable)
3590{
3591    int i, s = splhigh();
3592
3593    outb(TSIDX, 0x00); outb(TSREG, 0x01);   	/* stop sequencer */
3594    outb(TSIDX, 0x07); outb(TSREG, 0x00);   	/* unlock registers */
3595    for (i=0; i<4; i++) {           		/* program sequencer */
3596	outb(TSIDX, i+1);
3597	outb(TSREG, modetable[i+5]);
3598    }
3599    outb(MISC, modetable[9]);       		/* set dot-clock */
3600    outb(TSIDX, 0x00); outb(TSREG, 0x03);   	/* start sequencer */
3601    outb(crtc_addr, 0x11);
3602    outb(crtc_addr+1, inb(crtc_addr+1) & 0x7F);
3603    for (i=0; i<25; i++) {          		/* program crtc */
3604	outb(crtc_addr, i);
3605	if (i == 14 || i == 15)     		/* no hardware cursor */
3606	    outb(crtc_addr+1, 0xff);
3607	else
3608	    outb(crtc_addr+1, modetable[i+10]);
3609    }
3610    inb(crtc_addr+6);           		/* reset flip-flop */
3611    for (i=0; i<20; i++) {          		/* program attribute ctrl */
3612	outb(ATC, i);
3613	outb(ATC, modetable[i+35]);
3614    }
3615    for (i=0; i<9; i++) {           		/* program graph data ctrl */
3616	outb(GDCIDX, i);
3617	outb(GDCREG, modetable[i+55]);
3618    }
3619    inb(crtc_addr+6);           		/* reset flip-flop */
3620    outb(ATC, 0x20);            		/* enable palette */
3621    splx(s);
3622}
3623
3624static void
3625read_vgaregs(char *buf)
3626{
3627    int i, j;
3628    int s;
3629
3630    bzero(buf, 64);
3631
3632    s = splhigh();
3633
3634    outb(TSIDX, 0x00); outb(TSREG, 0x01);   	/* stop sequencer */
3635    outb(TSIDX, 0x07); outb(TSREG, 0x00);   	/* unlock registers */
3636    for (i=0, j=5; i<4; i++) {
3637	outb(TSIDX, i+1);
3638	buf[j++] = inb(TSREG);
3639    }
3640    buf[9] = inb(MISC + 10);      		/* dot-clock */
3641    outb(TSIDX, 0x00); outb(TSREG, 0x03);   	/* start sequencer */
3642
3643    for (i=0, j=10; i<25; i++) {       		/* crtc */
3644	outb(crtc_addr, i);
3645	buf[j++] = inb(crtc_addr+1);
3646    }
3647    for (i=0, j=35; i<20; i++) {          	/* attribute ctrl */
3648        inb(crtc_addr+6);           		/* reset flip-flop */
3649	outb(ATC, i);
3650	buf[j++] = inb(ATC + 1);
3651    }
3652    for (i=0, j=55; i<9; i++) {           	/* graph data ctrl */
3653	outb(GDCIDX, i);
3654	buf[j++] = inb(GDCREG);
3655    }
3656    inb(crtc_addr+6);           		/* reset flip-flop */
3657    outb(ATC, 0x20);            		/* enable palette */
3658
3659    buf[0] = *(char *)pa_to_va(0x44a);		/* COLS */
3660    buf[1] = *(char *)pa_to_va(0x484);		/* ROWS */
3661    buf[2] = *(char *)pa_to_va(0x485);		/* POINTS */
3662    buf[3] = *(char *)pa_to_va(0x44c);
3663    buf[4] = *(char *)pa_to_va(0x44d);
3664
3665    splx(s);
3666}
3667
3668static int
3669comp_vgaregs(u_char *buf1, u_char *buf2)
3670{
3671    int i;
3672
3673    for(i = 0; i < 20; ++i) {
3674	if (*buf1++ != *buf2++)
3675	    return 1;
3676    }
3677    buf1 += 2;  /* skip the cursor shape */
3678    buf2 += 2;
3679    for(i = 22; i < 24; ++i) {
3680	if (*buf1++ != *buf2++)
3681	    return 1;
3682    }
3683    buf1 += 2;  /* skip the cursor position */
3684    buf2 += 2;
3685    for(i = 26; i < 64; ++i) {
3686	if (*buf1++ != *buf2++)
3687	    return 1;
3688    }
3689    return 0;
3690}
3691
3692static void
3693dump_vgaregs(u_char *buf)
3694{
3695    int i;
3696
3697    for(i = 0; i < 64;) {
3698	printf("%02x ", buf[i]);
3699	if ((++i % 16) == 0)
3700	    printf("\n");
3701    }
3702}
3703
3704static void
3705set_font_mode()
3706{
3707    int s = splhigh();
3708
3709    /* setup vga for loading fonts (graphics plane mode) */
3710    inb(crtc_addr+6);           		/* reset flip-flop */
3711    outb(ATC, 0x10); outb(ATC, 0x01);
3712    inb(crtc_addr+6);               		/* reset flip-flop */
3713    outb(ATC, 0x20);            		/* enable palette */
3714
3715#if SLOW_VGA
3716    outb(TSIDX, 0x02); outb(TSREG, 0x04);
3717    outb(TSIDX, 0x04); outb(TSREG, 0x06);
3718    outb(GDCIDX, 0x04); outb(GDCREG, 0x02);
3719    outb(GDCIDX, 0x05); outb(GDCREG, 0x00);
3720    outb(GDCIDX, 0x06); outb(GDCREG, 0x05);
3721#else
3722    outw(TSIDX, 0x0402);
3723    outw(TSIDX, 0x0604);
3724    outw(GDCIDX, 0x0204);
3725    outw(GDCIDX, 0x0005);
3726    outw(GDCIDX, 0x0506);               /* addr = a0000, 64kb */
3727#endif
3728    splx(s);
3729}
3730
3731static void
3732set_normal_mode()
3733{
3734    char *modetable;
3735    int s = splhigh();
3736
3737    switch (cur_console->mode) {
3738    case M_VGA_M80x60:
3739    case M_VGA_M80x50:
3740    case M_VGA_M80x30:
3741	modetable = video_mode_ptr + (64*M_VGA_M80x25);
3742	break;
3743
3744    case M_VGA_C80x60:
3745    case M_VGA_C80x50:
3746    case M_VGA_C80x30:
3747	modetable = video_mode_ptr + (64*M_VGA_C80x25);
3748	break;
3749
3750    case M_ENH_B80x43:
3751	modetable = video_mode_ptr + (64*M_ENH_B80x25);
3752	break;
3753
3754    case M_ENH_C80x43:
3755	modetable = video_mode_ptr + (64*M_ENH_C80x25);
3756	break;
3757
3758    case M_VGA_C40x25: case M_VGA_C80x25:
3759    case M_VGA_M80x25:
3760    case M_B40x25:     case M_C40x25:
3761    case M_B80x25:     case M_C80x25:
3762    case M_ENH_B40x25: case M_ENH_C40x25:
3763    case M_ENH_B80x25: case M_ENH_C80x25:
3764    case M_EGAMONO80x25:
3765
3766    case M_BG320:     case M_CG320:     case M_BG640:
3767    case M_CG320_D:   case M_CG640_E:
3768    case M_CG640x350: case M_ENH_CG640:
3769    case M_BG640x480: case M_CG640x480: case M_VGA_CG320:
3770	modetable = video_mode_ptr + (cur_console->mode * 64);
3771	break;
3772
3773    default:
3774	modetable = video_mode_ptr + (64*M_VGA_C80x25);
3775    }
3776
3777    if (video_mode_ptr == NULL)
3778	modetable = vgaregs;
3779
3780    /* setup vga for normal operation mode again */
3781    inb(crtc_addr+6);           		/* reset flip-flop */
3782    outb(ATC, 0x10); outb(ATC, modetable[0x10+35]);
3783    inb(crtc_addr+6);               		/* reset flip-flop */
3784    outb(ATC, 0x20);            		/* enable palette */
3785#if SLOW_VGA
3786    outb(TSIDX, 0x02); outb(TSREG, modetable[0x02+4]);
3787    outb(TSIDX, 0x04); outb(TSREG, modetable[0x04+4]);
3788    outb(GDCIDX, 0x04); outb(GDCREG, modetable[0x04+55]);
3789    outb(GDCIDX, 0x05); outb(GDCREG, modetable[0x05+55]);
3790    outb(GDCIDX, 0x06); outb(GDCREG, modetable[0x06+55]);
3791    if (crtc_addr == MONO_BASE) {
3792	outb(GDCIDX, 0x06); outb(GDCREG,(modetable[0x06+55] & 0x03) | 0x08);
3793    }
3794    else {
3795	outb(GDCIDX, 0x06); outb(GDCREG,(modetable[0x06+55] & 0x03) | 0x0c);
3796    }
3797#else
3798    outw(TSIDX, 0x0002 | (modetable[0x02+4]<<8));
3799    outw(TSIDX, 0x0004 | (modetable[0x04+4]<<8));
3800    outw(GDCIDX, 0x0004 | (modetable[0x04+55]<<8));
3801    outw(GDCIDX, 0x0005 | (modetable[0x05+55]<<8));
3802    if (crtc_addr == MONO_BASE)
3803        outw(GDCIDX, 0x0006 | (((modetable[0x06+55] & 0x03) | 0x08)<<8));
3804    else
3805        outw(GDCIDX, 0x0006 | (((modetable[0x06+55] & 0x03) | 0x0c)<<8));
3806#endif
3807    splx(s);
3808}
3809
3810void
3811copy_font(int operation, int font_type, char* font_image)
3812{
3813    int ch, line, segment, fontsize;
3814    u_char val;
3815
3816    /* dont mess with console we dont know video mode on */
3817    if (cur_console->status & UNKNOWN_MODE)
3818	return;
3819
3820    switch (font_type) {
3821    default:
3822    case FONT_8:
3823	segment = 0x8000;
3824	fontsize = 8;
3825	break;
3826    case FONT_14:
3827	segment = 0x4000;
3828	fontsize = 14;
3829	break;
3830    case FONT_16:
3831	segment = 0x0000;
3832	fontsize = 16;
3833	break;
3834    }
3835    outb(TSIDX, 0x01); val = inb(TSREG);        /* disable screen */
3836    outb(TSIDX, 0x01); outb(TSREG, val | 0x20);
3837    set_font_mode();
3838    for (ch=0; ch < 256; ch++)
3839	for (line=0; line < fontsize; line++)
3840	if (operation)
3841	    *(char *)pa_to_va(VIDEOMEM+(segment)+(ch*32)+line) =
3842		    font_image[(ch*fontsize)+line];
3843	else
3844	    font_image[(ch*fontsize)+line] =
3845	    *(char *)pa_to_va(VIDEOMEM+(segment)+(ch*32)+line);
3846    set_normal_mode();
3847    outb(TSIDX, 0x01); outb(TSREG, val & 0xDF); /* enable screen */
3848}
3849
3850static void
3851set_destructive_cursor(scr_stat *scp)
3852{
3853    u_char cursor[32];
3854    caddr_t address;
3855    int i;
3856    char *font_buffer;
3857
3858
3859    if (scp->font_size < 14) {
3860	font_buffer = font_8;
3861	address = (caddr_t)VIDEOMEM + 0x8000;
3862    }
3863    else if (scp->font_size >= 16) {
3864	font_buffer = font_16;
3865	address = (caddr_t)VIDEOMEM;
3866    }
3867    else {
3868	font_buffer = font_14;
3869	address = (caddr_t)VIDEOMEM + 0x4000;
3870    }
3871
3872    if (scp->status & MOUSE_VISIBLE) {
3873	if ((scp->cursor_saveunder & 0xff) == 0xd0)
3874    	    bcopy(&scp->mouse_cursor[0], cursor, scp->font_size);
3875	else if ((scp->cursor_saveunder & 0xff) == 0xd1)
3876    	    bcopy(&scp->mouse_cursor[32], cursor, scp->font_size);
3877	else if ((scp->cursor_saveunder & 0xff) == 0xd2)
3878    	    bcopy(&scp->mouse_cursor[64], cursor, scp->font_size);
3879	else if ((scp->cursor_saveunder & 0xff) == 0xd3)
3880    	    bcopy(&scp->mouse_cursor[96], cursor, scp->font_size);
3881	else
3882	    bcopy(font_buffer+((scp->cursor_saveunder & 0xff)*scp->font_size),
3883 	       	   cursor, scp->font_size);
3884    }
3885    else
3886    	bcopy(font_buffer + ((scp->cursor_saveunder & 0xff) * scp->font_size),
3887 	       cursor, scp->font_size);
3888    for (i=0; i<32; i++)
3889	if ((i >= scp->cursor_start && i <= scp->cursor_end) ||
3890	    (scp->cursor_start >= scp->font_size && i == scp->font_size - 1))
3891	    cursor[i] |= 0xff;
3892#if 1
3893    while (!(inb(crtc_addr+6) & 0x08)) /* wait for vertical retrace */ ;
3894#endif
3895    set_font_mode();
3896    sc_bcopy(cursor, (char *)pa_to_va(address) + DEAD_CHAR * 32, 32);
3897    set_normal_mode();
3898}
3899
3900static void
3901set_mouse_pos(scr_stat *scp)
3902{
3903    static int last_xpos = -1, last_ypos = -1;
3904
3905    if (scp->mouse_xpos < 0)
3906	scp->mouse_xpos = 0;
3907    if (scp->mouse_ypos < 0)
3908	scp->mouse_ypos = 0;
3909    if (scp->status & UNKNOWN_MODE) {
3910        if (scp->mouse_xpos > scp->xpixel-1)
3911	    scp->mouse_xpos = scp->xpixel-1;
3912        if (scp->mouse_ypos > scp->ypixel-1)
3913	    scp->mouse_ypos = scp->ypixel-1;
3914	return;
3915    }
3916    if (scp->mouse_xpos > (scp->xsize*8)-1)
3917	scp->mouse_xpos = (scp->xsize*8)-1;
3918    if (scp->mouse_ypos > (scp->ysize*scp->font_size)-1)
3919	scp->mouse_ypos = (scp->ysize*scp->font_size)-1;
3920
3921    if (scp->mouse_xpos != last_xpos || scp->mouse_ypos != last_ypos) {
3922	scp->status |= MOUSE_MOVED;
3923
3924    	scp->mouse_pos = scp->scr_buf +
3925	    ((scp->mouse_ypos/scp->font_size)*scp->xsize + scp->mouse_xpos/8);
3926
3927	if ((scp->status & MOUSE_VISIBLE) && (scp->status & MOUSE_CUTTING)) {
3928	    u_short *ptr;
3929	    int i = 0;
3930
3931	    mark_for_update(scp, scp->mouse_cut_start - scp->scr_buf);
3932	    mark_for_update(scp, scp->mouse_cut_end - scp->scr_buf);
3933	    scp->mouse_cut_end = scp->mouse_pos;
3934	    for (ptr = (scp->mouse_cut_start > scp->mouse_cut_end
3935			? scp->mouse_cut_end : scp->mouse_cut_start);
3936		 ptr <= (scp->mouse_cut_start > scp->mouse_cut_end
3937			 ? scp->mouse_cut_start : scp->mouse_cut_end);
3938	    	 ptr++) {
3939	        cut_buffer[i++] = *ptr & 0xff;
3940	        if (((ptr - scp->scr_buf) % scp->xsize) == (scp->xsize - 1)) {
3941		    cut_buffer[i++] = '\n';
3942	        }
3943	    }
3944	    cut_buffer[i] = 0x00;
3945        }
3946    }
3947}
3948
3949static void
3950mouse_cut_start(scr_stat *scp)
3951{
3952    int i;
3953
3954    if (scp->status & MOUSE_VISIBLE) {
3955	if (scp->mouse_pos == scp->mouse_cut_start &&
3956	    scp->mouse_cut_start == scp->mouse_cut_end) {
3957	    cut_buffer[0] = 0x00;
3958	    remove_cutmarking(scp);
3959	}
3960	else {
3961	    scp->mouse_cut_start = scp->mouse_cut_end = scp->mouse_pos;
3962	    cut_buffer[0] = *scp->mouse_cut_start & 0xff;
3963	    cut_buffer[1] = 0x00;
3964	    scp->status |= MOUSE_CUTTING;
3965	}
3966    	mark_all(scp);
3967	/* delete all other screens cut markings */
3968	for (i=0; i<MAXCONS; i++) {
3969	    if (console[i] == NULL || console[i] == scp)
3970		continue;
3971	    remove_cutmarking(console[i]);
3972	}
3973    }
3974}
3975
3976static void
3977mouse_cut_end(scr_stat *scp)
3978{
3979    if (scp->status & MOUSE_VISIBLE) {
3980	scp->status &= ~MOUSE_CUTTING;
3981    }
3982}
3983
3984static void
3985mouse_paste(scr_stat *scp)
3986{
3987    if (scp->status & MOUSE_VISIBLE) {
3988	struct tty *tp;
3989	u_char *ptr = cut_buffer;
3990
3991	tp = VIRTUAL_TTY(get_scr_num());
3992	while (*ptr)
3993	    (*linesw[tp->t_line].l_rint)(scr_rmap[*ptr++], tp);
3994    }
3995}
3996
3997static void
3998draw_mouse_image(scr_stat *scp)
3999{
4000    caddr_t address;
4001    int i;
4002    char *font_buffer;
4003    u_short buffer[32];
4004    u_short xoffset, yoffset;
4005    u_short *crt_pos = Crtat + (scp->mouse_pos - scp->scr_buf);
4006    int font_size = scp->font_size;
4007
4008    if (font_size < 14) {
4009	font_buffer = font_8;
4010	address = (caddr_t)VIDEOMEM + 0x8000;
4011    }
4012    else if (font_size >= 16) {
4013	font_buffer = font_16;
4014	address = (caddr_t)VIDEOMEM;
4015    }
4016    else {
4017	font_buffer = font_14;
4018	address = (caddr_t)VIDEOMEM + 0x4000;
4019    }
4020    xoffset = scp->mouse_xpos % 8;
4021    yoffset = scp->mouse_ypos % font_size;
4022
4023    /* prepare mousepointer char's bitmaps */
4024    bcopy(font_buffer + ((*(scp->mouse_pos) & 0xff) * font_size),
4025	   &scp->mouse_cursor[0], font_size);
4026    bcopy(font_buffer + ((*(scp->mouse_pos+1) & 0xff) * font_size),
4027	   &scp->mouse_cursor[32], font_size);
4028    bcopy(font_buffer + ((*(scp->mouse_pos+scp->xsize) & 0xff) * font_size),
4029	   &scp->mouse_cursor[64], font_size);
4030    bcopy(font_buffer + ((*(scp->mouse_pos+scp->xsize+1) & 0xff) * font_size),
4031	   &scp->mouse_cursor[96], font_size);
4032    for (i=0; i<font_size; i++) {
4033	buffer[i] = scp->mouse_cursor[i]<<8 | scp->mouse_cursor[i+32];
4034	buffer[i+font_size]=scp->mouse_cursor[i+64]<<8|scp->mouse_cursor[i+96];
4035    }
4036
4037    /* now and-or in the mousepointer image */
4038    for (i=0; i<16; i++) {
4039	buffer[i+yoffset] =
4040	    ( buffer[i+yoffset] & ~(mouse_and_mask[i] >> xoffset))
4041	    | (mouse_or_mask[i] >> xoffset);
4042    }
4043    for (i=0; i<font_size; i++) {
4044	scp->mouse_cursor[i] = (buffer[i] & 0xff00) >> 8;
4045	scp->mouse_cursor[i+32] = buffer[i] & 0xff;
4046	scp->mouse_cursor[i+64] = (buffer[i+font_size] & 0xff00) >> 8;
4047	scp->mouse_cursor[i+96] = buffer[i+font_size] & 0xff;
4048    }
4049
4050    scp->mouse_oldpos = scp->mouse_pos;
4051
4052    /* wait for vertical retrace to avoid jitter on some videocards */
4053#if 1
4054    while (!(inb(crtc_addr+6) & 0x08)) /* idle */ ;
4055#endif
4056    set_font_mode();
4057    sc_bcopy(scp->mouse_cursor, (char *)pa_to_va(address) + 0xd0 * 32, 128);
4058    set_normal_mode();
4059    *(crt_pos) = (*(scp->mouse_pos)&0xff00)|0xd0;
4060    *(crt_pos+scp->xsize) = (*(scp->mouse_pos+scp->xsize)&0xff00)|0xd2;
4061    if (scp->mouse_xpos < (scp->xsize-1)*8) {
4062    	*(crt_pos+1) = (*(scp->mouse_pos+1)&0xff00)|0xd1;
4063    	*(crt_pos+scp->xsize+1) = (*(scp->mouse_pos+scp->xsize+1)&0xff00)|0xd3;
4064    }
4065    mark_for_update(scp, scp->mouse_pos - scp->scr_buf);
4066    mark_for_update(scp, scp->mouse_pos + scp->xsize + 1 - scp->scr_buf);
4067}
4068
4069static void
4070remove_mouse_image(scr_stat *scp)
4071{
4072    u_short *crt_pos = Crtat + (scp->mouse_oldpos - scp->scr_buf);
4073
4074    *(crt_pos) = *(scp->mouse_oldpos);
4075    *(crt_pos+1) = *(scp->mouse_oldpos+1);
4076    *(crt_pos+scp->xsize) = *(scp->mouse_oldpos+scp->xsize);
4077    *(crt_pos+scp->xsize+1) = *(scp->mouse_oldpos+scp->xsize+1);
4078    mark_for_update(scp, scp->mouse_oldpos - scp->scr_buf);
4079    mark_for_update(scp, scp->mouse_oldpos + scp->xsize + 1 - scp->scr_buf);
4080}
4081
4082static void
4083draw_cutmarking(scr_stat *scp)
4084{
4085    u_short *ptr;
4086    u_short och, nch;
4087
4088    for (ptr=scp->scr_buf; ptr<=(scp->scr_buf+(scp->xsize*scp->ysize)); ptr++) {
4089	nch = och = *(Crtat + (ptr - scp->scr_buf));
4090	/* are we outside the selected area ? */
4091	if ( ptr < (scp->mouse_cut_start > scp->mouse_cut_end ?
4092	            scp->mouse_cut_end : scp->mouse_cut_start) ||
4093	     ptr > (scp->mouse_cut_start > scp->mouse_cut_end ?
4094	            scp->mouse_cut_start : scp->mouse_cut_end)) {
4095	    if (ptr != scp->cursor_pos)
4096		nch = (och & 0xff) | (*ptr & 0xff00);
4097	}
4098	else {
4099	    /* are we clear of the cursor image ? */
4100	    if (ptr != scp->cursor_pos)
4101		nch = (och & 0x88ff) | (*ptr & 0x7000)>>4 | (*ptr & 0x0700)<<4;
4102	    else {
4103		if (flags & CHAR_CURSOR)
4104		    nch = (och & 0x88ff)|(*ptr & 0x7000)>>4|(*ptr & 0x0700)<<4;
4105		else
4106		    if (!(flags & BLINK_CURSOR))
4107		        nch = (och & 0xff) | (*ptr & 0xff00);
4108	    }
4109	}
4110	if (nch != och)
4111	    *(Crtat + (ptr - scp->scr_buf)) = nch;
4112    }
4113}
4114
4115static void
4116remove_cutmarking(scr_stat *scp)
4117{
4118    scp->mouse_cut_start = scp->mouse_cut_end = NULL;
4119    scp->status &= ~MOUSE_CUTTING;
4120    mark_all(scp);
4121}
4122
4123static void
4124save_palette(void)
4125{
4126    int i;
4127
4128    outb(PALRADR, 0x00);
4129    for (i=0x00; i<0x300; i++)
4130	palette[i] = inb(PALDATA);
4131    inb(crtc_addr+6);           /* reset flip/flop */
4132}
4133
4134void
4135load_palette(char *palette)
4136{
4137    int i;
4138
4139    outb(PIXMASK, 0xFF);            /* no pixelmask */
4140    outb(PALWADR, 0x00);
4141    for (i=0x00; i<0x300; i++)
4142	 outb(PALDATA, palette[i]);
4143    inb(crtc_addr+6);           /* reset flip/flop */
4144    outb(ATC, 0x20);            /* enable palette */
4145}
4146
4147static void
4148do_bell(scr_stat *scp, int pitch, int duration)
4149{
4150    if (flags & VISUAL_BELL) {
4151	if (blink_in_progress)
4152	    return;
4153	blink_in_progress = 4;
4154	if (scp != cur_console)
4155	    blink_in_progress += 2;
4156	blink_screen(cur_console);
4157    } else {
4158	if (scp != cur_console)
4159	    pitch *= 2;
4160	sysbeep(pitch, duration);
4161    }
4162}
4163
4164static void
4165blink_screen(void *arg)
4166{
4167    scr_stat *scp = arg;
4168
4169    if ((scp->status & UNKNOWN_MODE) || (blink_in_progress <= 1)) {
4170	blink_in_progress = FALSE;
4171    	mark_all(scp);
4172	if (delayed_next_scr)
4173	    switch_scr(scp, delayed_next_scr - 1);
4174    }
4175    else {
4176	if (blink_in_progress & 1)
4177	    fillw(kernel_default.std_color | scr_map[0x20],
4178		  Crtat, scp->xsize * scp->ysize);
4179	else
4180	    fillw(kernel_default.rev_color | scr_map[0x20],
4181		  Crtat, scp->xsize * scp->ysize);
4182	blink_in_progress--;
4183	timeout(blink_screen, scp, hz / 10);
4184    }
4185}
4186
4187#ifdef SC_SPLASH_SCREEN
4188static void
4189toggle_splash_screen(scr_stat *scp)
4190{
4191    static int toggle = 0;
4192    static u_char save_mode;
4193    int s;
4194
4195    if (video_mode_ptr == NULL)
4196	return;
4197
4198    s = splhigh();
4199    if (toggle) {
4200	scp->mode = save_mode;
4201	scp->status &= ~UNKNOWN_MODE;
4202	set_mode(scp);
4203	load_palette(palette);
4204	toggle = 0;
4205    }
4206    else {
4207	save_mode = scp->mode;
4208	scp->mode = M_VGA_CG320;
4209	scp->status |= UNKNOWN_MODE;
4210	set_mode(scp);
4211	/* load image */
4212	toggle = 1;
4213    }
4214    splx(s);
4215}
4216#endif
4217#endif /* NSC */
4218