xref: /freebsd/sys/dev/atkbdc/psm.c (revision 2ad872c5794e4c26fdf6ed219ad3f09ca0d5304a)
1 /*-
2  * Copyright (c) 1992, 1993 Erik Forsberg.
3  * Copyright (c) 1996, 1997 Kazutaka YOKOTA.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * THIS SOFTWARE IS PROVIDED BY ``AS IS'' AND ANY EXPRESS OR IMPLIED
13  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
15  * NO EVENT SHALL I BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
16  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
17  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
18  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
19  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
20  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
21  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22  *
23  * $Id: psm.c,v 1.1 1998/11/08 18:43:03 dfr Exp $
24  */
25 
26 /*
27  *  Ported to 386bsd Oct 17, 1992
28  *  Sandi Donno, Computer Science, University of Cape Town, South Africa
29  *  Please send bug reports to sandi@cs.uct.ac.za
30  *
31  *  Thanks are also due to Rick Macklem, rick@snowhite.cis.uoguelph.ca -
32  *  although I was only partially successful in getting the alpha release
33  *  of his "driver for the Logitech and ATI Inport Bus mice for use with
34  *  386bsd and the X386 port" to work with my Microsoft mouse, I nevertheless
35  *  found his code to be an invaluable reference when porting this driver
36  *  to 386bsd.
37  *
38  *  Further modifications for latest 386BSD+patchkit and port to NetBSD,
39  *  Andrew Herbert <andrew@werple.apana.org.au> - 8 June 1993
40  *
41  *  Cloned from the Microsoft Bus Mouse driver, also by Erik Forsberg, by
42  *  Andrew Herbert - 12 June 1993
43  *
44  *  Modified for PS/2 mouse by Charles Hannum <mycroft@ai.mit.edu>
45  *  - 13 June 1993
46  *
47  *  Modified for PS/2 AUX mouse by Shoji Yuen <yuen@nuie.nagoya-u.ac.jp>
48  *  - 24 October 1993
49  *
50  *  Hardware access routines and probe logic rewritten by
51  *  Kazutaka Yokota <yokota@zodiac.mech.utsunomiya-u.ac.jp>
52  *  - 3, 14, 22 October 1996.
53  *  - 12 November 1996. IOCTLs and rearranging `psmread', `psmioctl'...
54  *  - 14, 30 November 1996. Uses `kbdio.c'.
55  *  - 13 December 1996. Uses queuing version of `kbdio.c'.
56  *  - January/February 1997. Tweaked probe logic for
57  *    HiNote UltraII/Latitude/Armada laptops.
58  *  - 30 July 1997. Added APM support.
59  *  - 5 March 1997. Defined driver configuration flags (PSM_CONFIG_XXX).
60  *    Improved sync check logic.
61  *    Vendor specific support routines.
62  */
63 
64 #include "psm.h"
65 #include "opt_devfs.h"
66 #include "opt_psm.h"
67 
68 #if NPSM > 0
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/module.h>
74 #include <sys/bus.h>
75 #include <sys/conf.h>
76 #include <sys/poll.h>
77 #include <sys/syslog.h>
78 #include <sys/malloc.h>
79 #include <sys/rman.h>
80 #ifdef DEVFS
81 #include <sys/devfsext.h>
82 #endif
83 #include <sys/select.h>
84 #include <sys/uio.h>
85 
86 #include <machine/clock.h>
87 #include <machine/limits.h>
88 #include <machine/mouse.h>
89 #include <machine/resource.h>
90 
91 #include <isa/isareg.h>
92 #include <isa/isavar.h>
93 #include <isa/kbdio.h>
94 
95 /*
96  * Driver specific options: the following options may be set by
97  * `options' statements in the kernel configuration file.
98  */
99 
100 /* debugging */
101 #ifndef PSM_DEBUG
102 #define PSM_DEBUG	0	/* logging: 0: none, 1: brief, 2: verbose */
103 #endif
104 
105 /* features */
106 
107 /* #define PSM_HOOKAPM	   	   hook the APM resume event */
108 /* #define PSM_RESETAFTERSUSPEND   reset the device at the resume event */
109 
110 #if NAPM <= 0
111 #undef PSM_HOOKAPM
112 #endif /* NAPM */
113 
114 #ifndef PSM_HOOKAPM
115 #undef PSM_RESETAFTERSUSPEND
116 #endif /* PSM_HOOKAPM */
117 
118 /* end of driver specific options */
119 
120 /* input queue */
121 #define PSM_BUFSIZE		960
122 #define PSM_SMALLBUFSIZE	240
123 
124 /* operation levels */
125 #define PSM_LEVEL_BASE		0
126 #define PSM_LEVEL_STANDARD	1
127 #define PSM_LEVEL_NATIVE	2
128 #define PSM_LEVEL_MIN		PSM_LEVEL_BASE
129 #define PSM_LEVEL_MAX		PSM_LEVEL_NATIVE
130 
131 /* some macros */
132 #define PSM_UNIT(dev)		(minor(dev) >> 1)
133 #define PSM_NBLOCKIO(dev)	(minor(dev) & 1)
134 #define PSM_MKMINOR(unit,block)	(((unit) << 1) | ((block) ? 0:1))
135 
136 #ifndef max
137 #define max(x,y)		((x) > (y) ? (x) : (y))
138 #endif
139 #ifndef min
140 #define min(x,y)		((x) < (y) ? (x) : (y))
141 #endif
142 
143 /* ring buffer */
144 typedef struct ringbuf {
145     int           count;	/* # of valid elements in the buffer */
146     int           head;		/* head pointer */
147     int           tail;		/* tail poiner */
148     unsigned char buf[PSM_BUFSIZE];
149 } ringbuf_t;
150 
151 /* driver control block */
152 struct psm_softc {		/* Driver status information */
153     struct selinfo rsel;	/* Process selecting for Input */
154     unsigned char state;	/* Mouse driver state */
155     int           config;	/* driver configuration flags */
156     int           flags;	/* other flags */
157     KBDC          kbdc;		/* handle to access the keyboard controller */
158     int           addr;		/* I/O port address */
159     mousehw_t     hw;		/* hardware information */
160     mousemode_t   mode;		/* operation mode */
161     mousemode_t   dflt_mode;	/* default operation mode */
162     mousestatus_t status;	/* accumulated mouse movement */
163     ringbuf_t     queue;	/* mouse status queue */
164     unsigned char ipacket[16];	/* interim input buffer */
165     int           inputbytes;	/* # of bytes in the input buffer */
166     int           button;	/* the latest button state */
167 #ifdef DEVFS
168     void          *devfs_token;
169     void          *b_devfs_token;
170 #endif
171 #ifdef PSM_HOOKAPM
172     struct apmhook resumehook;
173 #endif
174 };
175 devclass_t psm_devclass;
176 #define PSM_SOFTC(unit)	((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
177 
178 /* driver state flags (state) */
179 #define PSM_VALID		0x80
180 #define PSM_OPEN		1	/* Device is open */
181 #define PSM_ASLP		2	/* Waiting for mouse data */
182 
183 /* driver configuration flags (config) */
184 #define PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
185 #define PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
186 #define PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
187 
188 #define PSM_CONFIG_FLAGS	(PSM_CONFIG_RESOLUTION 		\
189 				    | PSM_CONFIG_ACCEL		\
190 				    | PSM_CONFIG_NOCHECKSYNC)
191 
192 /* other flags (flags) */
193 /*
194  * Pass mouse data packet to the user land program `as is', even if
195  * the mouse has vendor-specific enhanced features and uses non-standard
196  * packet format.  Otherwise manipulate the mouse data packet so that
197  * it can be recognized by the programs which can only understand
198  * the standard packet format.
199 */
200 #define PSM_FLAGS_NATIVEMODE 	0x0200
201 
202 /* for backward compatibility */
203 #define OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
204 #define OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
205 #define OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)
206 
207 typedef struct old_mousehw {
208     int buttons;
209     int iftype;
210     int type;
211     int hwid;
212 } old_mousehw_t;
213 
214 typedef struct old_mousemode {
215     int protocol;
216     int rate;
217     int resolution;
218     int accelfactor;
219 } old_mousemode_t;
220 
221 /* packet formatting function */
222 typedef int packetfunc_t __P((struct psm_softc *, unsigned char *,
223 			      int *, int, mousestatus_t *));
224 
225 /* function prototypes */
226 static int psmprobe __P((device_t));
227 static int psmattach __P((device_t));
228 #ifdef PSM_HOOKAPM
229 static int psmresume __P((void *));
230 #endif
231 
232 static d_open_t psmopen;
233 static d_close_t psmclose;
234 static d_read_t psmread;
235 static d_ioctl_t psmioctl;
236 static d_poll_t psmpoll;
237 
238 static int enable_aux_dev __P((KBDC));
239 static int disable_aux_dev __P((KBDC));
240 static int get_mouse_status __P((KBDC, int *, int, int));
241 static int get_aux_id __P((KBDC));
242 static int set_mouse_sampling_rate __P((KBDC, int));
243 static int set_mouse_scaling __P((KBDC, int));
244 static int set_mouse_resolution __P((KBDC, int));
245 static int set_mouse_mode __P((KBDC));
246 static int get_mouse_buttons __P((KBDC));
247 static int is_a_mouse __P((int));
248 static void recover_from_error __P((KBDC));
249 static int restore_controller __P((KBDC, int));
250 static int reinitialize __P((int, mousemode_t *));
251 static int doopen __P((int, int));
252 static char *model_name(int);
253 static void psmintr(void*);
254 
255 /* vendor specific features */
256 typedef int probefunc_t __P((struct psm_softc *));
257 
258 static int mouse_id_proc1 __P((KBDC, int, int, int *));
259 static probefunc_t enable_groller;
260 static probefunc_t enable_gmouse;
261 static probefunc_t enable_aglide;
262 static probefunc_t enable_kmouse;
263 static probefunc_t enable_msintelli;
264 static probefunc_t enable_mmanplus;
265 static int tame_mouse __P((struct psm_softc *, mousestatus_t *, unsigned char *));
266 
267 static struct {
268     int                 model;
269     unsigned char	syncmask;
270     int 		packetsize;
271     probefunc_t 	*probefunc;
272 } vendortype[] = {
273     { MOUSE_MODEL_NET,			/* Genius NetMouse */
274       0xc8, MOUSE_INTELLI_PACKETSIZE, enable_gmouse, },
275     { MOUSE_MODEL_NETSCROLL,		/* Genius NetScroll */
276       0xc8, 6, enable_groller, },
277     { MOUSE_MODEL_GLIDEPOINT,		/* ALPS GlidePoint */
278       0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide, },
279     { MOUSE_MODEL_MOUSEMANPLUS,		/* Logitech MouseMan+ */
280       0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus, },
281     { MOUSE_MODEL_THINK,		/* Kensignton ThinkingMouse */
282       0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse, },
283     { MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
284       0xc8, MOUSE_INTELLI_PACKETSIZE, enable_msintelli, },
285     { MOUSE_MODEL_GENERIC,
286       0xc0, MOUSE_PS2_PACKETSIZE, NULL, },
287 };
288 
289 /* device driver declarateion */
290 static device_method_t psm_methods[] = {
291 	/* Device interface */
292 	DEVMETHOD(device_probe,		psmprobe),
293 	DEVMETHOD(device_attach,	psmattach),
294 
295 	{ 0, 0 }
296 };
297 
298 static driver_t psm_driver = {
299     "psm",
300     psm_methods,
301     DRIVER_TYPE_TTY,
302     sizeof(struct psm_softc),
303 };
304 
305 #define CDEV_MAJOR        21
306 
307 static struct  cdevsw psm_cdevsw = {
308 	psmopen,	psmclose,	psmread,	nowrite,	/* 21 */
309 	psmioctl,	nostop,		nullreset,	nodevtotty,
310 	psmpoll,	nommap,		NULL,		"psm",	NULL,	-1
311 };
312 
313 /* debug message level */
314 static int verbose = PSM_DEBUG;
315 
316 /* device I/O routines */
317 static int
318 enable_aux_dev(KBDC kbdc)
319 {
320     int res;
321 
322     res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
323     if (verbose >= 2)
324         log(LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res);
325 
326     return (res == PSM_ACK);
327 }
328 
329 static int
330 disable_aux_dev(KBDC kbdc)
331 {
332     int res;
333 
334     res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
335     if (verbose >= 2)
336         log(LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res);
337 
338     return (res == PSM_ACK);
339 }
340 
341 static int
342 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
343 {
344     int cmd;
345     int res;
346     int i;
347 
348     switch (flag) {
349     case 0:
350     default:
351 	cmd = PSMC_SEND_DEV_STATUS;
352 	break;
353     case 1:
354 	cmd = PSMC_SEND_DEV_DATA;
355 	break;
356     }
357     empty_aux_buffer(kbdc, 5);
358     res = send_aux_command(kbdc, cmd);
359     if (verbose >= 2)
360         log(LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
361 	    (flag == 1) ? "DATA" : "STATUS", res);
362     if (res != PSM_ACK)
363         return 0;
364 
365     for (i = 0; i < len; ++i) {
366         status[i] = read_aux_data(kbdc);
367 	if (status[i] < 0)
368 	    break;
369     }
370 
371     if (verbose) {
372         log(LOG_DEBUG, "psm: %s %02x %02x %02x\n",
373             (flag == 1) ? "data" : "status", status[0], status[1], status[2]);
374     }
375 
376     return i;
377 }
378 
379 static int
380 get_aux_id(KBDC kbdc)
381 {
382     int res;
383     int id;
384 
385     empty_aux_buffer(kbdc, 5);
386     res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
387     if (verbose >= 2)
388         log(LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res);
389     if (res != PSM_ACK)
390 	return (-1);
391 
392     /* 10ms delay */
393     DELAY(10000);
394 
395     id = read_aux_data(kbdc);
396     if (verbose >= 2)
397         log(LOG_DEBUG, "psm: device ID: %04x\n", id);
398 
399     return id;
400 }
401 
402 static int
403 set_mouse_sampling_rate(KBDC kbdc, int rate)
404 {
405     int res;
406 
407     res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
408     if (verbose >= 2)
409         log(LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res);
410 
411     return ((res == PSM_ACK) ? rate : -1);
412 }
413 
414 static int
415 set_mouse_scaling(KBDC kbdc, int scale)
416 {
417     int res;
418 
419     switch (scale) {
420     case 1:
421     default:
422 	scale = PSMC_SET_SCALING11;
423 	break;
424     case 2:
425 	scale = PSMC_SET_SCALING21;
426 	break;
427     }
428     res = send_aux_command(kbdc, scale);
429     if (verbose >= 2)
430         log(LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
431 	    (scale == PSMC_SET_SCALING21) ? "21" : "11", res);
432 
433     return (res == PSM_ACK);
434 }
435 
436 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
437 static int
438 set_mouse_resolution(KBDC kbdc, int val)
439 {
440     int res;
441 
442     res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
443     if (verbose >= 2)
444         log(LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res);
445 
446     return ((res == PSM_ACK) ? val : -1);
447 }
448 
449 /*
450  * NOTE: once `set_mouse_mode()' is called, the mouse device must be
451  * re-enabled by calling `enable_aux_dev()'
452  */
453 static int
454 set_mouse_mode(KBDC kbdc)
455 {
456     int res;
457 
458     res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
459     if (verbose >= 2)
460         log(LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res);
461 
462     return (res == PSM_ACK);
463 }
464 
465 static int
466 get_mouse_buttons(KBDC kbdc)
467 {
468     int c = 2;		/* assume two buttons by default */
469     int status[3];
470 
471     /*
472      * NOTE: a special sequence to obtain Logitech Mouse specific
473      * information: set resolution to 25 ppi, set scaling to 1:1, set
474      * scaling to 1:1, set scaling to 1:1. Then the second byte of the
475      * mouse status bytes is the number of available buttons.
476      * Some manufactures also support this sequence.
477      */
478     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
479         return c;
480     if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1)
481         && set_mouse_scaling(kbdc, 1)
482 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3)) {
483         if (status[1] != 0)
484             return status[1];
485     }
486     return c;
487 }
488 
489 /* misc subroutines */
490 /*
491  * Someday, I will get the complete list of valid pointing devices and
492  * their IDs... XXX
493  */
494 static int
495 is_a_mouse(int id)
496 {
497 #if 0
498     static int valid_ids[] = {
499         PSM_MOUSE_ID,		/* mouse */
500         PSM_BALLPOINT_ID,	/* ballpoint device */
501         PSM_INTELLI_ID,		/* Intellimouse */
502         -1			/* end of table */
503     };
504     int i;
505 
506     for (i = 0; valid_ids[i] >= 0; ++i)
507         if (valid_ids[i] == id)
508             return TRUE;
509     return FALSE;
510 #else
511     return TRUE;
512 #endif
513 }
514 
515 static char *
516 model_name(int model)
517 {
518     static struct {
519 	int model_code;
520 	char *model_name;
521     } models[] = {
522         { MOUSE_MODEL_NETSCROLL,	"NetScroll Mouse" },
523         { MOUSE_MODEL_NET,		"NetMouse" },
524         { MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
525         { MOUSE_MODEL_THINK,		"ThinkingMouse" },
526         { MOUSE_MODEL_INTELLI,		"IntelliMouse" },
527         { MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
528         { MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
529         { MOUSE_MODEL_UNKNOWN,		NULL },
530     };
531     int i;
532 
533     for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i) {
534 	if (models[i].model_code == model)
535 	    return models[i].model_name;
536     }
537     return "Unknown";
538 }
539 
540 static void
541 recover_from_error(KBDC kbdc)
542 {
543     /* discard anything left in the output buffer */
544     empty_both_buffers(kbdc, 10);
545 
546 #if 0
547     /*
548      * NOTE: KBDC_RESET_KBD may not restore the communication between the
549      * keyboard and the controller.
550      */
551     reset_kbd(kbdc);
552 #else
553     /*
554      * NOTE: somehow diagnostic and keyboard port test commands bring the
555      * keyboard back.
556      */
557     if (!test_controller(kbdc))
558         log(LOG_ERR, "psm: keyboard controller failed.\n");
559     /* if there isn't a keyboard in the system, the following error is OK */
560     if (test_kbd_port(kbdc) != 0) {
561 	if (verbose)
562 	    log(LOG_ERR, "psm: keyboard port failed.\n");
563     }
564 #endif
565 }
566 
567 static int
568 restore_controller(KBDC kbdc, int command_byte)
569 {
570     empty_both_buffers(kbdc, 10);
571 
572     if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
573 	log(LOG_ERR, "psm: failed to restore the keyboard controller "
574 		     "command byte.\n");
575 	return FALSE;
576     } else {
577 	return TRUE;
578     }
579 }
580 
581 /*
582  * Re-initialize the aux port and device. The aux port must be enabled
583  * and its interrupt must be disabled before calling this routine.
584  * The aux device will be disabled before returning.
585  * The keyboard controller must be locked via `kbdc_lock()' before
586  * calling this routine.
587  */
588 static int
589 reinitialize(int unit, mousemode_t *mode)
590 {
591     struct psm_softc *sc = PSM_SOFTC(unit);
592     KBDC kbdc = sc->kbdc;
593     int stat[3];
594     int i;
595 
596     switch((i = test_aux_port(kbdc))) {
597     case 1:	/* ignore this error */
598     case PSM_ACK:
599 	if (verbose)
600 	    log(LOG_DEBUG, "psm%d: strange result for test aux port (%d).\n",
601 	        unit, i);
602 	/* fall though */
603     case 0:	/* no error */
604     	break;
605     case -1: 	/* time out */
606     default: 	/* error */
607     	recover_from_error(kbdc);
608     	log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
609     	    unit, i);
610     	return FALSE;
611     }
612 
613     /*
614      * NOTE: some controllers appears to hang the `keyboard' when
615      * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
616      */
617     if (!reset_aux_dev(kbdc)) {
618         recover_from_error(kbdc);
619         log(LOG_ERR, "psm%d: failed to reset the aux device.\n", unit);
620         return FALSE;
621     }
622 
623     /*
624      * both the aux port and the aux device is functioning, see
625      * if the device can be enabled.
626      */
627     if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
628         log(LOG_ERR, "psm%d: failed to enable the aux device.\n", unit);
629         return FALSE;
630     }
631     empty_both_buffers(kbdc, 10);	/* remove stray data if any */
632 
633     /* FIXME: hardware ID, mouse buttons? */
634 
635     /* other parameters */
636     for (i = 0; vendortype[i].probefunc != NULL; ++i) {
637 	if ((*vendortype[i].probefunc)(sc)) {
638 	    if (verbose >= 2)
639 		log(LOG_ERR, "psm%d: found %s\n",
640 		    unit, model_name(vendortype[i].model));
641 	    break;
642 	}
643     }
644 
645     sc->hw.model = vendortype[i].model;
646     sc->mode.packetsize = vendortype[i].packetsize;
647 
648     /* set mouse parameters */
649     if (mode != (mousemode_t *)NULL) {
650 	if (mode->rate > 0)
651             mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
652 	if (mode->resolution >= 0)
653             mode->resolution = set_mouse_resolution(kbdc, mode->resolution);
654         set_mouse_scaling(kbdc, 1);
655         set_mouse_mode(kbdc);
656     }
657 
658     /* request a data packet and extract sync. bits */
659     if (get_mouse_status(kbdc, stat, 1, 3) < 3) {
660         log(LOG_DEBUG, "psm%d: failed to get data (reinitialize).\n", unit);
661         sc->mode.syncmask[0] = 0;
662     } else {
663         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
664 	/* the NetScroll Mouse will send three more bytes... Ignore them */
665 	empty_aux_buffer(kbdc, 5);
666     }
667 
668     /* just check the status of the mouse */
669     if (get_mouse_status(kbdc, stat, 0, 3) < 3)
670         log(LOG_DEBUG, "psm%d: failed to get status (reinitialize).\n", unit);
671 
672     return TRUE;
673 }
674 
675 static int
676 doopen(int unit, int command_byte)
677 {
678     struct psm_softc *sc = PSM_SOFTC(unit);
679     int stat[3];
680 
681     /* enable the mouse device */
682     if (!enable_aux_dev(sc->kbdc)) {
683 	/* MOUSE ERROR: failed to enable the mouse because:
684 	 * 1) the mouse is faulty,
685 	 * 2) the mouse has been removed(!?)
686 	 * In the latter case, the keyboard may have hung, and need
687 	 * recovery procedure...
688 	 */
689 	recover_from_error(sc->kbdc);
690 #if 0
691 	/* FIXME: we could reset the mouse here and try to enable
692 	 * it again. But it will take long time and it's not a good
693 	 * idea to disable the keyboard that long...
694 	 */
695 	if (!reinitialize(unit, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
696 	    recover_from_error(sc->kbdc);
697 #else
698         {
699 #endif
700             restore_controller(sc->kbdc, command_byte);
701 	    /* mark this device is no longer available */
702 	    sc->state &= ~PSM_VALID;
703 	    log(LOG_ERR, "psm%d: failed to enable the device (doopen).\n",
704 		unit);
705 	    return (EIO);
706 	}
707     }
708 
709     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
710         log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n", unit);
711 
712     /* enable the aux port and interrupt */
713     if (!set_controller_command_byte(sc->kbdc,
714 	    kbdc_get_device_mask(sc->kbdc),
715 	    (command_byte & KBD_KBD_CONTROL_BITS)
716 		| KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
717 	/* CONTROLLER ERROR */
718 	disable_aux_dev(sc->kbdc);
719         restore_controller(sc->kbdc, command_byte);
720 	log(LOG_ERR, "psm%d: failed to enable the aux interrupt (doopen).\n",
721 	    unit);
722 	return (EIO);
723     }
724 
725     return (0);
726 }
727 
728 /* psm driver entry points */
729 
730 #define endprobe(v)	{   if (bootverbose) 				\
731 				--verbose;   				\
732                             kbdc_set_device_mask(sc->kbdc, mask);	\
733 			    kbdc_lock(sc->kbdc, FALSE);			\
734  	                    free(sc, M_DEVBUF);                         \
735 			    return (v);	     				\
736 			}
737 
738 static int
739 psmprobe(device_t dev)
740 {
741     int unit = device_get_unit(dev);
742     struct psm_softc *sc = device_get_softc(dev);
743     int stat[3];
744     int command_byte;
745     int mask;
746     int i;
747 
748 #if 0
749     kbdc_debug(TRUE);
750 #endif
751     sc->addr = isa_get_port(dev);
752     sc->kbdc = kbdc_open(sc->addr);
753     sc->config = isa_get_flags(dev) & PSM_CONFIG_FLAGS;
754     sc->flags = 0;
755     if (bootverbose)
756         ++verbose;
757 
758     if (!kbdc_lock(sc->kbdc, TRUE)) {
759         printf("psm%d: unable to lock the controller.\n", unit);
760         if (bootverbose)
761             --verbose;
762 	return (ENXIO);
763     }
764 
765     /*
766      * NOTE: two bits in the command byte controls the operation of the
767      * aux port (mouse port): the aux port disable bit (bit 5) and the aux
768      * port interrupt (IRQ 12) enable bit (bit 2).
769      */
770 
771     /* discard anything left after the keyboard initialization */
772     empty_both_buffers(sc->kbdc, 10);
773 
774     /* save the current command byte; it will be used later */
775     mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
776     command_byte = get_controller_command_byte(sc->kbdc);
777     if (verbose)
778         printf("psm%d: current command byte:%04x\n", unit, command_byte);
779     if (command_byte == -1) {
780         /* CONTROLLER ERROR */
781         printf("psm%d: unable to get the current command byte value.\n",
782             unit);
783         endprobe(ENXIO);
784     }
785 
786     /*
787      * disable the keyboard port while probing the aux port, which must be
788      * enabled during this routine
789      */
790     if (!set_controller_command_byte(sc->kbdc,
791 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
792   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
793                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
794         /*
795 	 * this is CONTROLLER ERROR; I don't know how to recover
796          * from this error...
797 	 */
798         restore_controller(sc->kbdc, command_byte);
799         printf("psm%d: unable to set the command byte.\n", unit);
800         endprobe(ENXIO);
801     }
802 
803     /*
804      * NOTE: `test_aux_port()' is designed to return with zero if the aux
805      * port exists and is functioning. However, some controllers appears
806      * to respond with zero even when the aux port doesn't exist. (It may
807      * be that this is only the case when the controller DOES have the aux
808      * port but the port is not wired on the motherboard.) The keyboard
809      * controllers without the port, such as the original AT, are
810      * supporsed to return with an error code or simply time out. In any
811      * case, we have to continue probing the port even when the controller
812      * passes this test.
813      *
814      * XXX: some controllers erroneously return the error code 1 when
815      * it has the perfectly functional aux port. We have to ignore this
816      * error code. Even if the controller HAS error with the aux port,
817      * it will be detected later...
818      * XXX: another incompatible controller returns PSM_ACK (0xfa)...
819      */
820     switch ((i = test_aux_port(sc->kbdc))) {
821     case 1:	   /* ignore this error */
822     case PSM_ACK:
823         if (verbose)
824 	    printf("psm%d: strange result for test aux port (%d).\n",
825 	        unit, i);
826 	/* fall though */
827     case 0:        /* no error */
828         break;
829     case -1:        /* time out */
830     default:        /* error */
831         recover_from_error(sc->kbdc);
832         restore_controller(sc->kbdc, command_byte);
833         if (verbose)
834             printf("psm%d: the aux port is not functioning (%d).\n",
835                 unit, i);
836         endprobe(ENXIO);
837     }
838 
839     /*
840      * NOTE: some controllers appears to hang the `keyboard' when the aux
841      * port doesn't exist and `PSMC_RESET_DEV' is issued.
842      */
843     if (!reset_aux_dev(sc->kbdc)) {
844         recover_from_error(sc->kbdc);
845         restore_controller(sc->kbdc, command_byte);
846         if (verbose)
847             printf("psm%d: failed to reset the aux device.\n", unit);
848         endprobe(ENXIO);
849     }
850     /*
851      * both the aux port and the aux device is functioning, see if the
852      * device can be enabled. NOTE: when enabled, the device will start
853      * sending data; we shall immediately disable the device once we know
854      * the device can be enabled.
855      */
856     if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
857 	/* MOUSE ERROR */
858         restore_controller(sc->kbdc, command_byte);
859         if (verbose)
860             printf("psm%d: failed to enable the aux device.\n", unit);
861         endprobe(ENXIO);
862     }
863 
864     /* save the default values after reset */
865     if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
866 	sc->dflt_mode.rate = sc->mode.rate = stat[2];
867 	sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
868     } else {
869 	sc->dflt_mode.rate = sc->mode.rate = -1;
870 	sc->dflt_mode.resolution = sc->mode.resolution = -1;
871     }
872 
873     /* hardware information */
874     sc->hw.iftype = MOUSE_IF_PS2;
875 
876     /* verify the device is a mouse */
877     sc->hw.hwid = get_aux_id(sc->kbdc);
878     if (!is_a_mouse(sc->hw.hwid)) {
879         restore_controller(sc->kbdc, command_byte);
880         if (verbose)
881             printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid);
882         endprobe(ENXIO);
883     }
884     switch (sc->hw.hwid) {
885     case PSM_BALLPOINT_ID:
886         sc->hw.type = MOUSE_TRACKBALL;
887         break;
888     case PSM_MOUSE_ID:
889     case PSM_INTELLI_ID:
890         sc->hw.type = MOUSE_MOUSE;
891         break;
892     default:
893         sc->hw.type = MOUSE_UNKNOWN;
894         break;
895     }
896 
897     /* # of buttons */
898     sc->hw.buttons = get_mouse_buttons(sc->kbdc);
899 
900     /* other parameters */
901     for (i = 0; vendortype[i].probefunc != NULL; ++i) {
902 	if ((*vendortype[i].probefunc)(sc)) {
903 	    if (verbose >= 2)
904 		printf("psm%d: found %s\n",
905 		    unit, model_name(vendortype[i].model));
906 	    break;
907 	}
908     }
909 
910     sc->hw.model = vendortype[i].model;
911 
912     sc->dflt_mode.level = PSM_LEVEL_BASE;
913     sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
914     sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
915     if (sc->config & PSM_CONFIG_NOCHECKSYNC)
916         sc->dflt_mode.syncmask[0] = 0;
917     else
918         sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
919     sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
920     sc->mode = sc->dflt_mode;
921     sc->mode.packetsize = vendortype[i].packetsize;
922 
923     /* set mouse parameters */
924     i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
925     if (verbose >= 2)
926 	printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
927     if (sc->config & PSM_CONFIG_RESOLUTION) {
928         sc->mode.resolution
929 	    = set_mouse_resolution(sc->kbdc,
930 	        (sc->config & PSM_CONFIG_RESOLUTION) - 1);
931     }
932 
933     /* request a data packet and extract sync. bits */
934     if (get_mouse_status(sc->kbdc, stat, 1, 3) < 3) {
935         printf("psm%d: failed to get data.\n", unit);
936         sc->mode.syncmask[0] = 0;
937     } else {
938         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
939 	/* the NetScroll Mouse will send three more bytes... Ignore them */
940 	empty_aux_buffer(sc->kbdc, 5);
941     }
942 
943     /* just check the status of the mouse */
944     /*
945      * NOTE: XXX there are some arcane controller/mouse combinations out
946      * there, which hung the controller unless there is data transmission
947      * after ACK from the mouse.
948      */
949     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) {
950         printf("psm%d: failed to get status.\n", unit);
951     } else {
952 	/*
953 	 * When in its native mode, some mice operate with different
954 	 * default parameters than in the PS/2 compatible mode.
955 	 */
956         sc->dflt_mode.rate = sc->mode.rate = stat[2];
957         sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
958      }
959 
960     /* disable the aux port for now... */
961     if (!set_controller_command_byte(sc->kbdc,
962 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
963             (command_byte & KBD_KBD_CONTROL_BITS)
964                 | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
965         /*
966 	 * this is CONTROLLER ERROR; I don't know the proper way to
967          * recover from this error...
968 	 */
969         restore_controller(sc->kbdc, command_byte);
970         printf("psm%d: unable to set the command byte.\n", unit);
971         endprobe(ENXIO);
972     }
973 
974     /* done */
975     kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
976     kbdc_lock(sc->kbdc, FALSE);
977     return (0);
978 }
979 
980 static int
981 psmattach(device_t dev)
982 {
983     int unit = device_get_unit(dev);
984     struct psm_softc *sc = device_get_softc(dev);
985     void *ih;
986     struct resource *res;
987     int zero = 0;
988 
989     if (sc == NULL)    /* shouldn't happen */
990 	return (ENXIO);
991 
992     /* Setup initial state */
993     sc->state = PSM_VALID;
994 
995     /* Done */
996 #ifdef    DEVFS
997     sc->devfs_token =
998         devfs_add_devswf(&psm_cdevsw, PSM_MKMINOR(unit, FALSE),
999         DV_CHR, 0, 0, 0666, "psm%d", unit);
1000     sc->b_devfs_token =
1001         devfs_add_devswf(&psm_cdevsw, PSM_MKMINOR(unit, TRUE),
1002         DV_CHR, 0, 0, 0666, "bpsm%d", unit);
1003 #endif /* DEVFS */
1004 
1005 #ifdef PSM_HOOKAPM
1006     sc->resumehook.ah_name = "PS/2 mouse";
1007     sc->resumehook.ah_fun = psmresume;
1008     sc->resumehook.ah_arg = (void *)unit;
1009     sc->resumehook.ah_order = APM_MID_ORDER;
1010     apm_hook_establish(APM_HOOK_RESUME , &sc->resumehook);
1011     if (verbose)
1012         printf("psm%d: APM hooks installed.\n", unit);
1013 #endif /* PSM_HOOKAPM */
1014 
1015     if (!verbose) {
1016         printf("psm%d: model %s, device ID %d\n",
1017 	    unit, model_name(sc->hw.model), sc->hw.hwid);
1018     } else {
1019         printf("psm%d: model %s, device ID %d, %d buttons\n",
1020 	    unit, model_name(sc->hw.model), sc->hw.hwid, sc->hw.buttons);
1021 	printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1022 	    unit, sc->config, sc->flags, sc->mode.packetsize);
1023 	printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1024 	    unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1025     }
1026 
1027     if (bootverbose)
1028         --verbose;
1029 
1030     res = bus_alloc_resource(dev, SYS_RES_IRQ, &zero, 0ul, ~0ul, 1,
1031 			     RF_SHAREABLE | RF_ACTIVE);
1032     BUS_SETUP_INTR(device_get_parent(dev), dev, res, psmintr, sc,
1033 		   &ih);
1034 
1035     return (0);
1036 }
1037 
1038 static int
1039 psmopen(dev_t dev, int flag, int fmt, struct proc *p)
1040 {
1041     int unit = PSM_UNIT(dev);
1042     struct psm_softc *sc;
1043     int command_byte;
1044     int err;
1045     int s;
1046 
1047     /* Validate unit number */
1048     if (unit >= NPSM)
1049         return (ENXIO);
1050 
1051     /* Get device data */
1052     sc = PSM_SOFTC(unit);
1053     if ((sc == NULL) || (sc->state & PSM_VALID) == 0)
1054 	/* the device is no longer valid/functioning */
1055         return (ENXIO);
1056 
1057     /* Disallow multiple opens */
1058     if (sc->state & PSM_OPEN)
1059         return (EBUSY);
1060 
1061     device_busy(devclass_get_device(psm_devclass, unit));
1062 
1063     /* Initialize state */
1064     sc->rsel.si_flags = 0;
1065     sc->rsel.si_pid = 0;
1066     sc->mode.level = sc->dflt_mode.level;
1067     sc->mode.protocol = sc->dflt_mode.protocol;
1068 
1069     /* flush the event queue */
1070     sc->queue.count = 0;
1071     sc->queue.head = 0;
1072     sc->queue.tail = 0;
1073     sc->status.flags = 0;
1074     sc->status.button = 0;
1075     sc->status.obutton = 0;
1076     sc->status.dx = 0;
1077     sc->status.dy = 0;
1078     sc->status.dz = 0;
1079     sc->button = 0;
1080 
1081     /* empty input buffer */
1082     bzero(sc->ipacket, sizeof(sc->ipacket));
1083     sc->inputbytes = 0;
1084 
1085     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1086     if (!kbdc_lock(sc->kbdc, TRUE))
1087 	return (EIO);
1088 
1089     /* save the current controller command byte */
1090     s = spltty();
1091     command_byte = get_controller_command_byte(sc->kbdc);
1092 
1093     /* enable the aux port and temporalily disable the keyboard */
1094     if ((command_byte == -1)
1095         || !set_controller_command_byte(sc->kbdc,
1096 	    kbdc_get_device_mask(sc->kbdc),
1097   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1098 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1099         /* CONTROLLER ERROR; do you know how to get out of this? */
1100         kbdc_lock(sc->kbdc, FALSE);
1101 	splx(s);
1102 	log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n",
1103 	    unit);
1104 	return (EIO);
1105     }
1106     /*
1107      * Now that the keyboard controller is told not to generate
1108      * the keyboard and mouse interrupts, call `splx()' to allow
1109      * the other tty interrupts. The clock interrupt may also occur,
1110      * but timeout routines will be blocked by the poll flag set
1111      * via `kbdc_lock()'
1112      */
1113     splx(s);
1114 
1115     /* enable the mouse device */
1116     err = doopen(unit, command_byte);
1117 
1118     /* done */
1119     if (err == 0)
1120         sc->state |= PSM_OPEN;
1121     kbdc_lock(sc->kbdc, FALSE);
1122     return (err);
1123 }
1124 
1125 static int
1126 psmclose(dev_t dev, int flag, int fmt, struct proc *p)
1127 {
1128     int unit = PSM_UNIT(dev);
1129     struct psm_softc *sc = PSM_SOFTC(unit);
1130     int stat[3];
1131     int command_byte;
1132     int s;
1133 
1134     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1135     if (!kbdc_lock(sc->kbdc, TRUE))
1136 	return (EIO);
1137 
1138     /* save the current controller command byte */
1139     s = spltty();
1140     command_byte = get_controller_command_byte(sc->kbdc);
1141     if (command_byte == -1) {
1142         kbdc_lock(sc->kbdc, FALSE);
1143 	splx(s);
1144 	return (EIO);
1145     }
1146 
1147     /* disable the aux interrupt and temporalily disable the keyboard */
1148     if (!set_controller_command_byte(sc->kbdc,
1149 	    kbdc_get_device_mask(sc->kbdc),
1150   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1151 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1152 	log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n",
1153 	    PSM_UNIT(dev));
1154 	/* CONTROLLER ERROR;
1155 	 * NOTE: we shall force our way through. Because the only
1156 	 * ill effect we shall see is that we may not be able
1157 	 * to read ACK from the mouse, and it doesn't matter much
1158 	 * so long as the mouse will accept the DISABLE command.
1159 	 */
1160     }
1161     splx(s);
1162 
1163     /* remove anything left in the output buffer */
1164     empty_aux_buffer(sc->kbdc, 10);
1165 
1166     /* disable the aux device, port and interrupt */
1167     if (sc->state & PSM_VALID) {
1168         if (!disable_aux_dev(sc->kbdc)) {
1169 	    /* MOUSE ERROR;
1170 	     * NOTE: we don't return error and continue, pretending
1171 	     * we have successfully disabled the device. It's OK because
1172 	     * the interrupt routine will discard any data from the mouse
1173 	     * hereafter.
1174 	     */
1175 	    log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n",
1176 	        PSM_UNIT(dev));
1177         }
1178 
1179         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1180             log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n",
1181 	        PSM_UNIT(dev));
1182     }
1183 
1184     if (!set_controller_command_byte(sc->kbdc,
1185 	    kbdc_get_device_mask(sc->kbdc),
1186 	    (command_byte & KBD_KBD_CONTROL_BITS)
1187 	        | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1188 	/* CONTROLLER ERROR;
1189 	 * we shall ignore this error; see the above comment.
1190 	 */
1191 	log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n",
1192 	    PSM_UNIT(dev));
1193     }
1194 
1195     /* remove anything left in the output buffer */
1196     empty_aux_buffer(sc->kbdc, 10);
1197 
1198     /* close is almost always successful */
1199     sc->state &= ~PSM_OPEN;
1200     kbdc_lock(sc->kbdc, FALSE);
1201     device_unbusy(devclass_get_device(psm_devclass, unit));
1202     return (0);
1203 }
1204 
1205 static int
1206 tame_mouse(struct psm_softc *sc, mousestatus_t *status, unsigned char *buf)
1207 {
1208     static unsigned char butmapps2[8] = {
1209         0,
1210         MOUSE_PS2_BUTTON1DOWN,
1211         MOUSE_PS2_BUTTON2DOWN,
1212         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1213         MOUSE_PS2_BUTTON3DOWN,
1214         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1215         MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1216         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1217     };
1218     static unsigned char butmapmsc[8] = {
1219         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1220         MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1221         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1222         MOUSE_MSC_BUTTON3UP,
1223         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1224         MOUSE_MSC_BUTTON2UP,
1225         MOUSE_MSC_BUTTON1UP,
1226         0,
1227     };
1228     int mapped;
1229     int i;
1230 
1231     if (sc->mode.level == PSM_LEVEL_BASE) {
1232         mapped = status->button & ~MOUSE_BUTTON4DOWN;
1233         if (status->button & MOUSE_BUTTON4DOWN)
1234 	    mapped |= MOUSE_BUTTON1DOWN;
1235         status->button = mapped;
1236         buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1237         i = max(min(status->dx, 255), -256);
1238 	if (i < 0)
1239 	    buf[0] |= MOUSE_PS2_XNEG;
1240         buf[1] = i;
1241         i = max(min(status->dy, 255), -256);
1242 	if (i < 0)
1243 	    buf[0] |= MOUSE_PS2_YNEG;
1244         buf[2] = i;
1245 	return MOUSE_PS2_PACKETSIZE;
1246     } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1247         buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS];
1248         i = max(min(status->dx, 255), -256);
1249         buf[1] = i >> 1;
1250         buf[3] = i - buf[1];
1251         i = max(min(status->dy, 255), -256);
1252         buf[2] = i >> 1;
1253         buf[4] = i - buf[2];
1254         i = max(min(status->dz, 127), -128);
1255         buf[5] = (i >> 1) & 0x7f;
1256         buf[6] = (i - (i >> 1)) & 0x7f;
1257         buf[7] = (~status->button >> 3) & 0x7f;
1258 	return MOUSE_SYS_PACKETSIZE;
1259     }
1260     return sc->inputbytes;;
1261 }
1262 
1263 static int
1264 psmread(dev_t dev, struct uio *uio, int flag)
1265 {
1266     register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1267     unsigned char buf[PSM_SMALLBUFSIZE];
1268     int error = 0;
1269     int s;
1270     int l;
1271 
1272     if ((sc->state & PSM_VALID) == 0)
1273 	return EIO;
1274 
1275     /* block until mouse activity occured */
1276     s = spltty();
1277     while (sc->queue.count <= 0) {
1278         if (PSM_NBLOCKIO(dev)) {
1279             splx(s);
1280             return EWOULDBLOCK;
1281         }
1282         sc->state |= PSM_ASLP;
1283         error = tsleep((caddr_t) sc, PZERO | PCATCH, "psmrea", 0);
1284         sc->state &= ~PSM_ASLP;
1285         if (error) {
1286             splx(s);
1287             return error;
1288         } else if ((sc->state & PSM_VALID) == 0) {
1289             /* the device disappeared! */
1290             splx(s);
1291             return EIO;
1292 	}
1293     }
1294     splx(s);
1295 
1296     /* copy data to the user land */
1297     while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1298         s = spltty();
1299 	l = min(sc->queue.count, uio->uio_resid);
1300 	if (l > sizeof(buf))
1301 	    l = sizeof(buf);
1302 	if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1303 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1304 		sizeof(sc->queue.buf) - sc->queue.head);
1305 	    bcopy(&sc->queue.buf[0],
1306 		&buf[sizeof(sc->queue.buf) - sc->queue.head],
1307 		l - (sizeof(sc->queue.buf) - sc->queue.head));
1308 	} else {
1309 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1310 	}
1311 	sc->queue.count -= l;
1312 	sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1313         splx(s);
1314         error = uiomove(buf, l, uio);
1315         if (error)
1316 	    break;
1317     }
1318 
1319     return error;
1320 }
1321 
1322 static int
1323 block_mouse_data(struct psm_softc *sc, int *c)
1324 {
1325     int s;
1326 
1327     if (!kbdc_lock(sc->kbdc, TRUE))
1328 	return EIO;
1329 
1330     s = spltty();
1331     *c = get_controller_command_byte(sc->kbdc);
1332     if ((*c == -1)
1333 	|| !set_controller_command_byte(sc->kbdc,
1334 	    kbdc_get_device_mask(sc->kbdc),
1335             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1336                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1337         /* this is CONTROLLER ERROR */
1338 	splx(s);
1339         kbdc_lock(sc->kbdc, FALSE);
1340 	return EIO;
1341     }
1342 
1343     /*
1344      * The device may be in the middle of status data transmission.
1345      * The transmission will be interrupted, thus, incomplete status
1346      * data must be discarded. Although the aux interrupt is disabled
1347      * at the keyboard controller level, at most one aux interrupt
1348      * may have already been pending and a data byte is in the
1349      * output buffer; throw it away. Note that the second argument
1350      * to `empty_aux_buffer()' is zero, so that the call will just
1351      * flush the internal queue.
1352      * `psmintr()' will be invoked after `splx()' if an interrupt is
1353      * pending; it will see no data and returns immediately.
1354      */
1355     empty_aux_buffer(sc->kbdc, 0);	/* flush the queue */
1356     read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
1357     sc->inputbytes = 0;
1358     splx(s);
1359 
1360     return 0;
1361 }
1362 
1363 static int
1364 unblock_mouse_data(struct psm_softc *sc, int c)
1365 {
1366     int error = 0;
1367 
1368     /*
1369      * We may have seen a part of status data during `set_mouse_XXX()'.
1370      * they have been queued; flush it.
1371      */
1372     empty_aux_buffer(sc->kbdc, 0);
1373 
1374     /* restore ports and interrupt */
1375     if (!set_controller_command_byte(sc->kbdc,
1376             kbdc_get_device_mask(sc->kbdc),
1377 	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1378         /* CONTROLLER ERROR; this is serious, we may have
1379          * been left with the inaccessible keyboard and
1380          * the disabled mouse interrupt.
1381          */
1382         error = EIO;
1383     }
1384 
1385     kbdc_lock(sc->kbdc, FALSE);
1386     return error;
1387 }
1388 
1389 static int
1390 psmioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1391 {
1392     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1393     mousemode_t mode;
1394     mousestatus_t status;
1395 #if (defined(MOUSE_GETVARS))
1396     mousevar_t *var;
1397 #endif
1398     mousedata_t *data;
1399     int stat[3];
1400     int command_byte;
1401     int error = 0;
1402     int s;
1403 
1404     /* Perform IOCTL command */
1405     switch (cmd) {
1406 
1407     case OLD_MOUSE_GETHWINFO:
1408 	s = spltty();
1409         ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1410         ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1411         ((old_mousehw_t *)addr)->type = sc->hw.type;
1412         ((old_mousehw_t *)addr)->hwid = sc->hw.hwid;
1413 	splx(s);
1414         break;
1415 
1416     case MOUSE_GETHWINFO:
1417 	s = spltty();
1418         *(mousehw_t *)addr = sc->hw;
1419 	if (sc->mode.level == PSM_LEVEL_BASE)
1420 	    ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1421 	splx(s);
1422         break;
1423 
1424     case OLD_MOUSE_GETMODE:
1425 	s = spltty();
1426 	switch (sc->mode.level) {
1427 	case PSM_LEVEL_BASE:
1428 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1429 	    break;
1430 	case PSM_LEVEL_STANDARD:
1431 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1432 	    break;
1433 	case PSM_LEVEL_NATIVE:
1434 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1435 	    break;
1436 	}
1437         ((old_mousemode_t *)addr)->rate = sc->mode.rate;
1438         ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1439         ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1440 	splx(s);
1441         break;
1442 
1443     case MOUSE_GETMODE:
1444 	s = spltty();
1445         *(mousemode_t *)addr = sc->mode;
1446         ((mousemode_t *)addr)->resolution =
1447 	    MOUSE_RES_LOW - sc->mode.resolution;
1448 	switch (sc->mode.level) {
1449 	case PSM_LEVEL_BASE:
1450 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1451 	    ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE;
1452 	    break;
1453 	case PSM_LEVEL_STANDARD:
1454 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1455 	    ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE;
1456 	    ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1457 	    ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
1458 	    break;
1459 	case PSM_LEVEL_NATIVE:
1460 	    /* FIXME: this isn't quite correct... XXX */
1461 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1462 	    break;
1463 	}
1464 	splx(s);
1465         break;
1466 
1467     case OLD_MOUSE_SETMODE:
1468     case MOUSE_SETMODE:
1469 	if (cmd == OLD_MOUSE_SETMODE) {
1470 	    mode.rate = ((old_mousemode_t *)addr)->rate;
1471 	    /*
1472 	     * resolution  old I/F   new I/F
1473 	     * default        0         0
1474 	     * low            1        -2
1475 	     * medium low     2        -3
1476 	     * medium high    3        -4
1477 	     * high           4        -5
1478 	     */
1479 	    if (((old_mousemode_t *)addr)->resolution > 0)
1480 	        mode.resolution = -((old_mousemode_t *)addr)->resolution - 1;
1481 	    mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor;
1482 	    mode.level = -1;
1483 	} else {
1484 	    mode = *(mousemode_t *)addr;
1485 	}
1486 
1487 	/* adjust and validate parameters. */
1488 	if (mode.rate > UCHAR_MAX)
1489 	    return EINVAL;
1490         if (mode.rate == 0)
1491             mode.rate = sc->dflt_mode.rate;
1492 	else if (mode.rate == -1)
1493 	    /* don't change the current setting */
1494 	    ;
1495 	else if (mode.rate < 0)
1496 	    return EINVAL;
1497 	if (mode.resolution >= UCHAR_MAX)
1498 	    return EINVAL;
1499 	if (mode.resolution >= 200)
1500 	    mode.resolution = MOUSE_RES_HIGH;
1501 	else if (mode.resolution >= 100)
1502 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1503 	else if (mode.resolution >= 50)
1504 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1505 	else if (mode.resolution > 0)
1506 	    mode.resolution = MOUSE_RES_LOW;
1507         if (mode.resolution == MOUSE_RES_DEFAULT)
1508             mode.resolution = sc->dflt_mode.resolution;
1509         else if (mode.resolution == -1)
1510 	    /* don't change the current setting */
1511 	    ;
1512         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1513             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1514 	if (mode.level == -1)
1515 	    /* don't change the current setting */
1516 	    mode.level = sc->mode.level;
1517 	else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX))
1518 	    return EINVAL;
1519         if (mode.accelfactor == -1)
1520 	    /* don't change the current setting */
1521 	    mode.accelfactor = sc->mode.accelfactor;
1522         else if (mode.accelfactor < 0)
1523 	    return EINVAL;
1524 
1525 	/* don't allow anybody to poll the keyboard controller */
1526 	error = block_mouse_data(sc, &command_byte);
1527 	if (error)
1528             return error;
1529 
1530         /* set mouse parameters */
1531 	if (mode.rate > 0)
1532 	    mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1533 	if (mode.resolution >= 0)
1534 	    mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1535 	set_mouse_scaling(sc->kbdc, 1);
1536 	get_mouse_status(sc->kbdc, stat, 0, 3);
1537 
1538         s = spltty();
1539     	sc->mode.rate = mode.rate;
1540     	sc->mode.resolution = mode.resolution;
1541     	sc->mode.accelfactor = mode.accelfactor;
1542     	sc->mode.level = mode.level;
1543         splx(s);
1544 
1545 	unblock_mouse_data(sc, command_byte);
1546         break;
1547 
1548     case MOUSE_GETLEVEL:
1549 	*(int *)addr = sc->mode.level;
1550         break;
1551 
1552     case MOUSE_SETLEVEL:
1553 	if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX))
1554 	    return EINVAL;
1555 	sc->mode.level = *(int *)addr;
1556         break;
1557 
1558     case MOUSE_GETSTATUS:
1559         s = spltty();
1560 	status = sc->status;
1561 	sc->status.flags = 0;
1562 	sc->status.obutton = sc->status.button;
1563 	sc->status.button = 0;
1564 	sc->status.dx = 0;
1565 	sc->status.dy = 0;
1566 	sc->status.dz = 0;
1567         splx(s);
1568         *(mousestatus_t *)addr = status;
1569         break;
1570 
1571 #if (defined(MOUSE_GETVARS))
1572     case MOUSE_GETVARS:
1573 	var = (mousevar_t *)addr;
1574 	bzero(var, sizeof(*var));
1575 	s = spltty();
1576         var->var[0] = MOUSE_VARS_PS2_SIG;
1577         var->var[1] = sc->config;
1578         var->var[2] = sc->flags;
1579 	splx(s);
1580         break;
1581 
1582     case MOUSE_SETVARS:
1583 	return ENODEV;
1584 #endif /* MOUSE_GETVARS */
1585 
1586     case MOUSE_READSTATE:
1587     case MOUSE_READDATA:
1588 	data = (mousedata_t *)addr;
1589 	if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
1590 	    return EINVAL;
1591 
1592 	error = block_mouse_data(sc, &command_byte);
1593 	if (error)
1594             return error;
1595         if ((data->len = get_mouse_status(sc->kbdc, data->buf,
1596 		(cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
1597             error = EIO;
1598 	unblock_mouse_data(sc, command_byte);
1599 	break;
1600 
1601 #if (defined(MOUSE_SETRESOLUTION))
1602     case MOUSE_SETRESOLUTION:
1603 	mode.resolution = *(int *)addr;
1604 	if (mode.resolution >= UCHAR_MAX)
1605 	    return EINVAL;
1606 	else if (mode.resolution >= 200)
1607 	    mode.resolution = MOUSE_RES_HIGH;
1608 	else if (mode.resolution >= 100)
1609 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1610 	else if (mode.resolution >= 50)
1611 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1612 	else if (mode.resolution > 0)
1613 	    mode.resolution = MOUSE_RES_LOW;
1614         if (mode.resolution == MOUSE_RES_DEFAULT)
1615             mode.resolution = sc->dflt_mode.resolution;
1616         else if (mode.resolution == -1)
1617 	    mode.resolution = sc->mode.resolution;
1618         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1619             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1620 
1621 	error = block_mouse_data(sc, &command_byte);
1622 	if (error)
1623             return error;
1624         sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1625 	if (sc->mode.resolution != mode.resolution)
1626 	    error = EIO;
1627 	unblock_mouse_data(sc, command_byte);
1628         break;
1629 #endif /* MOUSE_SETRESOLUTION */
1630 
1631 #if (defined(MOUSE_SETRATE))
1632     case MOUSE_SETRATE:
1633 	mode.rate = *(int *)addr;
1634 	if (mode.rate > UCHAR_MAX)
1635 	    return EINVAL;
1636         if (mode.rate == 0)
1637             mode.rate = sc->dflt_mode.rate;
1638 	else if (mode.rate < 0)
1639 	    mode.rate = sc->mode.rate;
1640 
1641 	error = block_mouse_data(sc, &command_byte);
1642 	if (error)
1643             return error;
1644         sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1645 	if (sc->mode.rate != mode.rate)
1646 	    error = EIO;
1647 	unblock_mouse_data(sc, command_byte);
1648         break;
1649 #endif /* MOUSE_SETRATE */
1650 
1651 #if (defined(MOUSE_SETSCALING))
1652     case MOUSE_SETSCALING:
1653 	if ((*(int *)addr <= 0) || (*(int *)addr > 2))
1654 	    return EINVAL;
1655 
1656 	error = block_mouse_data(sc, &command_byte);
1657 	if (error)
1658             return error;
1659         if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
1660 	    error = EIO;
1661 	unblock_mouse_data(sc, command_byte);
1662         break;
1663 #endif /* MOUSE_SETSCALING */
1664 
1665 #if (defined(MOUSE_GETHWID))
1666     case MOUSE_GETHWID:
1667 	error = block_mouse_data(sc, &command_byte);
1668 	if (error)
1669             return error;
1670         sc->hw.hwid = get_aux_id(sc->kbdc);
1671 	*(int *)addr = sc->hw.hwid;
1672 	unblock_mouse_data(sc, command_byte);
1673         break;
1674 #endif /* MOUSE_GETHWID */
1675 
1676     default:
1677 	return ENOTTY;
1678     }
1679 
1680     return error;
1681 }
1682 
1683 static void
1684 psmintr(void *arg)
1685 {
1686     /*
1687      * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
1688      * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
1689      */
1690     static int butmap[8] = {
1691         0,
1692 	MOUSE_BUTTON1DOWN,
1693 	MOUSE_BUTTON3DOWN,
1694 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1695 	MOUSE_BUTTON2DOWN,
1696 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1697 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1698         MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1699     };
1700     register struct psm_softc *sc = arg;
1701     mousestatus_t ms;
1702     int x, y, z;
1703     int c;
1704     int l;
1705 
1706     /* read until there is nothing to read */
1707     while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
1708 
1709         /* discard the byte if the device is not open */
1710         if ((sc->state & PSM_OPEN) == 0)
1711             continue;
1712 
1713         /*
1714 	 * Check sync bits. We check for overflow bits and the bit 3
1715 	 * for most mice. True, the code doesn't work if overflow
1716 	 * condition occurs. But we expect it rarely happens...
1717 	 */
1718 	if ((sc->inputbytes == 0)
1719 		&& ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1])) {
1720             log(LOG_DEBUG, "psmintr: out of sync (%04x != %04x).\n",
1721 		c & sc->mode.syncmask[0], sc->mode.syncmask[1]);
1722             continue;
1723 	}
1724 
1725         sc->ipacket[sc->inputbytes++] = c;
1726         if (sc->inputbytes < sc->mode.packetsize)
1727 	    continue;
1728 
1729 #if 0
1730         log(LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
1731 	    sc->ipacket[0], sc->ipacket[1], sc->ipacket[2],
1732 	    sc->ipacket[3], sc->ipacket[4], sc->ipacket[5]);
1733 #endif
1734 
1735 	c = sc->ipacket[0];
1736 
1737         /*
1738 	 * A kludge for Kensington device!
1739 	 * The MSB of the horizontal count appears to be stored in
1740 	 * a strange place. This kludge doesn't affect other mice
1741 	 * because the bit is the overflow bit which is, in most cases,
1742 	 * expected to be zero when we reach here. XXX
1743 	 */
1744         sc->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
1745 
1746         /* ignore the overflow bits... */
1747         x = (c & MOUSE_PS2_XNEG) ?  sc->ipacket[1] - 256 : sc->ipacket[1];
1748         y = (c & MOUSE_PS2_YNEG) ?  sc->ipacket[2] - 256 : sc->ipacket[2];
1749 	z = 0;
1750         ms.obutton = sc->button;		  /* previous button state */
1751         ms.button = butmap[c & MOUSE_PS2_BUTTONS];
1752 
1753 	switch (sc->hw.model) {
1754 
1755 	case MOUSE_MODEL_INTELLI:
1756 	case MOUSE_MODEL_NET:
1757 	    /* wheel data is in the fourth byte */
1758 	    z = (char)sc->ipacket[3];
1759 	    break;
1760 
1761 	case MOUSE_MODEL_MOUSEMANPLUS:
1762 	    if ((c & ~MOUSE_PS2_BUTTONS) == 0xc8) {
1763 		/* the extended data packet encodes button and wheel events */
1764 		x = y = 0;
1765 		z = (sc->ipacket[1] & MOUSE_PS2PLUS_ZNEG)
1766 		    ? (sc->ipacket[2] & 0x0f) - 16 : (sc->ipacket[2] & 0x0f);
1767 		ms.button |= (sc->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
1768 		    ? MOUSE_BUTTON4DOWN : 0;
1769 	    } else {
1770 		/* preserve button states */
1771 		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
1772 	    }
1773 	    break;
1774 
1775 	case MOUSE_MODEL_GLIDEPOINT:
1776 	    /* `tapping' action */
1777 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
1778 	    break;
1779 
1780 	case MOUSE_MODEL_NETSCROLL:
1781 	    /* three addtional bytes encode button and wheel events */
1782 	    ms.button |= (sc->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
1783 		? MOUSE_BUTTON4DOWN : 0;
1784 	    z = (sc->ipacket[3] & MOUSE_PS2_XNEG)
1785 		? sc->ipacket[4] - 256 : sc->ipacket[4];
1786 	    break;
1787 
1788 	case MOUSE_MODEL_THINK:
1789 	    /* the fourth button state in the first byte */
1790 	    ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
1791 	    break;
1792 
1793 	case MOUSE_MODEL_GENERIC:
1794 	default:
1795 	    break;
1796 	}
1797 
1798         /* scale values */
1799         if (sc->mode.accelfactor >= 1) {
1800             if (x != 0) {
1801                 x = x * x / sc->mode.accelfactor;
1802                 if (x == 0)
1803                     x = 1;
1804                 if (c & MOUSE_PS2_XNEG)
1805                     x = -x;
1806             }
1807             if (y != 0) {
1808                 y = y * y / sc->mode.accelfactor;
1809                 if (y == 0)
1810                     y = 1;
1811                 if (c & MOUSE_PS2_YNEG)
1812                     y = -y;
1813             }
1814         }
1815 
1816         ms.dx = x;
1817         ms.dy = y;
1818         ms.dz = z;
1819         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0)
1820 	    | (ms.obutton ^ ms.button);
1821 
1822 	if (sc->mode.level < PSM_LEVEL_NATIVE)
1823 	    sc->inputbytes = tame_mouse(sc, &ms, sc->ipacket);
1824 
1825         sc->status.flags |= ms.flags;
1826         sc->status.dx += ms.dx;
1827         sc->status.dy += ms.dy;
1828         sc->status.dz += ms.dz;
1829         sc->status.button = ms.button;
1830         sc->button = ms.button;
1831 
1832         /* queue data */
1833         if (sc->queue.count + sc->inputbytes < sizeof(sc->queue.buf)) {
1834 	    l = min(sc->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
1835 	    bcopy(&sc->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
1836 	    if (sc->inputbytes > l)
1837 	        bcopy(&sc->ipacket[l], &sc->queue.buf[0], sc->inputbytes - l);
1838             sc->queue.tail =
1839 		(sc->queue.tail + sc->inputbytes) % sizeof(sc->queue.buf);
1840             sc->queue.count += sc->inputbytes;
1841 	}
1842         sc->inputbytes = 0;
1843 
1844         if (sc->state & PSM_ASLP) {
1845             sc->state &= ~PSM_ASLP;
1846             wakeup((caddr_t) sc);
1847     	}
1848         selwakeup(&sc->rsel);
1849     }
1850 }
1851 
1852 static int
1853 psmpoll(dev_t dev, int events, struct proc *p)
1854 {
1855     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1856     int s;
1857     int revents = 0;
1858 
1859     /* Return true if a mouse event available */
1860     s = spltty();
1861     if (events & (POLLIN | POLLRDNORM))
1862 	if (sc->queue.count > 0)
1863 	    revents |= events & (POLLIN | POLLRDNORM);
1864 	else
1865 	    selrecord(p, &sc->rsel);
1866 
1867     splx(s);
1868 
1869     return (revents);
1870 }
1871 
1872 /* vendor/model specific routines */
1873 
1874 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
1875 {
1876     if (set_mouse_resolution(kbdc, res) != res)
1877         return FALSE;
1878     if (set_mouse_scaling(kbdc, scale)
1879 	&& set_mouse_scaling(kbdc, scale)
1880 	&& set_mouse_scaling(kbdc, scale)
1881 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3))
1882 	return TRUE;
1883     return FALSE;
1884 }
1885 
1886 #if notyet
1887 /* Logitech MouseMan Cordless II */
1888 static int
1889 enable_lcordless(struct psm_softc *sc)
1890 {
1891     int status[3];
1892     int ch;
1893 
1894     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
1895         return FALSE;
1896     if (status[1] == PSMD_RES_HIGH)
1897 	return FALSE;
1898     ch = (status[0] & 0x07) - 1;	/* channel # */
1899     if ((ch <= 0) || (ch > 4))
1900 	return FALSE;
1901     /*
1902      * status[1]: always one?
1903      * status[2]: battery status? (0-100)
1904      */
1905     return TRUE;
1906 }
1907 #endif /* notyet */
1908 
1909 /* Genius NetScroll Mouse */
1910 static int
1911 enable_groller(struct psm_softc *sc)
1912 {
1913     int status[3];
1914 
1915     /*
1916      * The special sequence to enable the fourth button and the
1917      * roller. Immediately after this sequence check status bytes.
1918      * if the mouse is NetScroll, the second and the third bytes are
1919      * '3' and 'D'.
1920      */
1921 
1922     /*
1923      * If the mouse is an ordinary PS/2 mouse, the status bytes should
1924      * look like the following.
1925      *
1926      * byte 1 bit 7 always 0
1927      *        bit 6 stream mode (0)
1928      *        bit 5 disabled (0)
1929      *        bit 4 1:1 scaling (0)
1930      *        bit 3 always 0
1931      *        bit 0-2 button status
1932      * byte 2 resolution (PSMD_RES_HIGH)
1933      * byte 3 report rate (?)
1934      */
1935 
1936     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
1937         return FALSE;
1938     if ((status[1] != '3') || (status[2] != 'D'))
1939         return FALSE;
1940     /* FIXME!! */
1941     sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1942     sc->hw.buttons = 4;
1943     return TRUE;
1944 }
1945 
1946 /* Genius NetMouse/NetMouse Pro */
1947 static int
1948 enable_gmouse(struct psm_softc *sc)
1949 {
1950     int status[3];
1951 
1952     /*
1953      * The special sequence to enable the middle, "rubber" button.
1954      * Immediately after this sequence check status bytes.
1955      * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
1956      * the second and the third bytes are '3' and 'U'.
1957      * NOTE: NetMouse reports that it has three buttons although it has
1958      * two buttons and a rubber button. NetMouse Pro and MIE Mouse
1959      * say they have three buttons too and they do have a button on the
1960      * side...
1961      */
1962     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
1963         return FALSE;
1964     if ((status[1] != '3') || (status[2] != 'U'))
1965         return FALSE;
1966     return TRUE;
1967 }
1968 
1969 /* ALPS GlidePoint */
1970 static int
1971 enable_aglide(struct psm_softc *sc)
1972 {
1973     int status[3];
1974 
1975     /*
1976      * The special sequence to obtain ALPS GlidePoint specific
1977      * information. Immediately after this sequence, status bytes will
1978      * contain something interesting.
1979      * NOTE: ALPS produces several models of GlidePoint. Some of those
1980      * do not respond to this sequence, thus, cannot be detected this way.
1981      */
1982     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
1983         return FALSE;
1984     if ((status[0] & 0x10) || (status[1] == PSMD_RES_LOW))
1985         return FALSE;
1986     return TRUE;
1987 }
1988 
1989 /* Kensington ThinkingMouse/Trackball */
1990 static int
1991 enable_kmouse(struct psm_softc *sc)
1992 {
1993     static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
1994     KBDC kbdc = sc->kbdc;
1995     int status[3];
1996     int id1;
1997     int id2;
1998     int i;
1999 
2000     id1 = get_aux_id(kbdc);
2001     if (set_mouse_sampling_rate(kbdc, 10) != 10)
2002 	return FALSE;
2003     /*
2004      * The device is now in the native mode? It returns a different
2005      * ID value...
2006      */
2007     id2 = get_aux_id(kbdc);
2008     if ((id1 == id2) || (id2 != 2))
2009 	return FALSE;
2010 
2011     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
2012         return FALSE;
2013 #if PSM_DEBUG >= 2
2014     /* at this point, resolution is LOW, sampling rate is 10/sec */
2015     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2016         return FALSE;
2017 #endif
2018 
2019     /*
2020      * The special sequence to enable the third and fourth buttons.
2021      * Otherwise they behave like the first and second buttons.
2022      */
2023     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2024         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2025 	    return FALSE;
2026     }
2027 
2028     /*
2029      * At this point, the device is using default resolution and
2030      * sampling rate for the native mode.
2031      */
2032     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2033         return FALSE;
2034     if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
2035         return FALSE;
2036 
2037     /* the device appears be enabled by this sequence, diable it for now */
2038     disable_aux_dev(kbdc);
2039     empty_aux_buffer(kbdc, 5);
2040 
2041     return TRUE;
2042 }
2043 
2044 /* Logitech MouseMan+/FirstMouse+ */
2045 static int
2046 enable_mmanplus(struct psm_softc *sc)
2047 {
2048     static char res[] = {
2049 	-1, PSMD_RES_LOW, PSMD_RES_HIGH, PSMD_RES_MEDIUM_HIGH,
2050 	PSMD_RES_MEDIUM_LOW, -1, PSMD_RES_HIGH, PSMD_RES_MEDIUM_LOW,
2051 	PSMD_RES_MEDIUM_HIGH, PSMD_RES_HIGH,
2052     };
2053     KBDC kbdc = sc->kbdc;
2054     int data[3];
2055     int i;
2056 
2057     /* the special sequence to enable the fourth button and the roller. */
2058     for (i = 0; i < sizeof(res)/sizeof(res[0]); ++i) {
2059 	if (res[i] < 0) {
2060 	    if (!set_mouse_scaling(kbdc, 1))
2061 		return FALSE;
2062 	} else {
2063 	    if (set_mouse_resolution(kbdc, res[i]) != res[i])
2064 		return FALSE;
2065 	}
2066     }
2067 
2068     if (get_mouse_status(kbdc, data, 1, 3) < 3)
2069         return FALSE;
2070 
2071     /*
2072      * MouseMan+ and FirstMouse+ return following data.
2073      *
2074      * byte 1 0xc8
2075      * byte 2 ?? (MouseMan+:0xc2, FirstMouse+:0xc6)
2076      * byte 3 model ID? MouseMan+:0x50, FirstMouse+:0x51
2077      */
2078     if ((data[0] & ~MOUSE_PS2_BUTTONS) != 0xc8)
2079         return FALSE;
2080 
2081     /*
2082      * MouseMan+ (or FirstMouse+) is now in its native mode, in which
2083      * the wheel and the fourth button events are encoded in the
2084      * special data packet. The mouse may be put in the IntelliMouse mode
2085      * if it is initialized by the IntelliMouse's method.
2086      */
2087     return TRUE;
2088 }
2089 
2090 /* MS IntelliMouse */
2091 static int
2092 enable_msintelli(struct psm_softc *sc)
2093 {
2094     /*
2095      * Logitech MouseMan+ and FirstMouse+ will also respond to this
2096      * probe routine and act like IntelliMouse.
2097      */
2098 
2099     static unsigned char rate[] = { 200, 100, 80, };
2100     KBDC kbdc = sc->kbdc;
2101     int id;
2102     int i;
2103 
2104     /* the special sequence to enable the third button and the roller. */
2105     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2106         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2107 	    return FALSE;
2108     }
2109     /* the device will give the genuine ID only after the above sequence */
2110     id = get_aux_id(kbdc);
2111     if (id != PSM_INTELLI_ID)
2112 	return FALSE;
2113 
2114     sc->hw.hwid = id;
2115     sc->hw.buttons = 3;
2116 
2117     return TRUE;
2118 }
2119 
2120 #ifdef PSM_HOOKAPM
2121 static int
2122 psmresume(void *dummy)
2123 {
2124     struct psm_softc *sc = psm_softc[(int)dummy];
2125     int unit = (int)dummy;
2126     int err = 0;
2127     int s;
2128     int c;
2129 
2130     if (verbose >= 2)
2131         log(LOG_NOTICE, "psm%d: APM resume hook called.\n", unit);
2132 
2133     /* don't let anybody mess with the aux device */
2134     if (!kbdc_lock(sc->kbdc, TRUE))
2135 	return (EIO);
2136     s = spltty();
2137 
2138     /* save the current controller command byte */
2139     empty_both_buffers(sc->kbdc, 10);
2140     c = get_controller_command_byte(sc->kbdc);
2141     if (verbose >= 2)
2142         log(LOG_DEBUG, "psm%d: current command byte: %04x (psmresume).\n",
2143 	    unit, c);
2144 
2145     /* enable the aux port but disable the aux interrupt and the keyboard */
2146     if ((c == -1) || !set_controller_command_byte(sc->kbdc,
2147 	    kbdc_get_device_mask(sc->kbdc),
2148   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
2149 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2150         /* CONTROLLER ERROR */
2151 	splx(s);
2152         kbdc_lock(sc->kbdc, FALSE);
2153 	log(LOG_ERR, "psm%d: unable to set the command byte (psmresume).\n",
2154 	    unit);
2155 	return (EIO);
2156     }
2157 
2158     /* flush any data */
2159     if (sc->state & PSM_VALID) {
2160 	disable_aux_dev(sc->kbdc);	/* this may fail; but never mind... */
2161 	empty_aux_buffer(sc->kbdc, 10);
2162     }
2163     sc->inputbytes = 0;
2164 
2165 #ifdef PSM_RESETAFTERSUSPEND
2166     /* try to detect the aux device; are you still there? */
2167     if (reinitialize(unit, &sc->mode)) {
2168 	/* yes */
2169 	sc->state |= PSM_VALID;
2170     } else {
2171 	/* the device has gone! */
2172         restore_controller(sc->kbdc, c);
2173 	sc->state &= ~PSM_VALID;
2174 	log(LOG_ERR, "psm%d: the aux device has gone! (psmresume).\n",
2175 	    unit);
2176 	err = ENXIO;
2177     }
2178 #endif /* PSM_RESETAFTERSUSPEND */
2179     splx(s);
2180 
2181     /* restore the driver state */
2182     if ((sc->state & PSM_OPEN) && (err == 0)) {
2183         /* enable the aux device and the port again */
2184 	err = doopen(unit, c);
2185 	if (err != 0)
2186 	    log(LOG_ERR, "psm%d: failed to enable the device (psmresume).\n",
2187 		unit);
2188     } else {
2189         /* restore the keyboard port and disable the aux port */
2190         if (!set_controller_command_byte(sc->kbdc,
2191                 kbdc_get_device_mask(sc->kbdc),
2192                 (c & KBD_KBD_CONTROL_BITS)
2193                     | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
2194             /* CONTROLLER ERROR */
2195             log(LOG_ERR, "psm%d: failed to disable the aux port (psmresume).\n",
2196                 unit);
2197             err = EIO;
2198 	}
2199     }
2200 
2201     /* done */
2202     kbdc_lock(sc->kbdc, FALSE);
2203     if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
2204 	/*
2205 	 * Release the blocked process; it must be notified that the device
2206 	 * cannot be accessed anymore.
2207 	 */
2208         sc->state &= ~PSM_ASLP;
2209         wakeup((caddr_t)sc);
2210     }
2211 
2212     if (verbose >= 2)
2213         log(LOG_DEBUG, "psm%d: APM resume hook exiting.\n", unit);
2214 
2215     return (err);
2216 }
2217 #endif /* PSM_HOOKAPM */
2218 
2219 CDEV_DRIVER_MODULE(psm, isa, psm_driver, psm_devclass,
2220 		   CDEV_MAJOR, psm_cdevsw, 0, 0);
2221 
2222 #endif /* NPSM > 0 */
2223