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