xref: /freebsd/sys/dev/atkbdc/psm.c (revision 6b3455a7665208c366849f0b2b3bc916fb97516e)
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 /*
24  *  Ported to 386bsd Oct 17, 1992
25  *  Sandi Donno, Computer Science, University of Cape Town, South Africa
26  *  Please send bug reports to sandi@cs.uct.ac.za
27  *
28  *  Thanks are also due to Rick Macklem, rick@snowhite.cis.uoguelph.ca -
29  *  although I was only partially successful in getting the alpha release
30  *  of his "driver for the Logitech and ATI Inport Bus mice for use with
31  *  386bsd and the X386 port" to work with my Microsoft mouse, I nevertheless
32  *  found his code to be an invaluable reference when porting this driver
33  *  to 386bsd.
34  *
35  *  Further modifications for latest 386BSD+patchkit and port to NetBSD,
36  *  Andrew Herbert <andrew@werple.apana.org.au> - 8 June 1993
37  *
38  *  Cloned from the Microsoft Bus Mouse driver, also by Erik Forsberg, by
39  *  Andrew Herbert - 12 June 1993
40  *
41  *  Modified for PS/2 mouse by Charles Hannum <mycroft@ai.mit.edu>
42  *  - 13 June 1993
43  *
44  *  Modified for PS/2 AUX mouse by Shoji Yuen <yuen@nuie.nagoya-u.ac.jp>
45  *  - 24 October 1993
46  *
47  *  Hardware access routines and probe logic rewritten by
48  *  Kazutaka Yokota <yokota@zodiac.mech.utsunomiya-u.ac.jp>
49  *  - 3, 14, 22 October 1996.
50  *  - 12 November 1996. IOCTLs and rearranging `psmread', `psmioctl'...
51  *  - 14, 30 November 1996. Uses `kbdio.c'.
52  *  - 13 December 1996. Uses queuing version of `kbdio.c'.
53  *  - January/February 1997. Tweaked probe logic for
54  *    HiNote UltraII/Latitude/Armada laptops.
55  *  - 30 July 1997. Added APM support.
56  *  - 5 March 1997. Defined driver configuration flags (PSM_CONFIG_XXX).
57  *    Improved sync check logic.
58  *    Vendor specific support routines.
59  */
60 
61 #include <sys/cdefs.h>
62 __FBSDID("$FreeBSD$");
63 
64 #include "opt_psm.h"
65 
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/kernel.h>
69 #include <sys/module.h>
70 #include <sys/bus.h>
71 #include <sys/conf.h>
72 #include <sys/poll.h>
73 #include <sys/syslog.h>
74 #include <machine/bus.h>
75 #include <sys/rman.h>
76 #include <sys/selinfo.h>
77 #include <sys/sysctl.h>
78 #include <sys/time.h>
79 #include <sys/uio.h>
80 
81 #include <sys/limits.h>
82 #include <sys/mouse.h>
83 #include <machine/resource.h>
84 
85 #include <isa/isavar.h>
86 #include <dev/kbd/atkbdcreg.h>
87 
88 /*
89  * Driver specific options: the following options may be set by
90  * `options' statements in the kernel configuration file.
91  */
92 
93 /* debugging */
94 #ifndef PSM_DEBUG
95 #define PSM_DEBUG	0	/* logging: 0: none, 1: brief, 2: verbose */
96 #endif
97 
98 #ifndef PSM_SYNCERR_THRESHOLD1
99 #define PSM_SYNCERR_THRESHOLD1	20
100 #endif
101 
102 #ifndef PSM_INPUT_TIMEOUT
103 #define PSM_INPUT_TIMEOUT	2000000	/* 2 sec */
104 #endif
105 
106 /* end of driver specific options */
107 
108 #define PSM_DRIVER_NAME		"psm"
109 #define PSMCPNP_DRIVER_NAME	"psmcpnp"
110 
111 /* input queue */
112 #define PSM_BUFSIZE		960
113 #define PSM_SMALLBUFSIZE	240
114 
115 /* operation levels */
116 #define PSM_LEVEL_BASE		0
117 #define PSM_LEVEL_STANDARD	1
118 #define PSM_LEVEL_NATIVE	2
119 #define PSM_LEVEL_MIN		PSM_LEVEL_BASE
120 #define PSM_LEVEL_MAX		PSM_LEVEL_NATIVE
121 
122 /* Logitech PS2++ protocol */
123 #define MOUSE_PS2PLUS_CHECKBITS(b)	\
124 				((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
125 #define MOUSE_PS2PLUS_PACKET_TYPE(b)	\
126 				(((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
127 
128 /* some macros */
129 #define PSM_UNIT(dev)		(minor(dev) >> 1)
130 #define PSM_NBLOCKIO(dev)	(minor(dev) & 1)
131 #define PSM_MKMINOR(unit,block)	(((unit) << 1) | ((block) ? 0:1))
132 
133 /* ring buffer */
134 typedef struct ringbuf {
135     int           count;	/* # of valid elements in the buffer */
136     int           head;		/* head pointer */
137     int           tail;		/* tail poiner */
138     unsigned char buf[PSM_BUFSIZE];
139 } ringbuf_t;
140 
141 /* data buffer */
142 typedef struct packetbuf {
143     unsigned char ipacket[16];	/* interim input buffer */
144     int           inputbytes;	/* # of bytes in the input buffer */
145 } packetbuf_t;
146 
147 #ifndef PSM_PACKETQUEUE
148 #define PSM_PACKETQUEUE	128
149 #endif
150 
151 /* driver control block */
152 struct psm_softc {		/* Driver status information */
153     int		  unit;
154     struct selinfo rsel;	/* Process selecting for Input */
155     unsigned char state;	/* Mouse driver state */
156     int           config;	/* driver configuration flags */
157     int           flags;	/* other flags */
158     KBDC          kbdc;		/* handle to access the keyboard controller */
159     struct resource *intr;	/* IRQ resource */
160     void	  *ih;		/* interrupt handle */
161     mousehw_t     hw;		/* hardware information */
162     synapticshw_t synhw;	/* Synaptics-specific hardware information */
163     mousemode_t   mode;		/* operation mode */
164     mousemode_t   dflt_mode;	/* default operation mode */
165     mousestatus_t status;	/* accumulated mouse movement */
166     ringbuf_t     queue;	/* mouse status queue */
167     packetbuf_t   pqueue[PSM_PACKETQUEUE];	/* mouse data queue */
168     int           pqueue_start; /* start of data in queue */
169     int           pqueue_end;   /* end of data in queue */
170     int           button;	/* the latest button state */
171     int		  xold;	/* previous absolute X position */
172     int		  yold;	/* previous absolute Y position */
173     int		  syncerrors; /* XXX: KILL ME! */
174     struct timeval inputtimeout;
175     struct timeval lastsoftintr;	/* time of last soft interrupt */
176     struct timeval lastinputerr;	/* time last sync error happened */
177     int		  watchdog;	/* watchdog timer flag */
178     struct callout_handle callout;	/* watchdog timer call out */
179     struct callout_handle softcallout;	/* buffer timer call out */
180     struct cdev *dev;
181     struct cdev *bdev;
182     int           lasterr;
183     int           cmdcount;
184 };
185 static devclass_t psm_devclass;
186 #define PSM_SOFTC(unit)	((struct psm_softc*)devclass_get_softc(psm_devclass, unit))
187 
188 /* driver state flags (state) */
189 #define PSM_VALID		0x80
190 #define PSM_OPEN		1	/* Device is open */
191 #define PSM_ASLP		2	/* Waiting for mouse data */
192 #define PSM_SOFTARMED		4	/* Software interrupt armed */
193 
194 /* driver configuration flags (config) */
195 #define PSM_CONFIG_RESOLUTION	0x000f	/* resolution */
196 #define PSM_CONFIG_ACCEL	0x00f0  /* acceleration factor */
197 #define PSM_CONFIG_NOCHECKSYNC	0x0100  /* disable sync. test */
198 #define PSM_CONFIG_NOIDPROBE	0x0200  /* disable mouse model probe */
199 #define PSM_CONFIG_NORESET	0x0400  /* don't reset the mouse */
200 #define PSM_CONFIG_FORCETAP	0x0800  /* assume `tap' action exists */
201 #define PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
202 #define PSM_CONFIG_HOOKRESUME	0x2000	/* hook the system resume event */
203 #define PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resume event */
204 #define PSM_CONFIG_SYNCHACK	0x8000 /* enable `out-of-sync' hack */
205 
206 #define PSM_CONFIG_FLAGS	(PSM_CONFIG_RESOLUTION 		\
207 				    | PSM_CONFIG_ACCEL		\
208 				    | PSM_CONFIG_NOCHECKSYNC	\
209 				    | PSM_CONFIG_SYNCHACK	\
210 				    | PSM_CONFIG_NOIDPROBE	\
211 				    | PSM_CONFIG_NORESET	\
212 				    | PSM_CONFIG_FORCETAP	\
213 				    | PSM_CONFIG_IGNPORTERROR	\
214 				    | PSM_CONFIG_HOOKRESUME	\
215 				    | PSM_CONFIG_INITAFTERSUSPEND)
216 
217 /* other flags (flags) */
218 #define PSM_FLAGS_FINGERDOWN	0x0001 /* VersaPad finger down */
219 
220 /* for backward compatibility */
221 #define OLD_MOUSE_GETHWINFO	_IOR('M', 1, old_mousehw_t)
222 #define OLD_MOUSE_GETMODE	_IOR('M', 2, old_mousemode_t)
223 #define OLD_MOUSE_SETMODE	_IOW('M', 3, old_mousemode_t)
224 
225 typedef struct old_mousehw {
226     int buttons;
227     int iftype;
228     int type;
229     int hwid;
230 } old_mousehw_t;
231 
232 typedef struct old_mousemode {
233     int protocol;
234     int rate;
235     int resolution;
236     int accelfactor;
237 } old_mousemode_t;
238 
239 /* packet formatting function */
240 typedef int packetfunc_t(struct psm_softc *, unsigned char *,
241 			      int *, int, mousestatus_t *);
242 
243 /* function prototypes */
244 static void psmidentify(driver_t *, device_t);
245 static int psmprobe(device_t);
246 static int psmattach(device_t);
247 static int psmdetach(device_t);
248 static int psmresume(device_t);
249 
250 static d_open_t psmopen;
251 static d_close_t psmclose;
252 static d_read_t psmread;
253 static d_ioctl_t psmioctl;
254 static d_poll_t psmpoll;
255 
256 static int enable_aux_dev(KBDC);
257 static int disable_aux_dev(KBDC);
258 static int get_mouse_status(KBDC, int *, int, int);
259 static int get_aux_id(KBDC);
260 static int set_mouse_sampling_rate(KBDC, int);
261 static int set_mouse_scaling(KBDC, int);
262 static int set_mouse_resolution(KBDC, int);
263 static int set_mouse_mode(KBDC);
264 static int get_mouse_buttons(KBDC);
265 static int is_a_mouse(int);
266 static void recover_from_error(KBDC);
267 static int restore_controller(KBDC, int);
268 static int doinitialize(struct psm_softc *, mousemode_t *);
269 static int doopen(struct psm_softc *, int);
270 static int reinitialize(struct psm_softc *, int);
271 static char *model_name(int);
272 static void psmsoftintr(void *);
273 static void psmintr(void *);
274 static void psmtimeout(void *);
275 static int timeelapsed(const struct timeval *,
276     int, int, const struct timeval *);
277 static void dropqueue(struct psm_softc *);
278 static void flushpackets(struct psm_softc *);
279 
280 /* vendor specific features */
281 typedef int probefunc_t(struct psm_softc *);
282 
283 static int mouse_id_proc1(KBDC, int, int, int *);
284 static int mouse_ext_command(KBDC, int);
285 static probefunc_t enable_groller;
286 static probefunc_t enable_gmouse;
287 static probefunc_t enable_aglide;
288 static probefunc_t enable_kmouse;
289 static probefunc_t enable_msexplorer;
290 static probefunc_t enable_msintelli;
291 static probefunc_t enable_4dmouse;
292 static probefunc_t enable_4dplus;
293 static probefunc_t enable_mmanplus;
294 static probefunc_t enable_synaptics;
295 static probefunc_t enable_versapad;
296 static int tame_mouse(struct psm_softc *, packetbuf_t *, mousestatus_t *, unsigned char *);
297 
298 static struct {
299     int                 model;
300     unsigned char	syncmask;
301     int 		packetsize;
302     probefunc_t 	*probefunc;
303 } vendortype[] = {
304     /*
305      * WARNING: the order of probe is very important.  Don't mess it
306      * unless you know what you are doing.
307      */
308     { MOUSE_MODEL_NET,			/* Genius NetMouse */
309       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_gmouse, },
310     { MOUSE_MODEL_NETSCROLL,		/* Genius NetScroll */
311       0xc8, 6, enable_groller, },
312     { MOUSE_MODEL_MOUSEMANPLUS,		/* Logitech MouseMan+ */
313       0x08, MOUSE_PS2_PACKETSIZE, enable_mmanplus, },
314     { MOUSE_MODEL_EXPLORER,		/* Microsoft IntelliMouse Explorer */
315       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msexplorer, },
316     { MOUSE_MODEL_4D,			/* A4 Tech 4D Mouse */
317       0x08, MOUSE_4D_PACKETSIZE, enable_4dmouse, },
318     { MOUSE_MODEL_4DPLUS,		/* A4 Tech 4D+ Mouse */
319       0xc8, MOUSE_4DPLUS_PACKETSIZE, enable_4dplus, },
320     { MOUSE_MODEL_INTELLI,		/* Microsoft IntelliMouse */
321       0x08, MOUSE_PS2INTELLI_PACKETSIZE, enable_msintelli, },
322     { MOUSE_MODEL_GLIDEPOINT,		/* ALPS GlidePoint */
323       0xc0, MOUSE_PS2_PACKETSIZE, enable_aglide, },
324     { MOUSE_MODEL_THINK,		/* Kensignton ThinkingMouse */
325       0x80, MOUSE_PS2_PACKETSIZE, enable_kmouse, },
326     { MOUSE_MODEL_VERSAPAD,		/* Interlink electronics VersaPad */
327       0xe8, MOUSE_PS2VERSA_PACKETSIZE, enable_versapad, },
328     { MOUSE_MODEL_SYNAPTICS,		/* Synaptics Touchpad */
329       0xc0, MOUSE_SYNAPTICS_PACKETSIZE, enable_synaptics, },
330     { MOUSE_MODEL_GENERIC,
331       0xc0, MOUSE_PS2_PACKETSIZE, NULL, },
332 };
333 #define GENERIC_MOUSE_ENTRY	((sizeof(vendortype) / sizeof(*vendortype)) - 1)
334 
335 /* device driver declarateion */
336 static device_method_t psm_methods[] = {
337 	/* Device interface */
338 	DEVMETHOD(device_identify,	psmidentify),
339 	DEVMETHOD(device_probe,		psmprobe),
340 	DEVMETHOD(device_attach,	psmattach),
341 	DEVMETHOD(device_detach,	psmdetach),
342 	DEVMETHOD(device_resume,	psmresume),
343 
344 	{ 0, 0 }
345 };
346 
347 static driver_t psm_driver = {
348     PSM_DRIVER_NAME,
349     psm_methods,
350     sizeof(struct psm_softc),
351 };
352 
353 
354 static struct cdevsw psm_cdevsw = {
355 	.d_version =	D_VERSION,
356 	.d_flags =	D_NEEDGIANT,
357 	.d_open =	psmopen,
358 	.d_close =	psmclose,
359 	.d_read =	psmread,
360 	.d_ioctl =	psmioctl,
361 	.d_poll =	psmpoll,
362 	.d_name =	PSM_DRIVER_NAME,
363 };
364 
365 /* debug message level */
366 static int verbose = PSM_DEBUG;
367 
368 /* device I/O routines */
369 static int
370 enable_aux_dev(KBDC kbdc)
371 {
372     int res;
373 
374     res = send_aux_command(kbdc, PSMC_ENABLE_DEV);
375     if (verbose >= 2)
376         log(LOG_DEBUG, "psm: ENABLE_DEV return code:%04x\n", res);
377 
378     return (res == PSM_ACK);
379 }
380 
381 static int
382 disable_aux_dev(KBDC kbdc)
383 {
384     int res;
385 
386     res = send_aux_command(kbdc, PSMC_DISABLE_DEV);
387     if (verbose >= 2)
388         log(LOG_DEBUG, "psm: DISABLE_DEV return code:%04x\n", res);
389 
390     return (res == PSM_ACK);
391 }
392 
393 static int
394 get_mouse_status(KBDC kbdc, int *status, int flag, int len)
395 {
396     int cmd;
397     int res;
398     int i;
399 
400     switch (flag) {
401     case 0:
402     default:
403 	cmd = PSMC_SEND_DEV_STATUS;
404 	break;
405     case 1:
406 	cmd = PSMC_SEND_DEV_DATA;
407 	break;
408     }
409     empty_aux_buffer(kbdc, 5);
410     res = send_aux_command(kbdc, cmd);
411     if (verbose >= 2)
412         log(LOG_DEBUG, "psm: SEND_AUX_DEV_%s return code:%04x\n",
413 	    (flag == 1) ? "DATA" : "STATUS", res);
414     if (res != PSM_ACK)
415         return 0;
416 
417     for (i = 0; i < len; ++i) {
418         status[i] = read_aux_data(kbdc);
419 	if (status[i] < 0)
420 	    break;
421     }
422 
423     if (verbose) {
424         log(LOG_DEBUG, "psm: %s %02x %02x %02x\n",
425             (flag == 1) ? "data" : "status", status[0], status[1], status[2]);
426     }
427 
428     return i;
429 }
430 
431 static int
432 get_aux_id(KBDC kbdc)
433 {
434     int res;
435     int id;
436 
437     empty_aux_buffer(kbdc, 5);
438     res = send_aux_command(kbdc, PSMC_SEND_DEV_ID);
439     if (verbose >= 2)
440         log(LOG_DEBUG, "psm: SEND_DEV_ID return code:%04x\n", res);
441     if (res != PSM_ACK)
442 	return (-1);
443 
444     /* 10ms delay */
445     DELAY(10000);
446 
447     id = read_aux_data(kbdc);
448     if (verbose >= 2)
449         log(LOG_DEBUG, "psm: device ID: %04x\n", id);
450 
451     return id;
452 }
453 
454 static int
455 set_mouse_sampling_rate(KBDC kbdc, int rate)
456 {
457     int res;
458 
459     res = send_aux_command_and_data(kbdc, PSMC_SET_SAMPLING_RATE, rate);
460     if (verbose >= 2)
461         log(LOG_DEBUG, "psm: SET_SAMPLING_RATE (%d) %04x\n", rate, res);
462 
463     return ((res == PSM_ACK) ? rate : -1);
464 }
465 
466 static int
467 set_mouse_scaling(KBDC kbdc, int scale)
468 {
469     int res;
470 
471     switch (scale) {
472     case 1:
473     default:
474 	scale = PSMC_SET_SCALING11;
475 	break;
476     case 2:
477 	scale = PSMC_SET_SCALING21;
478 	break;
479     }
480     res = send_aux_command(kbdc, scale);
481     if (verbose >= 2)
482         log(LOG_DEBUG, "psm: SET_SCALING%s return code:%04x\n",
483 	    (scale == PSMC_SET_SCALING21) ? "21" : "11", res);
484 
485     return (res == PSM_ACK);
486 }
487 
488 /* `val' must be 0 through PSMD_MAX_RESOLUTION */
489 static int
490 set_mouse_resolution(KBDC kbdc, int val)
491 {
492     int res;
493 
494     res = send_aux_command_and_data(kbdc, PSMC_SET_RESOLUTION, val);
495     if (verbose >= 2)
496         log(LOG_DEBUG, "psm: SET_RESOLUTION (%d) %04x\n", val, res);
497 
498     return ((res == PSM_ACK) ? val : -1);
499 }
500 
501 /*
502  * NOTE: once `set_mouse_mode()' is called, the mouse device must be
503  * re-enabled by calling `enable_aux_dev()'
504  */
505 static int
506 set_mouse_mode(KBDC kbdc)
507 {
508     int res;
509 
510     res = send_aux_command(kbdc, PSMC_SET_STREAM_MODE);
511     if (verbose >= 2)
512         log(LOG_DEBUG, "psm: SET_STREAM_MODE return code:%04x\n", res);
513 
514     return (res == PSM_ACK);
515 }
516 
517 static int
518 get_mouse_buttons(KBDC kbdc)
519 {
520     int c = 2;		/* assume two buttons by default */
521     int status[3];
522 
523     /*
524      * NOTE: a special sequence to obtain Logitech Mouse specific
525      * information: set resolution to 25 ppi, set scaling to 1:1, set
526      * scaling to 1:1, set scaling to 1:1. Then the second byte of the
527      * mouse status bytes is the number of available buttons.
528      * Some manufactures also support this sequence.
529      */
530     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
531         return c;
532     if (set_mouse_scaling(kbdc, 1) && set_mouse_scaling(kbdc, 1)
533         && set_mouse_scaling(kbdc, 1)
534 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3)) {
535         if (status[1] != 0)
536             return status[1];
537     }
538     return c;
539 }
540 
541 /* misc subroutines */
542 /*
543  * Someday, I will get the complete list of valid pointing devices and
544  * their IDs... XXX
545  */
546 static int
547 is_a_mouse(int id)
548 {
549 #if 0
550     static int valid_ids[] = {
551         PSM_MOUSE_ID,		/* mouse */
552         PSM_BALLPOINT_ID,	/* ballpoint device */
553         PSM_INTELLI_ID,		/* Intellimouse */
554         PSM_EXPLORER_ID,	/* Intellimouse Explorer */
555         -1			/* end of table */
556     };
557     int i;
558 
559     for (i = 0; valid_ids[i] >= 0; ++i)
560         if (valid_ids[i] == id)
561             return TRUE;
562     return FALSE;
563 #else
564     return TRUE;
565 #endif
566 }
567 
568 static char *
569 model_name(int model)
570 {
571     static struct {
572 	int model_code;
573 	char *model_name;
574     } models[] = {
575         { MOUSE_MODEL_NETSCROLL,	"NetScroll" },
576         { MOUSE_MODEL_NET,		"NetMouse/NetScroll Optical" },
577         { MOUSE_MODEL_GLIDEPOINT,	"GlidePoint" },
578         { MOUSE_MODEL_THINK,		"ThinkingMouse" },
579         { MOUSE_MODEL_INTELLI,		"IntelliMouse" },
580         { MOUSE_MODEL_MOUSEMANPLUS,	"MouseMan+" },
581         { MOUSE_MODEL_VERSAPAD,		"VersaPad" },
582         { MOUSE_MODEL_EXPLORER,		"IntelliMouse Explorer" },
583         { MOUSE_MODEL_4D,		"4D Mouse" },
584         { MOUSE_MODEL_4DPLUS,		"4D+ Mouse" },
585         { MOUSE_MODEL_SYNAPTICS,	"Synaptics Touchpad" },
586         { MOUSE_MODEL_GENERIC,		"Generic PS/2 mouse" },
587         { MOUSE_MODEL_UNKNOWN,		NULL },
588     };
589     int i;
590 
591     for (i = 0; models[i].model_code != MOUSE_MODEL_UNKNOWN; ++i) {
592 	if (models[i].model_code == model)
593 	    return models[i].model_name;
594     }
595     return "Unknown";
596 }
597 
598 static void
599 recover_from_error(KBDC kbdc)
600 {
601     /* discard anything left in the output buffer */
602     empty_both_buffers(kbdc, 10);
603 
604 #if 0
605     /*
606      * NOTE: KBDC_RESET_KBD may not restore the communication between the
607      * keyboard and the controller.
608      */
609     reset_kbd(kbdc);
610 #else
611     /*
612      * NOTE: somehow diagnostic and keyboard port test commands bring the
613      * keyboard back.
614      */
615     if (!test_controller(kbdc))
616         log(LOG_ERR, "psm: keyboard controller failed.\n");
617     /* if there isn't a keyboard in the system, the following error is OK */
618     if (test_kbd_port(kbdc) != 0) {
619 	if (verbose)
620 	    log(LOG_ERR, "psm: keyboard port failed.\n");
621     }
622 #endif
623 }
624 
625 static int
626 restore_controller(KBDC kbdc, int command_byte)
627 {
628     empty_both_buffers(kbdc, 10);
629 
630     if (!set_controller_command_byte(kbdc, 0xff, command_byte)) {
631 	log(LOG_ERR, "psm: failed to restore the keyboard controller "
632 		     "command byte.\n");
633 	empty_both_buffers(kbdc, 10);
634 	return FALSE;
635     } else {
636 	empty_both_buffers(kbdc, 10);
637 	return TRUE;
638     }
639 }
640 
641 /*
642  * Re-initialize the aux port and device. The aux port must be enabled
643  * and its interrupt must be disabled before calling this routine.
644  * The aux device will be disabled before returning.
645  * The keyboard controller must be locked via `kbdc_lock()' before
646  * calling this routine.
647  */
648 static int
649 doinitialize(struct psm_softc *sc, mousemode_t *mode)
650 {
651     KBDC kbdc = sc->kbdc;
652     int stat[3];
653     int i;
654 
655     switch((i = test_aux_port(kbdc))) {
656     case 1:	/* ignore these errors */
657     case 2:
658     case 3:
659     case PSM_ACK:
660 	if (verbose)
661 	    log(LOG_DEBUG, "psm%d: strange result for test aux port (%d).\n",
662 	        sc->unit, i);
663 	/* FALLTHROUGH */
664     case 0:	/* no error */
665     	break;
666     case -1: 	/* time out */
667     default: 	/* error */
668     	recover_from_error(kbdc);
669 	if (sc->config & PSM_CONFIG_IGNPORTERROR)
670 	    break;
671     	log(LOG_ERR, "psm%d: the aux port is not functioning (%d).\n",
672     	    sc->unit, i);
673     	return FALSE;
674     }
675 
676     if (sc->config & PSM_CONFIG_NORESET) {
677 	/*
678 	 * Don't try to reset the pointing device.  It may possibly be
679 	 * left in the unknown state, though...
680 	 */
681     } else {
682 	/*
683 	 * NOTE: some controllers appears to hang the `keyboard' when
684 	 * the aux port doesn't exist and `PSMC_RESET_DEV' is issued.
685 	 */
686 	if (!reset_aux_dev(kbdc)) {
687             recover_from_error(kbdc);
688             log(LOG_ERR, "psm%d: failed to reset the aux device.\n", sc->unit);
689             return FALSE;
690 	}
691     }
692 
693     /*
694      * both the aux port and the aux device is functioning, see
695      * if the device can be enabled.
696      */
697     if (!enable_aux_dev(kbdc) || !disable_aux_dev(kbdc)) {
698         log(LOG_ERR, "psm%d: failed to enable the aux device.\n", sc->unit);
699         return FALSE;
700     }
701     empty_both_buffers(kbdc, 10);	/* remove stray data if any */
702 
703     if (sc->config & PSM_CONFIG_NOIDPROBE) {
704 	i = GENERIC_MOUSE_ENTRY;
705     } else {
706 	/* FIXME: hardware ID, mouse buttons? */
707 
708 	/* other parameters */
709 	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
710 	    if ((*vendortype[i].probefunc)(sc)) {
711 		if (verbose >= 2)
712 		    log(LOG_ERR, "psm%d: found %s\n",
713 			sc->unit, model_name(vendortype[i].model));
714 		break;
715 	    }
716 	}
717     }
718 
719     sc->hw.model = vendortype[i].model;
720     sc->mode.packetsize = vendortype[i].packetsize;
721 
722     /* set mouse parameters */
723     if (mode != (mousemode_t *)NULL) {
724 	if (mode->rate > 0)
725             mode->rate = set_mouse_sampling_rate(kbdc, mode->rate);
726 	if (mode->resolution >= 0)
727             mode->resolution = set_mouse_resolution(kbdc, mode->resolution);
728         set_mouse_scaling(kbdc, 1);
729         set_mouse_mode(kbdc);
730     }
731 
732     /* request a data packet and extract sync. bits */
733     if (get_mouse_status(kbdc, stat, 1, 3) < 3) {
734         log(LOG_DEBUG, "psm%d: failed to get data (doinitialize).\n",
735 	    sc->unit);
736         sc->mode.syncmask[0] = 0;
737     } else {
738         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
739 	/* the NetScroll Mouse will send three more bytes... Ignore them */
740 	empty_aux_buffer(kbdc, 5);
741     }
742 
743     /* just check the status of the mouse */
744     if (get_mouse_status(kbdc, stat, 0, 3) < 3)
745         log(LOG_DEBUG, "psm%d: failed to get status (doinitialize).\n",
746 	    sc->unit);
747 
748     return TRUE;
749 }
750 
751 static int
752 doopen(struct psm_softc *sc, int command_byte)
753 {
754     int stat[3];
755 
756     /* enable the mouse device */
757     if (!enable_aux_dev(sc->kbdc)) {
758 	/* MOUSE ERROR: failed to enable the mouse because:
759 	 * 1) the mouse is faulty,
760 	 * 2) the mouse has been removed(!?)
761 	 * In the latter case, the keyboard may have hung, and need
762 	 * recovery procedure...
763 	 */
764 	recover_from_error(sc->kbdc);
765 #if 0
766 	/* FIXME: we could reset the mouse here and try to enable
767 	 * it again. But it will take long time and it's not a good
768 	 * idea to disable the keyboard that long...
769 	 */
770 	if (!doinitialize(sc, &sc->mode) || !enable_aux_dev(sc->kbdc)) {
771 	    recover_from_error(sc->kbdc);
772 #else
773         {
774 #endif
775             restore_controller(sc->kbdc, command_byte);
776 	    /* mark this device is no longer available */
777 	    sc->state &= ~PSM_VALID;
778 	    log(LOG_ERR, "psm%d: failed to enable the device (doopen).\n",
779 		sc->unit);
780 	    return (EIO);
781 	}
782     }
783 
784     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
785         log(LOG_DEBUG, "psm%d: failed to get status (doopen).\n", sc->unit);
786 
787     /* enable the aux port and interrupt */
788     if (!set_controller_command_byte(sc->kbdc,
789 	    kbdc_get_device_mask(sc->kbdc),
790 	    (command_byte & KBD_KBD_CONTROL_BITS)
791 		| KBD_ENABLE_AUX_PORT | KBD_ENABLE_AUX_INT)) {
792 	/* CONTROLLER ERROR */
793 	disable_aux_dev(sc->kbdc);
794         restore_controller(sc->kbdc, command_byte);
795 	log(LOG_ERR, "psm%d: failed to enable the aux interrupt (doopen).\n",
796 	    sc->unit);
797 	return (EIO);
798     }
799 
800     /* start the watchdog timer */
801     sc->watchdog = FALSE;
802     sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz*2);
803 
804     return (0);
805 }
806 
807 static int
808 reinitialize(struct psm_softc *sc, int doinit)
809 {
810     int err;
811     int c;
812     int s;
813 
814     /* don't let anybody mess with the aux device */
815     if (!kbdc_lock(sc->kbdc, TRUE))
816 	return (EIO);
817     s = spltty();
818 
819     /* block our watchdog timer */
820     sc->watchdog = FALSE;
821     untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
822     callout_handle_init(&sc->callout);
823 
824     /* save the current controller command byte */
825     empty_both_buffers(sc->kbdc, 10);
826     c = get_controller_command_byte(sc->kbdc);
827     if (verbose >= 2)
828         log(LOG_DEBUG, "psm%d: current command byte: %04x (reinitialize).\n",
829 	    sc->unit, c);
830 
831     /* enable the aux port but disable the aux interrupt and the keyboard */
832     if ((c == -1) || !set_controller_command_byte(sc->kbdc,
833 	    kbdc_get_device_mask(sc->kbdc),
834   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
835 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
836         /* CONTROLLER ERROR */
837 	splx(s);
838         kbdc_lock(sc->kbdc, FALSE);
839 	log(LOG_ERR, "psm%d: unable to set the command byte (reinitialize).\n",
840 	    sc->unit);
841 	return (EIO);
842     }
843 
844     /* flush any data */
845     if (sc->state & PSM_VALID) {
846 	disable_aux_dev(sc->kbdc);	/* this may fail; but never mind... */
847 	empty_aux_buffer(sc->kbdc, 10);
848     }
849     flushpackets(sc);
850     sc->syncerrors = 0;
851 
852     /* try to detect the aux device; are you still there? */
853     err = 0;
854     if (doinit) {
855 	if (doinitialize(sc, &sc->mode)) {
856 	    /* yes */
857 	    sc->state |= PSM_VALID;
858 	} else {
859 	    /* the device has gone! */
860 	    restore_controller(sc->kbdc, c);
861 	    sc->state &= ~PSM_VALID;
862 	    log(LOG_ERR, "psm%d: the aux device has gone! (reinitialize).\n",
863 		sc->unit);
864 	    err = ENXIO;
865 	}
866     }
867     splx(s);
868 
869     /* restore the driver state */
870     if ((sc->state & PSM_OPEN) && (err == 0)) {
871         /* enable the aux device and the port again */
872 	err = doopen(sc, c);
873 	if (err != 0)
874 	    log(LOG_ERR, "psm%d: failed to enable the device (reinitialize).\n",
875 		sc->unit);
876     } else {
877         /* restore the keyboard port and disable the aux port */
878         if (!set_controller_command_byte(sc->kbdc,
879                 kbdc_get_device_mask(sc->kbdc),
880                 (c & KBD_KBD_CONTROL_BITS)
881                     | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
882             /* CONTROLLER ERROR */
883             log(LOG_ERR, "psm%d: failed to disable the aux port (reinitialize).\n",
884                 sc->unit);
885             err = EIO;
886 	}
887     }
888 
889     kbdc_lock(sc->kbdc, FALSE);
890     return (err);
891 }
892 
893 /* psm driver entry points */
894 
895 static void
896 psmidentify(driver_t *driver, device_t parent)
897 {
898     device_t psmc;
899     device_t psm;
900     u_long irq;
901     int unit;
902 
903     unit = device_get_unit(parent);
904 
905     /* always add at least one child */
906     psm = BUS_ADD_CHILD(parent, KBDC_RID_AUX, driver->name, unit);
907     if (psm == NULL)
908 	return;
909 
910     irq = bus_get_resource_start(psm, SYS_RES_IRQ, KBDC_RID_AUX);
911     if (irq > 0)
912 	return;
913 
914     /*
915      * If the PS/2 mouse device has already been reported by ACPI or
916      * PnP BIOS, obtain the IRQ resource from it.
917      * (See psmcpnp_attach() below.)
918      */
919     psmc = device_find_child(device_get_parent(parent),
920 			     PSMCPNP_DRIVER_NAME, unit);
921     if (psmc == NULL)
922 	return;
923     irq = bus_get_resource_start(psmc, SYS_RES_IRQ, 0);
924     if (irq <= 0)
925 	return;
926     bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
927 }
928 
929 #define endprobe(v)	do {   if (bootverbose)				\
930 				--verbose;   				\
931                             kbdc_set_device_mask(sc->kbdc, mask);	\
932 			    kbdc_lock(sc->kbdc, FALSE);			\
933 			    return (v);	     				\
934 			} while (0)
935 
936 static int
937 psmprobe(device_t dev)
938 {
939     int unit = device_get_unit(dev);
940     struct psm_softc *sc = device_get_softc(dev);
941     int stat[3];
942     int command_byte;
943     int mask;
944     int rid;
945     int i;
946 
947 #if 0
948     kbdc_debug(TRUE);
949 #endif
950 
951     /* see if IRQ is available */
952     rid = KBDC_RID_AUX;
953     sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
954 				      RF_SHAREABLE | RF_ACTIVE);
955     if (sc->intr == NULL) {
956 	if (bootverbose)
957             device_printf(dev, "unable to allocate IRQ\n");
958         return (ENXIO);
959     }
960     bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
961 
962     sc->unit = unit;
963     sc->kbdc = atkbdc_open(device_get_unit(device_get_parent(dev)));
964     sc->config = device_get_flags(dev) & PSM_CONFIG_FLAGS;
965     /* XXX: for backward compatibility */
966 #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
967     sc->config |=
968 #ifdef PSM_RESETAFTERSUSPEND
969 	PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
970 #else
971 	PSM_CONFIG_HOOKRESUME;
972 #endif
973 #endif /* PSM_HOOKRESUME | PSM_HOOKAPM */
974     sc->flags = 0;
975     if (bootverbose)
976         ++verbose;
977 
978     device_set_desc(dev, "PS/2 Mouse");
979 
980     if (!kbdc_lock(sc->kbdc, TRUE)) {
981         printf("psm%d: unable to lock the controller.\n", unit);
982         if (bootverbose)
983             --verbose;
984 	return (ENXIO);
985     }
986 
987     /*
988      * NOTE: two bits in the command byte controls the operation of the
989      * aux port (mouse port): the aux port disable bit (bit 5) and the aux
990      * port interrupt (IRQ 12) enable bit (bit 2).
991      */
992 
993     /* discard anything left after the keyboard initialization */
994     empty_both_buffers(sc->kbdc, 10);
995 
996     /* save the current command byte; it will be used later */
997     mask = kbdc_get_device_mask(sc->kbdc) & ~KBD_AUX_CONTROL_BITS;
998     command_byte = get_controller_command_byte(sc->kbdc);
999     if (verbose)
1000         printf("psm%d: current command byte:%04x\n", unit, command_byte);
1001     if (command_byte == -1) {
1002         /* CONTROLLER ERROR */
1003         printf("psm%d: unable to get the current command byte value.\n",
1004             unit);
1005         endprobe(ENXIO);
1006     }
1007 
1008     /*
1009      * disable the keyboard port while probing the aux port, which must be
1010      * enabled during this routine
1011      */
1012     if (!set_controller_command_byte(sc->kbdc,
1013 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1014   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1015                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1016         /*
1017 	 * this is CONTROLLER ERROR; I don't know how to recover
1018          * from this error...
1019 	 */
1020         restore_controller(sc->kbdc, command_byte);
1021         printf("psm%d: unable to set the command byte.\n", unit);
1022         endprobe(ENXIO);
1023     }
1024     write_controller_command(sc->kbdc, KBDC_ENABLE_AUX_PORT);
1025 
1026     /*
1027      * NOTE: `test_aux_port()' is designed to return with zero if the aux
1028      * port exists and is functioning. However, some controllers appears
1029      * to respond with zero even when the aux port doesn't exist. (It may
1030      * be that this is only the case when the controller DOES have the aux
1031      * port but the port is not wired on the motherboard.) The keyboard
1032      * controllers without the port, such as the original AT, are
1033      * supporsed to return with an error code or simply time out. In any
1034      * case, we have to continue probing the port even when the controller
1035      * passes this test.
1036      *
1037      * XXX: some controllers erroneously return the error code 1, 2 or 3
1038      * when it has the perfectly functional aux port. We have to ignore
1039      * this error code. Even if the controller HAS error with the aux
1040      * port, it will be detected later...
1041      * XXX: another incompatible controller returns PSM_ACK (0xfa)...
1042      */
1043     switch ((i = test_aux_port(sc->kbdc))) {
1044     case 1:	   /* ignore these errors */
1045     case 2:
1046     case 3:
1047     case PSM_ACK:
1048         if (verbose)
1049 	    printf("psm%d: strange result for test aux port (%d).\n",
1050 	        unit, i);
1051 	/* FALLTHROUGH */
1052     case 0:        /* no error */
1053         break;
1054     case -1:        /* time out */
1055     default:        /* error */
1056         recover_from_error(sc->kbdc);
1057 	if (sc->config & PSM_CONFIG_IGNPORTERROR)
1058 	    break;
1059         restore_controller(sc->kbdc, command_byte);
1060         if (verbose)
1061             printf("psm%d: the aux port is not functioning (%d).\n",
1062                 unit, i);
1063         endprobe(ENXIO);
1064     }
1065 
1066     if (sc->config & PSM_CONFIG_NORESET) {
1067 	/*
1068 	 * Don't try to reset the pointing device.  It may possibly be
1069 	 * left in the unknown state, though...
1070 	 */
1071     } else {
1072 	/*
1073 	 * NOTE: some controllers appears to hang the `keyboard' when the aux
1074 	 * port doesn't exist and `PSMC_RESET_DEV' is issued.
1075 	 *
1076 	 * Attempt to reset the controller twice -- this helps
1077 	 * pierce through some KVM switches. The second reset
1078 	 * is non-fatal.
1079 	 */
1080 	if (!reset_aux_dev(sc->kbdc)) {
1081             recover_from_error(sc->kbdc);
1082             restore_controller(sc->kbdc, command_byte);
1083             if (verbose)
1084         	printf("psm%d: failed to reset the aux device.\n", unit);
1085             endprobe(ENXIO);
1086 	} else if (!reset_aux_dev(sc->kbdc)) {
1087 	    recover_from_error(sc->kbdc);
1088 	    if (verbose >= 2)
1089         	printf("psm%d: failed to reset the aux device (2).\n",
1090         	    unit);
1091 	}
1092     }
1093 
1094     /*
1095      * both the aux port and the aux device is functioning, see if the
1096      * device can be enabled. NOTE: when enabled, the device will start
1097      * sending data; we shall immediately disable the device once we know
1098      * the device can be enabled.
1099      */
1100     if (!enable_aux_dev(sc->kbdc) || !disable_aux_dev(sc->kbdc)) {
1101         /* MOUSE ERROR */
1102 	recover_from_error(sc->kbdc);
1103 	restore_controller(sc->kbdc, command_byte);
1104 	if (verbose)
1105 	    printf("psm%d: failed to enable the aux device.\n", unit);
1106         endprobe(ENXIO);
1107     }
1108 
1109     /* save the default values after reset */
1110     if (get_mouse_status(sc->kbdc, stat, 0, 3) >= 3) {
1111 	sc->dflt_mode.rate = sc->mode.rate = stat[2];
1112 	sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1113     } else {
1114 	sc->dflt_mode.rate = sc->mode.rate = -1;
1115 	sc->dflt_mode.resolution = sc->mode.resolution = -1;
1116     }
1117 
1118     /* hardware information */
1119     sc->hw.iftype = MOUSE_IF_PS2;
1120 
1121     /* verify the device is a mouse */
1122     sc->hw.hwid = get_aux_id(sc->kbdc);
1123     if (!is_a_mouse(sc->hw.hwid)) {
1124         restore_controller(sc->kbdc, command_byte);
1125         if (verbose)
1126             printf("psm%d: unknown device type (%d).\n", unit, sc->hw.hwid);
1127         endprobe(ENXIO);
1128     }
1129     switch (sc->hw.hwid) {
1130     case PSM_BALLPOINT_ID:
1131         sc->hw.type = MOUSE_TRACKBALL;
1132         break;
1133     case PSM_MOUSE_ID:
1134     case PSM_INTELLI_ID:
1135     case PSM_EXPLORER_ID:
1136     case PSM_4DMOUSE_ID:
1137     case PSM_4DPLUS_ID:
1138         sc->hw.type = MOUSE_MOUSE;
1139         break;
1140     default:
1141         sc->hw.type = MOUSE_UNKNOWN;
1142         break;
1143     }
1144 
1145     if (sc->config & PSM_CONFIG_NOIDPROBE) {
1146 	sc->hw.buttons = 2;
1147 	i = GENERIC_MOUSE_ENTRY;
1148     } else {
1149 	/* # of buttons */
1150 	sc->hw.buttons = get_mouse_buttons(sc->kbdc);
1151 
1152 	/* other parameters */
1153 	for (i = 0; vendortype[i].probefunc != NULL; ++i) {
1154 	    if ((*vendortype[i].probefunc)(sc)) {
1155 		if (verbose >= 2)
1156 		    printf("psm%d: found %s\n",
1157 			   unit, model_name(vendortype[i].model));
1158 		break;
1159 	    }
1160 	}
1161     }
1162 
1163     sc->hw.model = vendortype[i].model;
1164 
1165     sc->dflt_mode.level = PSM_LEVEL_BASE;
1166     sc->dflt_mode.packetsize = MOUSE_PS2_PACKETSIZE;
1167     sc->dflt_mode.accelfactor = (sc->config & PSM_CONFIG_ACCEL) >> 4;
1168     if (sc->config & PSM_CONFIG_NOCHECKSYNC)
1169         sc->dflt_mode.syncmask[0] = 0;
1170     else
1171         sc->dflt_mode.syncmask[0] = vendortype[i].syncmask;
1172     if (sc->config & PSM_CONFIG_FORCETAP)
1173         sc->mode.syncmask[0] &= ~MOUSE_PS2_TAP;
1174     sc->dflt_mode.syncmask[1] = 0;	/* syncbits */
1175     sc->mode = sc->dflt_mode;
1176     sc->mode.packetsize = vendortype[i].packetsize;
1177 
1178     /* set mouse parameters */
1179 #if 0
1180     /*
1181      * A version of Logitech FirstMouse+ won't report wheel movement,
1182      * if SET_DEFAULTS is sent...  Don't use this command.
1183      * This fix was found by Takashi Nishida.
1184      */
1185     i = send_aux_command(sc->kbdc, PSMC_SET_DEFAULTS);
1186     if (verbose >= 2)
1187 	printf("psm%d: SET_DEFAULTS return code:%04x\n", unit, i);
1188 #endif
1189     if (sc->config & PSM_CONFIG_RESOLUTION) {
1190         sc->mode.resolution
1191 	    = set_mouse_resolution(sc->kbdc,
1192 				   (sc->config & PSM_CONFIG_RESOLUTION) - 1);
1193     } else if (sc->mode.resolution >= 0) {
1194 	sc->mode.resolution
1195 	    = set_mouse_resolution(sc->kbdc, sc->dflt_mode.resolution);
1196     }
1197     if (sc->mode.rate > 0) {
1198 	sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, sc->dflt_mode.rate);
1199     }
1200     set_mouse_scaling(sc->kbdc, 1);
1201 
1202     /* request a data packet and extract sync. bits */
1203     if (get_mouse_status(sc->kbdc, stat, 1, 3) < 3) {
1204         printf("psm%d: failed to get data.\n", unit);
1205         sc->mode.syncmask[0] = 0;
1206     } else {
1207         sc->mode.syncmask[1] = stat[0] & sc->mode.syncmask[0];	/* syncbits */
1208 	/* the NetScroll Mouse will send three more bytes... Ignore them */
1209 	empty_aux_buffer(sc->kbdc, 5);
1210     }
1211 
1212     /* just check the status of the mouse */
1213     /*
1214      * NOTE: XXX there are some arcane controller/mouse combinations out
1215      * there, which hung the controller unless there is data transmission
1216      * after ACK from the mouse.
1217      */
1218     if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3) {
1219         printf("psm%d: failed to get status.\n", unit);
1220     } else {
1221 	/*
1222 	 * When in its native mode, some mice operate with different
1223 	 * default parameters than in the PS/2 compatible mode.
1224 	 */
1225         sc->dflt_mode.rate = sc->mode.rate = stat[2];
1226         sc->dflt_mode.resolution = sc->mode.resolution = stat[1];
1227      }
1228 
1229     /* disable the aux port for now... */
1230     if (!set_controller_command_byte(sc->kbdc,
1231 	    KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS,
1232             (command_byte & KBD_KBD_CONTROL_BITS)
1233                 | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1234         /*
1235 	 * this is CONTROLLER ERROR; I don't know the proper way to
1236          * recover from this error...
1237 	 */
1238         restore_controller(sc->kbdc, command_byte);
1239         printf("psm%d: unable to set the command byte.\n", unit);
1240         endprobe(ENXIO);
1241     }
1242 
1243     /* done */
1244     kbdc_set_device_mask(sc->kbdc, mask | KBD_AUX_CONTROL_BITS);
1245     kbdc_lock(sc->kbdc, FALSE);
1246     return (0);
1247 }
1248 
1249 static int
1250 psmattach(device_t dev)
1251 {
1252     int unit = device_get_unit(dev);
1253     struct psm_softc *sc = device_get_softc(dev);
1254     int error;
1255     int rid;
1256 
1257     /* Setup initial state */
1258     sc->state = PSM_VALID;
1259     callout_handle_init(&sc->callout);
1260 
1261     /* Setup our interrupt handler */
1262     rid = KBDC_RID_AUX;
1263     sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1264 				      RF_SHAREABLE | RF_ACTIVE);
1265     if (sc->intr == NULL)
1266 	return (ENXIO);
1267     error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, psmintr, sc, &sc->ih);
1268     if (error) {
1269 	bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1270 	return (error);
1271     }
1272 
1273     /* Done */
1274     sc->dev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, FALSE), 0, 0, 0666,
1275 		       "psm%d", unit);
1276     sc->bdev = make_dev(&psm_cdevsw, PSM_MKMINOR(unit, TRUE), 0, 0, 0666,
1277 			"bpsm%d", unit);
1278 
1279     if (!verbose) {
1280         printf("psm%d: model %s, device ID %d\n",
1281 	    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
1282     } else {
1283         printf("psm%d: model %s, device ID %d-%02x, %d buttons\n",
1284 	    unit, model_name(sc->hw.model),
1285 	    sc->hw.hwid & 0x00ff, sc->hw.hwid >> 8, sc->hw.buttons);
1286 	printf("psm%d: config:%08x, flags:%08x, packet size:%d\n",
1287 	    unit, sc->config, sc->flags, sc->mode.packetsize);
1288 	printf("psm%d: syncmask:%02x, syncbits:%02x\n",
1289 	    unit, sc->mode.syncmask[0], sc->mode.syncmask[1]);
1290     }
1291 
1292     if (bootverbose)
1293         --verbose;
1294 
1295     return (0);
1296 }
1297 
1298 static int
1299 psmdetach(device_t dev)
1300 {
1301     struct psm_softc *sc;
1302     int rid;
1303 
1304     sc = device_get_softc(dev);
1305     if (sc->state & PSM_OPEN)
1306 	return EBUSY;
1307 
1308     rid = KBDC_RID_AUX;
1309     bus_teardown_intr(dev, sc->intr, sc->ih);
1310     bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);
1311 
1312     destroy_dev(sc->dev);
1313     destroy_dev(sc->bdev);
1314 
1315     return 0;
1316 }
1317 
1318 static int
1319 psmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
1320 {
1321     int unit = PSM_UNIT(dev);
1322     struct psm_softc *sc;
1323     int command_byte;
1324     int err;
1325     int s;
1326 
1327     /* Get device data */
1328     sc = PSM_SOFTC(unit);
1329     if ((sc == NULL) || (sc->state & PSM_VALID) == 0)
1330 	/* the device is no longer valid/functioning */
1331         return (ENXIO);
1332 
1333     /* Disallow multiple opens */
1334     if (sc->state & PSM_OPEN)
1335         return (EBUSY);
1336 
1337     device_busy(devclass_get_device(psm_devclass, unit));
1338 
1339     /* Initialize state */
1340     sc->mode.level = sc->dflt_mode.level;
1341     sc->mode.protocol = sc->dflt_mode.protocol;
1342     sc->watchdog = FALSE;
1343 
1344     /* flush the event queue */
1345     sc->queue.count = 0;
1346     sc->queue.head = 0;
1347     sc->queue.tail = 0;
1348     sc->status.flags = 0;
1349     sc->status.button = 0;
1350     sc->status.obutton = 0;
1351     sc->status.dx = 0;
1352     sc->status.dy = 0;
1353     sc->status.dz = 0;
1354     sc->button = 0;
1355     sc->pqueue_start = 0;
1356     sc->pqueue_end = 0;
1357 
1358     /* empty input buffer */
1359     flushpackets(sc);
1360     sc->syncerrors = 0;
1361 
1362     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1363     if (!kbdc_lock(sc->kbdc, TRUE))
1364 	return (EIO);
1365 
1366     /* save the current controller command byte */
1367     s = spltty();
1368     command_byte = get_controller_command_byte(sc->kbdc);
1369 
1370     /* enable the aux port and temporalily disable the keyboard */
1371     if ((command_byte == -1)
1372         || !set_controller_command_byte(sc->kbdc,
1373 	    kbdc_get_device_mask(sc->kbdc),
1374   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1375 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1376         /* CONTROLLER ERROR; do you know how to get out of this? */
1377         kbdc_lock(sc->kbdc, FALSE);
1378 	splx(s);
1379 	log(LOG_ERR, "psm%d: unable to set the command byte (psmopen).\n",
1380 	    unit);
1381 	return (EIO);
1382     }
1383     /*
1384      * Now that the keyboard controller is told not to generate
1385      * the keyboard and mouse interrupts, call `splx()' to allow
1386      * the other tty interrupts. The clock interrupt may also occur,
1387      * but timeout routines will be blocked by the poll flag set
1388      * via `kbdc_lock()'
1389      */
1390     splx(s);
1391 
1392     /* enable the mouse device */
1393     err = doopen(sc, command_byte);
1394 
1395     /* done */
1396     if (err == 0)
1397         sc->state |= PSM_OPEN;
1398     kbdc_lock(sc->kbdc, FALSE);
1399     return (err);
1400 }
1401 
1402 static int
1403 psmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
1404 {
1405     int unit = PSM_UNIT(dev);
1406     struct psm_softc *sc = PSM_SOFTC(unit);
1407     int stat[3];
1408     int command_byte;
1409     int s;
1410 
1411     /* don't let timeout routines in the keyboard driver to poll the kbdc */
1412     if (!kbdc_lock(sc->kbdc, TRUE))
1413 	return (EIO);
1414 
1415     /* save the current controller command byte */
1416     s = spltty();
1417     command_byte = get_controller_command_byte(sc->kbdc);
1418     if (command_byte == -1) {
1419         kbdc_lock(sc->kbdc, FALSE);
1420 	splx(s);
1421 	return (EIO);
1422     }
1423 
1424     /* disable the aux interrupt and temporalily disable the keyboard */
1425     if (!set_controller_command_byte(sc->kbdc,
1426 	    kbdc_get_device_mask(sc->kbdc),
1427   	    KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1428 	        | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1429 	log(LOG_ERR, "psm%d: failed to disable the aux int (psmclose).\n",
1430 	    unit);
1431 	/* CONTROLLER ERROR;
1432 	 * NOTE: we shall force our way through. Because the only
1433 	 * ill effect we shall see is that we may not be able
1434 	 * to read ACK from the mouse, and it doesn't matter much
1435 	 * so long as the mouse will accept the DISABLE command.
1436 	 */
1437     }
1438     splx(s);
1439 
1440     /* stop the watchdog timer */
1441     untimeout(psmtimeout, (void *)(uintptr_t)sc, sc->callout);
1442     callout_handle_init(&sc->callout);
1443 
1444     /* remove anything left in the output buffer */
1445     empty_aux_buffer(sc->kbdc, 10);
1446 
1447     /* disable the aux device, port and interrupt */
1448     if (sc->state & PSM_VALID) {
1449         if (!disable_aux_dev(sc->kbdc)) {
1450 	    /* MOUSE ERROR;
1451 	     * NOTE: we don't return error and continue, pretending
1452 	     * we have successfully disabled the device. It's OK because
1453 	     * the interrupt routine will discard any data from the mouse
1454 	     * hereafter.
1455 	     */
1456 	    log(LOG_ERR, "psm%d: failed to disable the device (psmclose).\n",
1457 		unit);
1458         }
1459 
1460         if (get_mouse_status(sc->kbdc, stat, 0, 3) < 3)
1461             log(LOG_DEBUG, "psm%d: failed to get status (psmclose).\n",
1462 		unit);
1463     }
1464 
1465     if (!set_controller_command_byte(sc->kbdc,
1466 	    kbdc_get_device_mask(sc->kbdc),
1467 	    (command_byte & KBD_KBD_CONTROL_BITS)
1468 	        | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1469 	/* CONTROLLER ERROR;
1470 	 * we shall ignore this error; see the above comment.
1471 	 */
1472 	log(LOG_ERR, "psm%d: failed to disable the aux port (psmclose).\n",
1473 	    unit);
1474     }
1475 
1476     /* remove anything left in the output buffer */
1477     empty_aux_buffer(sc->kbdc, 10);
1478 
1479     /* close is almost always successful */
1480     sc->state &= ~PSM_OPEN;
1481     kbdc_lock(sc->kbdc, FALSE);
1482     device_unbusy(devclass_get_device(psm_devclass, unit));
1483     return (0);
1484 }
1485 
1486 static int
1487 tame_mouse(struct psm_softc *sc, packetbuf_t *pb, mousestatus_t *status, unsigned char *buf)
1488 {
1489     static unsigned char butmapps2[8] = {
1490         0,
1491         MOUSE_PS2_BUTTON1DOWN,
1492         MOUSE_PS2_BUTTON2DOWN,
1493         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN,
1494         MOUSE_PS2_BUTTON3DOWN,
1495         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON3DOWN,
1496         MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1497         MOUSE_PS2_BUTTON1DOWN | MOUSE_PS2_BUTTON2DOWN | MOUSE_PS2_BUTTON3DOWN,
1498     };
1499     static unsigned char butmapmsc[8] = {
1500         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1501         MOUSE_MSC_BUTTON2UP | MOUSE_MSC_BUTTON3UP,
1502         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON3UP,
1503         MOUSE_MSC_BUTTON3UP,
1504         MOUSE_MSC_BUTTON1UP | MOUSE_MSC_BUTTON2UP,
1505         MOUSE_MSC_BUTTON2UP,
1506         MOUSE_MSC_BUTTON1UP,
1507         0,
1508     };
1509     int mapped;
1510     int i;
1511 
1512     if (sc->mode.level == PSM_LEVEL_BASE) {
1513         mapped = status->button & ~MOUSE_BUTTON4DOWN;
1514         if (status->button & MOUSE_BUTTON4DOWN)
1515 	    mapped |= MOUSE_BUTTON1DOWN;
1516         status->button = mapped;
1517         buf[0] = MOUSE_PS2_SYNC | butmapps2[mapped & MOUSE_STDBUTTONS];
1518         i = imax(imin(status->dx, 255), -256);
1519 	if (i < 0)
1520 	    buf[0] |= MOUSE_PS2_XNEG;
1521         buf[1] = i;
1522         i = imax(imin(status->dy, 255), -256);
1523 	if (i < 0)
1524 	    buf[0] |= MOUSE_PS2_YNEG;
1525         buf[2] = i;
1526 	return MOUSE_PS2_PACKETSIZE;
1527     } else if (sc->mode.level == PSM_LEVEL_STANDARD) {
1528         buf[0] = MOUSE_MSC_SYNC | butmapmsc[status->button & MOUSE_STDBUTTONS];
1529         i = imax(imin(status->dx, 255), -256);
1530         buf[1] = i >> 1;
1531         buf[3] = i - buf[1];
1532         i = imax(imin(status->dy, 255), -256);
1533         buf[2] = i >> 1;
1534         buf[4] = i - buf[2];
1535         i = imax(imin(status->dz, 127), -128);
1536         buf[5] = (i >> 1) & 0x7f;
1537         buf[6] = (i - (i >> 1)) & 0x7f;
1538         buf[7] = (~status->button >> 3) & 0x7f;
1539 	return MOUSE_SYS_PACKETSIZE;
1540     }
1541     return pb->inputbytes;
1542 }
1543 
1544 static int
1545 psmread(struct cdev *dev, struct uio *uio, int flag)
1546 {
1547     register struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1548     unsigned char buf[PSM_SMALLBUFSIZE];
1549     int error = 0;
1550     int s;
1551     int l;
1552 
1553     if ((sc->state & PSM_VALID) == 0)
1554 	return EIO;
1555 
1556     /* block until mouse activity occured */
1557     s = spltty();
1558     while (sc->queue.count <= 0) {
1559         if (PSM_NBLOCKIO(dev)) {
1560             splx(s);
1561             return EWOULDBLOCK;
1562         }
1563         sc->state |= PSM_ASLP;
1564         error = tsleep( sc, PZERO | PCATCH, "psmrea", 0);
1565         sc->state &= ~PSM_ASLP;
1566         if (error) {
1567             splx(s);
1568             return error;
1569         } else if ((sc->state & PSM_VALID) == 0) {
1570             /* the device disappeared! */
1571             splx(s);
1572             return EIO;
1573 	}
1574     }
1575     splx(s);
1576 
1577     /* copy data to the user land */
1578     while ((sc->queue.count > 0) && (uio->uio_resid > 0)) {
1579         s = spltty();
1580 	l = imin(sc->queue.count, uio->uio_resid);
1581 	if (l > sizeof(buf))
1582 	    l = sizeof(buf);
1583 	if (l > sizeof(sc->queue.buf) - sc->queue.head) {
1584 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0],
1585 		sizeof(sc->queue.buf) - sc->queue.head);
1586 	    bcopy(&sc->queue.buf[0],
1587 		&buf[sizeof(sc->queue.buf) - sc->queue.head],
1588 		l - (sizeof(sc->queue.buf) - sc->queue.head));
1589 	} else {
1590 	    bcopy(&sc->queue.buf[sc->queue.head], &buf[0], l);
1591 	}
1592 	sc->queue.count -= l;
1593 	sc->queue.head = (sc->queue.head + l) % sizeof(sc->queue.buf);
1594         splx(s);
1595         error = uiomove(buf, l, uio);
1596         if (error)
1597 	    break;
1598     }
1599 
1600     return error;
1601 }
1602 
1603 static int
1604 block_mouse_data(struct psm_softc *sc, int *c)
1605 {
1606     int s;
1607 
1608     if (!kbdc_lock(sc->kbdc, TRUE))
1609 	return EIO;
1610 
1611     s = spltty();
1612     *c = get_controller_command_byte(sc->kbdc);
1613     if ((*c == -1)
1614 	|| !set_controller_command_byte(sc->kbdc,
1615 	    kbdc_get_device_mask(sc->kbdc),
1616             KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1617                 | KBD_ENABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1618         /* this is CONTROLLER ERROR */
1619 	splx(s);
1620         kbdc_lock(sc->kbdc, FALSE);
1621 	return EIO;
1622     }
1623 
1624     /*
1625      * The device may be in the middle of status data transmission.
1626      * The transmission will be interrupted, thus, incomplete status
1627      * data must be discarded. Although the aux interrupt is disabled
1628      * at the keyboard controller level, at most one aux interrupt
1629      * may have already been pending and a data byte is in the
1630      * output buffer; throw it away. Note that the second argument
1631      * to `empty_aux_buffer()' is zero, so that the call will just
1632      * flush the internal queue.
1633      * `psmintr()' will be invoked after `splx()' if an interrupt is
1634      * pending; it will see no data and returns immediately.
1635      */
1636     empty_aux_buffer(sc->kbdc, 0);	/* flush the queue */
1637     read_aux_data_no_wait(sc->kbdc);	/* throw away data if any */
1638     flushpackets(sc);
1639     splx(s);
1640 
1641     return 0;
1642 }
1643 
1644 static void
1645 dropqueue(struct psm_softc *sc)
1646 {
1647 
1648     	sc->queue.count = 0;
1649    	sc->queue.head = 0;
1650     	sc->queue.tail = 0;
1651 	if ((sc->state & PSM_SOFTARMED) != 0) {
1652 		sc->state &= ~PSM_SOFTARMED;
1653 		untimeout(psmsoftintr, (void *)(uintptr_t)sc, sc->softcallout);
1654 	}
1655 	sc->pqueue_start = sc->pqueue_end;
1656 }
1657 
1658 static void
1659 flushpackets(struct psm_softc *sc)
1660 {
1661 
1662 	dropqueue(sc);
1663 	bzero(&sc->pqueue, sizeof(sc->pqueue));
1664 }
1665 
1666 static int
1667 unblock_mouse_data(struct psm_softc *sc, int c)
1668 {
1669     int error = 0;
1670 
1671     /*
1672      * We may have seen a part of status data during `set_mouse_XXX()'.
1673      * they have been queued; flush it.
1674      */
1675     empty_aux_buffer(sc->kbdc, 0);
1676 
1677     /* restore ports and interrupt */
1678     if (!set_controller_command_byte(sc->kbdc,
1679             kbdc_get_device_mask(sc->kbdc),
1680 	    c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1681         /* CONTROLLER ERROR; this is serious, we may have
1682          * been left with the inaccessible keyboard and
1683          * the disabled mouse interrupt.
1684          */
1685         error = EIO;
1686     }
1687 
1688     kbdc_lock(sc->kbdc, FALSE);
1689     return error;
1690 }
1691 
1692 static int
1693 psmioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1694 {
1695     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
1696     mousemode_t mode;
1697     mousestatus_t status;
1698 #if (defined(MOUSE_GETVARS))
1699     mousevar_t *var;
1700 #endif
1701     mousedata_t *data;
1702     int stat[3];
1703     int command_byte;
1704     int error = 0;
1705     int s;
1706 
1707     /* Perform IOCTL command */
1708     switch (cmd) {
1709 
1710     case OLD_MOUSE_GETHWINFO:
1711 	s = spltty();
1712         ((old_mousehw_t *)addr)->buttons = sc->hw.buttons;
1713         ((old_mousehw_t *)addr)->iftype = sc->hw.iftype;
1714         ((old_mousehw_t *)addr)->type = sc->hw.type;
1715         ((old_mousehw_t *)addr)->hwid = sc->hw.hwid & 0x00ff;
1716 	splx(s);
1717         break;
1718 
1719     case MOUSE_GETHWINFO:
1720 	s = spltty();
1721         *(mousehw_t *)addr = sc->hw;
1722 	if (sc->mode.level == PSM_LEVEL_BASE)
1723 	    ((mousehw_t *)addr)->model = MOUSE_MODEL_GENERIC;
1724 	splx(s);
1725         break;
1726 
1727     case MOUSE_SYN_GETHWINFO:
1728 	s = spltty();
1729 	if (sc->hw.model == MOUSE_MODEL_SYNAPTICS)
1730 	    *(synapticshw_t *)addr = sc->synhw;
1731 	else
1732 	    error = EINVAL;
1733 	splx(s);
1734 	break;
1735 
1736     case OLD_MOUSE_GETMODE:
1737 	s = spltty();
1738 	switch (sc->mode.level) {
1739 	case PSM_LEVEL_BASE:
1740 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1741 	    break;
1742 	case PSM_LEVEL_STANDARD:
1743 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1744 	    break;
1745 	case PSM_LEVEL_NATIVE:
1746 	    ((old_mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1747 	    break;
1748 	}
1749         ((old_mousemode_t *)addr)->rate = sc->mode.rate;
1750         ((old_mousemode_t *)addr)->resolution = sc->mode.resolution;
1751         ((old_mousemode_t *)addr)->accelfactor = sc->mode.accelfactor;
1752 	splx(s);
1753         break;
1754 
1755     case MOUSE_GETMODE:
1756 	s = spltty();
1757         *(mousemode_t *)addr = sc->mode;
1758         ((mousemode_t *)addr)->resolution =
1759 	    MOUSE_RES_LOW - sc->mode.resolution;
1760 	switch (sc->mode.level) {
1761 	case PSM_LEVEL_BASE:
1762 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1763 	    ((mousemode_t *)addr)->packetsize = MOUSE_PS2_PACKETSIZE;
1764 	    break;
1765 	case PSM_LEVEL_STANDARD:
1766 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_SYSMOUSE;
1767 	    ((mousemode_t *)addr)->packetsize = MOUSE_SYS_PACKETSIZE;
1768 	    ((mousemode_t *)addr)->syncmask[0] = MOUSE_SYS_SYNCMASK;
1769 	    ((mousemode_t *)addr)->syncmask[1] = MOUSE_SYS_SYNC;
1770 	    break;
1771 	case PSM_LEVEL_NATIVE:
1772 	    /* FIXME: this isn't quite correct... XXX */
1773 	    ((mousemode_t *)addr)->protocol = MOUSE_PROTO_PS2;
1774 	    break;
1775 	}
1776 	splx(s);
1777         break;
1778 
1779     case OLD_MOUSE_SETMODE:
1780     case MOUSE_SETMODE:
1781 	if (cmd == OLD_MOUSE_SETMODE) {
1782 	    mode.rate = ((old_mousemode_t *)addr)->rate;
1783 	    /*
1784 	     * resolution  old I/F   new I/F
1785 	     * default        0         0
1786 	     * low            1        -2
1787 	     * medium low     2        -3
1788 	     * medium high    3        -4
1789 	     * high           4        -5
1790 	     */
1791 	    if (((old_mousemode_t *)addr)->resolution > 0)
1792 	        mode.resolution = -((old_mousemode_t *)addr)->resolution - 1;
1793 	    mode.accelfactor = ((old_mousemode_t *)addr)->accelfactor;
1794 	    mode.level = -1;
1795 	} else {
1796 	    mode = *(mousemode_t *)addr;
1797 	}
1798 
1799 	/* adjust and validate parameters. */
1800 	if (mode.rate > UCHAR_MAX)
1801 	    return EINVAL;
1802         if (mode.rate == 0)
1803             mode.rate = sc->dflt_mode.rate;
1804 	else if (mode.rate == -1)
1805 	    /* don't change the current setting */
1806 	    ;
1807 	else if (mode.rate < 0)
1808 	    return EINVAL;
1809 	if (mode.resolution >= UCHAR_MAX)
1810 	    return EINVAL;
1811 	if (mode.resolution >= 200)
1812 	    mode.resolution = MOUSE_RES_HIGH;
1813 	else if (mode.resolution >= 100)
1814 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1815 	else if (mode.resolution >= 50)
1816 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1817 	else if (mode.resolution > 0)
1818 	    mode.resolution = MOUSE_RES_LOW;
1819         if (mode.resolution == MOUSE_RES_DEFAULT)
1820             mode.resolution = sc->dflt_mode.resolution;
1821         else if (mode.resolution == -1)
1822 	    /* don't change the current setting */
1823 	    ;
1824         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1825             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1826 	if (mode.level == -1)
1827 	    /* don't change the current setting */
1828 	    mode.level = sc->mode.level;
1829 	else if ((mode.level < PSM_LEVEL_MIN) || (mode.level > PSM_LEVEL_MAX))
1830 	    return EINVAL;
1831         if (mode.accelfactor == -1)
1832 	    /* don't change the current setting */
1833 	    mode.accelfactor = sc->mode.accelfactor;
1834         else if (mode.accelfactor < 0)
1835 	    return EINVAL;
1836 
1837 	/* don't allow anybody to poll the keyboard controller */
1838 	error = block_mouse_data(sc, &command_byte);
1839 	if (error)
1840             return error;
1841 
1842         /* set mouse parameters */
1843 	if (mode.rate > 0)
1844 	    mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1845 	if (mode.resolution >= 0)
1846 	    mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1847 	set_mouse_scaling(sc->kbdc, 1);
1848 	get_mouse_status(sc->kbdc, stat, 0, 3);
1849 
1850         s = spltty();
1851     	sc->mode.rate = mode.rate;
1852     	sc->mode.resolution = mode.resolution;
1853     	sc->mode.accelfactor = mode.accelfactor;
1854     	sc->mode.level = mode.level;
1855         splx(s);
1856 
1857 	unblock_mouse_data(sc, command_byte);
1858         break;
1859 
1860     case MOUSE_GETLEVEL:
1861 	*(int *)addr = sc->mode.level;
1862         break;
1863 
1864     case MOUSE_SETLEVEL:
1865 	if ((*(int *)addr < PSM_LEVEL_MIN) || (*(int *)addr > PSM_LEVEL_MAX))
1866 	    return EINVAL;
1867 	sc->mode.level = *(int *)addr;
1868         break;
1869 
1870     case MOUSE_GETSTATUS:
1871         s = spltty();
1872 	status = sc->status;
1873 	sc->status.flags = 0;
1874 	sc->status.obutton = sc->status.button;
1875 	sc->status.button = 0;
1876 	sc->status.dx = 0;
1877 	sc->status.dy = 0;
1878 	sc->status.dz = 0;
1879         splx(s);
1880         *(mousestatus_t *)addr = status;
1881         break;
1882 
1883 #if (defined(MOUSE_GETVARS))
1884     case MOUSE_GETVARS:
1885 	var = (mousevar_t *)addr;
1886 	bzero(var, sizeof(*var));
1887 	s = spltty();
1888         var->var[0] = MOUSE_VARS_PS2_SIG;
1889         var->var[1] = sc->config;
1890         var->var[2] = sc->flags;
1891 	splx(s);
1892         break;
1893 
1894     case MOUSE_SETVARS:
1895 	return ENODEV;
1896 #endif /* MOUSE_GETVARS */
1897 
1898     case MOUSE_READSTATE:
1899     case MOUSE_READDATA:
1900 	data = (mousedata_t *)addr;
1901 	if (data->len > sizeof(data->buf)/sizeof(data->buf[0]))
1902 	    return EINVAL;
1903 
1904 	error = block_mouse_data(sc, &command_byte);
1905 	if (error)
1906             return error;
1907         if ((data->len = get_mouse_status(sc->kbdc, data->buf,
1908 		(cmd == MOUSE_READDATA) ? 1 : 0, data->len)) <= 0)
1909             error = EIO;
1910 	unblock_mouse_data(sc, command_byte);
1911 	break;
1912 
1913 #if (defined(MOUSE_SETRESOLUTION))
1914     case MOUSE_SETRESOLUTION:
1915 	mode.resolution = *(int *)addr;
1916 	if (mode.resolution >= UCHAR_MAX)
1917 	    return EINVAL;
1918 	else if (mode.resolution >= 200)
1919 	    mode.resolution = MOUSE_RES_HIGH;
1920 	else if (mode.resolution >= 100)
1921 	    mode.resolution = MOUSE_RES_MEDIUMHIGH;
1922 	else if (mode.resolution >= 50)
1923 	    mode.resolution = MOUSE_RES_MEDIUMLOW;
1924 	else if (mode.resolution > 0)
1925 	    mode.resolution = MOUSE_RES_LOW;
1926         if (mode.resolution == MOUSE_RES_DEFAULT)
1927             mode.resolution = sc->dflt_mode.resolution;
1928         else if (mode.resolution == -1)
1929 	    mode.resolution = sc->mode.resolution;
1930         else if (mode.resolution < 0) /* MOUSE_RES_LOW/MEDIUM/HIGH */
1931             mode.resolution = MOUSE_RES_LOW - mode.resolution;
1932 
1933 	error = block_mouse_data(sc, &command_byte);
1934 	if (error)
1935             return error;
1936         sc->mode.resolution = set_mouse_resolution(sc->kbdc, mode.resolution);
1937 	if (sc->mode.resolution != mode.resolution)
1938 	    error = EIO;
1939 	unblock_mouse_data(sc, command_byte);
1940         break;
1941 #endif /* MOUSE_SETRESOLUTION */
1942 
1943 #if (defined(MOUSE_SETRATE))
1944     case MOUSE_SETRATE:
1945 	mode.rate = *(int *)addr;
1946 	if (mode.rate > UCHAR_MAX)
1947 	    return EINVAL;
1948         if (mode.rate == 0)
1949             mode.rate = sc->dflt_mode.rate;
1950 	else if (mode.rate < 0)
1951 	    mode.rate = sc->mode.rate;
1952 
1953 	error = block_mouse_data(sc, &command_byte);
1954 	if (error)
1955             return error;
1956         sc->mode.rate = set_mouse_sampling_rate(sc->kbdc, mode.rate);
1957 	if (sc->mode.rate != mode.rate)
1958 	    error = EIO;
1959 	unblock_mouse_data(sc, command_byte);
1960         break;
1961 #endif /* MOUSE_SETRATE */
1962 
1963 #if (defined(MOUSE_SETSCALING))
1964     case MOUSE_SETSCALING:
1965 	if ((*(int *)addr <= 0) || (*(int *)addr > 2))
1966 	    return EINVAL;
1967 
1968 	error = block_mouse_data(sc, &command_byte);
1969 	if (error)
1970             return error;
1971         if (!set_mouse_scaling(sc->kbdc, *(int *)addr))
1972 	    error = EIO;
1973 	unblock_mouse_data(sc, command_byte);
1974         break;
1975 #endif /* MOUSE_SETSCALING */
1976 
1977 #if (defined(MOUSE_GETHWID))
1978     case MOUSE_GETHWID:
1979 	error = block_mouse_data(sc, &command_byte);
1980 	if (error)
1981             return error;
1982         sc->hw.hwid &= ~0x00ff;
1983         sc->hw.hwid |= get_aux_id(sc->kbdc);
1984 	*(int *)addr = sc->hw.hwid & 0x00ff;
1985 	unblock_mouse_data(sc, command_byte);
1986         break;
1987 #endif /* MOUSE_GETHWID */
1988 
1989     default:
1990 	return ENOTTY;
1991     }
1992 
1993     return error;
1994 }
1995 
1996 static void
1997 psmtimeout(void *arg)
1998 {
1999     struct psm_softc *sc;
2000     int s;
2001 
2002     sc = (struct psm_softc *)arg;
2003     s = spltty();
2004     if (sc->watchdog && kbdc_lock(sc->kbdc, TRUE)) {
2005 	if (verbose >= 4)
2006 	    log(LOG_DEBUG, "psm%d: lost interrupt?\n", sc->unit);
2007 	psmintr(sc);
2008 	kbdc_lock(sc->kbdc, FALSE);
2009     }
2010     sc->watchdog = TRUE;
2011     splx(s);
2012     sc->callout = timeout(psmtimeout, (void *)(uintptr_t)sc, hz);
2013 }
2014 
2015 static int psmhz = 20;
2016 SYSCTL_INT(_debug, OID_AUTO, psmhz, CTLFLAG_RW, &psmhz, 0, "");
2017 
2018 static int psm_soft_timeout = 500000; /* 0.5 sec */
2019 SYSCTL_INT(_debug, OID_AUTO, psm_soft_timeout, CTLFLAG_RW,
2020     &psm_soft_timeout, 0, "");
2021 
2022 static int psmerrsecs = 2;
2023 SYSCTL_INT(_debug, OID_AUTO, psmerrsecs, CTLFLAG_RW, &psmerrsecs, 0, "");
2024 static int psmerrusecs = 0;
2025 SYSCTL_INT(_debug, OID_AUTO, psmerrusecs, CTLFLAG_RW, &psmerrusecs, 0, "");
2026 static int psmsecs = 0;
2027 SYSCTL_INT(_debug, OID_AUTO, psmsecs, CTLFLAG_RW, &psmsecs, 0, "");
2028 static int psmusecs = 500000;
2029 SYSCTL_INT(_debug, OID_AUTO, psmusecs, CTLFLAG_RW, &psmusecs, 0, "");
2030 
2031 static void
2032 psmintr(void *arg)
2033 {
2034     struct psm_softc *sc = arg;
2035     struct timeval now;
2036     int c;
2037     packetbuf_t *pb;
2038     int haderror = 0;
2039 
2040 
2041     /* read until there is nothing to read */
2042     while((c = read_aux_data_no_wait(sc->kbdc)) != -1) {
2043 
2044         pb = &sc->pqueue[sc->pqueue_end];
2045         /* discard the byte if the device is not open */
2046         if ((sc->state & PSM_OPEN) == 0)
2047             continue;
2048 
2049 	getmicrouptime(&now);
2050 	if ((pb->inputbytes > 0) && timevalcmp(&now, &sc->inputtimeout, >)) {
2051 #if DEBUG
2052 	    log(LOG_DEBUG, "psmintr: delay too long; resetting byte count\n");
2053 #endif
2054 	    pb->inputbytes = 0;
2055 	    sc->syncerrors = 0;
2056 	}
2057 	sc->inputtimeout.tv_sec = PSM_INPUT_TIMEOUT/1000000;
2058 	sc->inputtimeout.tv_usec = PSM_INPUT_TIMEOUT%1000000;
2059 	timevaladd(&sc->inputtimeout, &now);
2060 
2061         pb->ipacket[pb->inputbytes++] = c;
2062         if (pb->inputbytes < sc->mode.packetsize)
2063 	    continue;
2064 
2065 #if DEBUG
2066         log(LOG_DEBUG, "psmintr: %02x %02x %02x %02x %02x %02x\n",
2067 	    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2],
2068 	    pb->ipacket[3], pb->ipacket[4], pb->ipacket[5]);
2069 #endif
2070 
2071 	c = pb->ipacket[0];
2072 
2073 	if ((c & sc->mode.syncmask[0]) != sc->mode.syncmask[1]) {
2074 #if DEBUG
2075             log(LOG_DEBUG, "psmintr: out of sync (%04x != %04x) %d"
2076 		" cmds since last error.\n",
2077 		c & sc->mode.syncmask[0], sc->mode.syncmask[1],
2078 		sc->cmdcount - sc->lasterr);
2079 #endif
2080 	    haderror = 1;
2081 	    sc->lasterr = sc->cmdcount;
2082 	    dropqueue(sc);
2083 	    ++sc->syncerrors;
2084 	    sc->lastinputerr = now;
2085 	    if (sc->syncerrors < sc->mode.packetsize) {
2086 #if DEBUG
2087 		log(LOG_DEBUG, "psmintr: discard a byte (%d).\n", sc->syncerrors);
2088 #endif
2089 		--pb->inputbytes;
2090 		bcopy(&pb->ipacket[1], &pb->ipacket[0], pb->inputbytes);
2091 	    } else if (sc->syncerrors == sc->mode.packetsize) {
2092 #if DEBUG
2093 		log(LOG_DEBUG, "psmintr: re-enable the mouse.\n");
2094 #endif
2095 		pb->inputbytes = 0;
2096 		disable_aux_dev(sc->kbdc);
2097 		enable_aux_dev(sc->kbdc);
2098 	    } else if (sc->syncerrors < PSM_SYNCERR_THRESHOLD1) {
2099 #if DEBUG
2100 		log(LOG_DEBUG, "psmintr: discard a byte (%d).\n", sc->syncerrors);
2101 #endif
2102 		--pb->inputbytes;
2103 		bcopy(&pb->ipacket[1], &pb->ipacket[0], pb->inputbytes);
2104 	    } else if (sc->syncerrors >= PSM_SYNCERR_THRESHOLD1) {
2105 #if DEBUG
2106 		log(LOG_DEBUG, "psmintr: reset the mouse.\n");
2107 #endif
2108 		reinitialize(sc, TRUE);
2109 	    }
2110 	    continue;
2111 	}
2112 	/* if this packet is at all bogus then drop the packet. */
2113 	if (haderror ||
2114 	    !timeelapsed(&sc->lastinputerr, psmerrsecs, psmerrusecs, &now)) {
2115 		pb->inputbytes = 0;
2116 		haderror = 0;
2117 		continue;
2118 	}
2119 
2120 	sc->cmdcount++;
2121 	if (++sc->pqueue_end >= PSM_PACKETQUEUE)
2122 		sc->pqueue_end = 0;
2123 	/*
2124 	 * If we've filled the queue then call the softintr ourselves,
2125 	 * otherwise schedule the interrupt for later.
2126 	 */
2127 	if (!timeelapsed(&sc->lastsoftintr, psmsecs, psmusecs, &now) ||
2128 	    (sc->pqueue_end == sc->pqueue_start)) {
2129     		if ((sc->state & PSM_SOFTARMED) != 0) {
2130 			sc->state &= ~PSM_SOFTARMED;
2131 			untimeout(psmsoftintr, arg, sc->softcallout);
2132 		}
2133 		psmsoftintr(arg);
2134 	} else if ((sc->state & PSM_SOFTARMED) == 0) {
2135 		sc->state |= PSM_SOFTARMED;
2136 		sc->softcallout = timeout(psmsoftintr, arg,
2137 		    psmhz < 1 ? 1 : (hz/psmhz));
2138 	}
2139     }
2140 }
2141 
2142 static void
2143 psmsoftintr(void *arg)
2144 {
2145     /*
2146      * the table to turn PS/2 mouse button bits (MOUSE_PS2_BUTTON?DOWN)
2147      * into `mousestatus' button bits (MOUSE_BUTTON?DOWN).
2148      */
2149     static int butmap[8] = {
2150         0,
2151 	MOUSE_BUTTON1DOWN,
2152 	MOUSE_BUTTON3DOWN,
2153 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
2154 	MOUSE_BUTTON2DOWN,
2155 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
2156 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
2157         MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
2158     };
2159     static int butmap_versapad[8] = {
2160 	0,
2161 	MOUSE_BUTTON3DOWN,
2162 	0,
2163 	MOUSE_BUTTON3DOWN,
2164 	MOUSE_BUTTON1DOWN,
2165 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
2166 	MOUSE_BUTTON1DOWN,
2167 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN
2168     };
2169     register struct psm_softc *sc = arg;
2170     mousestatus_t ms;
2171     int w, x, y, z;
2172     int c;
2173     int l;
2174     int x0, y0;
2175     int s;
2176     packetbuf_t *pb;
2177 
2178     getmicrouptime(&sc->lastsoftintr);
2179 
2180     s = spltty();
2181 
2182     do {
2183 
2184 	pb = &sc->pqueue[sc->pqueue_start];
2185 	c = pb->ipacket[0];
2186 	/*
2187 	 * A kludge for Kensington device!
2188 	 * The MSB of the horizontal count appears to be stored in
2189 	 * a strange place.
2190 	 */
2191 	if (sc->hw.model == MOUSE_MODEL_THINK)
2192 	    pb->ipacket[1] |= (c & MOUSE_PS2_XOVERFLOW) ? 0x80 : 0;
2193 
2194         /* ignore the overflow bits... */
2195         x = (c & MOUSE_PS2_XNEG) ?  pb->ipacket[1] - 256 : pb->ipacket[1];
2196         y = (c & MOUSE_PS2_YNEG) ?  pb->ipacket[2] - 256 : pb->ipacket[2];
2197 	z = 0;
2198         ms.obutton = sc->button;		  /* previous button state */
2199         ms.button = butmap[c & MOUSE_PS2_BUTTONS];
2200 	/* `tapping' action */
2201 	if (sc->config & PSM_CONFIG_FORCETAP)
2202 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2203 
2204 	switch (sc->hw.model) {
2205 
2206 	case MOUSE_MODEL_EXPLORER:
2207 	    /*
2208 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2209 	     * byte 1:  oy ox sy sx 1  M  R  L
2210 	     * byte 2:  x  x  x  x  x  x  x  x
2211 	     * byte 3:  y  y  y  y  y  y  y  y
2212 	     * byte 4:  *  *  S2 S1 s  d2 d1 d0
2213 	     *
2214 	     * L, M, R, S1, S2: left, middle, right and side buttons
2215 	     * s: wheel data sign bit
2216 	     * d2-d0: wheel data
2217 	     */
2218 	    z = (pb->ipacket[3] & MOUSE_EXPLORER_ZNEG)
2219 		? (pb->ipacket[3] & 0x0f) - 16 : (pb->ipacket[3] & 0x0f);
2220 	    ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON4DOWN)
2221 		? MOUSE_BUTTON4DOWN : 0;
2222 	    ms.button |= (pb->ipacket[3] & MOUSE_EXPLORER_BUTTON5DOWN)
2223 		? MOUSE_BUTTON5DOWN : 0;
2224 	    break;
2225 
2226 	case MOUSE_MODEL_INTELLI:
2227 	case MOUSE_MODEL_NET:
2228 	    /* wheel data is in the fourth byte */
2229 	    z = (char)pb->ipacket[3];
2230 	    /* some mice may send 7 when there is no Z movement?! XXX */
2231 	    if ((z >= 7) || (z <= -7))
2232 		z = 0;
2233 	    /* some compatible mice have additional buttons */
2234 	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON4DOWN)
2235 		? MOUSE_BUTTON4DOWN : 0;
2236 	    ms.button |= (c & MOUSE_PS2INTELLI_BUTTON5DOWN)
2237 		? MOUSE_BUTTON5DOWN : 0;
2238 	    break;
2239 
2240 	case MOUSE_MODEL_MOUSEMANPLUS:
2241 	    /*
2242 	     * PS2++ protocl packet
2243 	     *
2244 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2245 	     * byte 1:  *  1  p3 p2 1  *  *  *
2246 	     * byte 2:  c1 c2 p1 p0 d1 d0 1  0
2247 	     *
2248 	     * p3-p0: packet type
2249 	     * c1, c2: c1 & c2 == 1, if p2 == 0
2250 	     *         c1 & c2 == 0, if p2 == 1
2251 	     *
2252 	     * packet type: 0 (device type)
2253 	     * See comments in enable_mmanplus() below.
2254 	     *
2255 	     * packet type: 1 (wheel data)
2256 	     *
2257 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2258 	     * byte 3:  h  *  B5 B4 s  d2 d1 d0
2259 	     *
2260 	     * h: 1, if horizontal roller data
2261 	     *    0, if vertical roller data
2262 	     * B4, B5: button 4 and 5
2263 	     * s: sign bit
2264 	     * d2-d0: roller data
2265 	     *
2266 	     * packet type: 2 (reserved)
2267 	     */
2268 	    if (((c & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
2269 		    && (abs(x) > 191)
2270 		    && MOUSE_PS2PLUS_CHECKBITS(pb->ipacket)) {
2271 		/* the extended data packet encodes button and wheel events */
2272 		switch (MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket)) {
2273 		case 1:
2274 		    /* wheel data packet */
2275 		    x = y = 0;
2276 		    if (pb->ipacket[2] & 0x80) {
2277 			/* horizontal roller count - ignore it XXX*/
2278 		    } else {
2279 			/* vertical roller count */
2280 			z = (pb->ipacket[2] & MOUSE_PS2PLUS_ZNEG)
2281 			    ? (pb->ipacket[2] & 0x0f) - 16
2282 			    : (pb->ipacket[2] & 0x0f);
2283 		    }
2284 		    ms.button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
2285 			? MOUSE_BUTTON4DOWN : 0;
2286 		    ms.button |= (pb->ipacket[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
2287 			? MOUSE_BUTTON5DOWN : 0;
2288 		    break;
2289 		case 2:
2290 		    /* this packet type is reserved by Logitech... */
2291 		    /*
2292 		     * IBM ScrollPoint Mouse uses this packet type to
2293 		     * encode both vertical and horizontal scroll movement.
2294 		     */
2295 		    x = y = 0;
2296 		    /* horizontal count */
2297 		    if (pb->ipacket[2] & 0x0f)
2298 			z = (pb->ipacket[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
2299 		    /* vertical count */
2300 		    if (pb->ipacket[2] & 0xf0)
2301 			z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
2302 #if 0
2303 		    /* vertical count */
2304 		    z = (pb->ipacket[2] & MOUSE_SPOINT_ZNEG)
2305 			? ((pb->ipacket[2] >> 4) & 0x0f) - 16
2306 			: ((pb->ipacket[2] >> 4) & 0x0f);
2307 		    /* horizontal count */
2308 		    w = (pb->ipacket[2] & MOUSE_SPOINT_WNEG)
2309 			? (pb->ipacket[2] & 0x0f) - 16
2310 			: (pb->ipacket[2] & 0x0f);
2311 #endif
2312 		    break;
2313 		case 0:
2314 		    /* device type packet - shouldn't happen */
2315 		    /* FALLTHROUGH */
2316 		default:
2317 		    x = y = 0;
2318 		    ms.button = ms.obutton;
2319 		    if (bootverbose)
2320 			log(LOG_DEBUG, "psmintr: unknown PS2++ packet type %d: "
2321 				       "0x%02x 0x%02x 0x%02x\n",
2322 			    MOUSE_PS2PLUS_PACKET_TYPE(pb->ipacket),
2323 			    pb->ipacket[0], pb->ipacket[1], pb->ipacket[2]);
2324 		    break;
2325 		}
2326 	    } else {
2327 		/* preserve button states */
2328 		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2329 	    }
2330 	    break;
2331 
2332 	case MOUSE_MODEL_GLIDEPOINT:
2333 	    /* `tapping' action */
2334 	    ms.button |= ((c & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2335 	    break;
2336 
2337 	case MOUSE_MODEL_NETSCROLL:
2338 	    /* three addtional bytes encode buttons and wheel events */
2339 	    ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON3DOWN)
2340 		? MOUSE_BUTTON4DOWN : 0;
2341 	    ms.button |= (pb->ipacket[3] & MOUSE_PS2_BUTTON1DOWN)
2342 		? MOUSE_BUTTON5DOWN : 0;
2343 	    z = (pb->ipacket[3] & MOUSE_PS2_XNEG)
2344 		? pb->ipacket[4] - 256 : pb->ipacket[4];
2345 	    break;
2346 
2347 	case MOUSE_MODEL_THINK:
2348 	    /* the fourth button state in the first byte */
2349 	    ms.button |= (c & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
2350 	    break;
2351 
2352 	case MOUSE_MODEL_VERSAPAD:
2353 	    /* VersaPad PS/2 absolute mode message format
2354 	     *
2355 	     * [packet1]     7   6   5   4   3   2   1   0(LSB)
2356 	     *  ipacket[0]:  1   1   0   A   1   L   T   R
2357 	     *  ipacket[1]: H7  H6  H5  H4  H3  H2  H1  H0
2358 	     *  ipacket[2]: V7  V6  V5  V4  V3  V2  V1  V0
2359 	     *  ipacket[3]:  1   1   1   A   1   L   T   R
2360 	     *  ipacket[4]:V11 V10  V9  V8 H11 H10  H9  H8
2361 	     *  ipacket[5]:  0  P6  P5  P4  P3  P2  P1  P0
2362 	     *
2363 	     * [note]
2364 	     *  R: right physical mouse button (1=on)
2365 	     *  T: touch pad virtual button (1=tapping)
2366 	     *  L: left physical mouse button (1=on)
2367 	     *  A: position data is valid (1=valid)
2368 	     *  H: horizontal data (12bit signed integer. H11 is sign bit.)
2369 	     *  V: vertical data (12bit signed integer. V11 is sign bit.)
2370 	     *  P: pressure data
2371 	     *
2372 	     * Tapping is mapped to MOUSE_BUTTON4.
2373 	     */
2374 	    ms.button = butmap_versapad[c & MOUSE_PS2VERSA_BUTTONS];
2375 	    ms.button |= (c & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2376 	    x = y = 0;
2377 	    if (c & MOUSE_PS2VERSA_IN_USE) {
2378 		x0 = pb->ipacket[1] | (((pb->ipacket[4]) & 0x0f) << 8);
2379 		y0 = pb->ipacket[2] | (((pb->ipacket[4]) & 0xf0) << 4);
2380 		if (x0 & 0x800)
2381 		    x0 -= 0x1000;
2382 		if (y0 & 0x800)
2383 		    y0 -= 0x1000;
2384 		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2385 		    x = sc->xold - x0;
2386 		    y = y0 - sc->yold;
2387 		    if (x < 0)	/* XXX */
2388 			x++;
2389 		    else if (x)
2390 			x--;
2391 		    if (y < 0)
2392 			y++;
2393 		    else if (y)
2394 			y--;
2395 		} else {
2396 		    sc->flags |= PSM_FLAGS_FINGERDOWN;
2397 		}
2398 		sc->xold = x0;
2399 		sc->yold = y0;
2400 	    } else {
2401 		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2402 	    }
2403 	    c = ((x < 0) ? MOUSE_PS2_XNEG : 0)
2404 		| ((y < 0) ? MOUSE_PS2_YNEG : 0);
2405 	    break;
2406 
2407 	case MOUSE_MODEL_4D:
2408 	    /*
2409 	     *          b7 b6 b5 b4 b3 b2 b1 b0
2410 	     * byte 1:  s2 d2 s1 d1 1  M  R  L
2411 	     * byte 2:  sx x  x  x  x  x  x  x
2412 	     * byte 3:  sy y  y  y  y  y  y  y
2413 	     *
2414 	     * s1: wheel 1 direction
2415 	     * d1: wheel 1 data
2416 	     * s2: wheel 2 direction
2417 	     * d2: wheel 2 data
2418 	     */
2419 	    x = (pb->ipacket[1] & 0x80) ? pb->ipacket[1] - 256 : pb->ipacket[1];
2420 	    y = (pb->ipacket[2] & 0x80) ? pb->ipacket[2] - 256 : pb->ipacket[2];
2421 	    switch (c & MOUSE_4D_WHEELBITS) {
2422 	    case 0x10:
2423 		z = 1;
2424 		break;
2425 	    case 0x30:
2426 		z = -1;
2427 		break;
2428 	    case 0x40:	/* 2nd wheel turning right XXX */
2429 		z = 2;
2430 		break;
2431 	    case 0xc0:	/* 2nd wheel turning left XXX */
2432 		z = -2;
2433 		break;
2434 	    }
2435 	    break;
2436 
2437 	case MOUSE_MODEL_4DPLUS:
2438 	    if ((x < 16 - 256) && (y < 16 - 256)) {
2439 		/*
2440 		 *          b7 b6 b5 b4 b3 b2 b1 b0
2441 		 * byte 1:  0  0  1  1  1  M  R  L
2442 		 * byte 2:  0  0  0  0  1  0  0  0
2443 		 * byte 3:  0  0  0  0  S  s  d1 d0
2444 		 *
2445 		 * L, M, R, S: left, middle, right and side buttons
2446 		 * s: wheel data sign bit
2447 		 * d1-d0: wheel data
2448 		 */
2449 		x = y = 0;
2450 		if (pb->ipacket[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2451 		    ms.button |= MOUSE_BUTTON4DOWN;
2452 		z = (pb->ipacket[2] & MOUSE_4DPLUS_ZNEG)
2453 			? ((pb->ipacket[2] & 0x07) - 8)
2454 			: (pb->ipacket[2] & 0x07) ;
2455 	    } else {
2456 		/* preserve previous button states */
2457 		ms.button |= ms.obutton & MOUSE_EXTBUTTONS;
2458 	    }
2459 	    break;
2460 
2461 	case MOUSE_MODEL_SYNAPTICS:
2462 	    /* TouchPad PS/2 absolute mode message format
2463 	     *
2464 	     *  Bits:        7   6   5   4   3   2   1   0 (LSB)
2465 	     *  ------------------------------------------------
2466 	     *  ipacket[0]:  1   0  W3  W2   0  W1   R   L
2467 	     *  ipacket[1]: Yb  Ya  Y9  Y8  Xb  Xa  X9  X8
2468 	     *  ipacket[2]: Z7  Z6  Z5  Z4  Z3  Z2  Z1  Z0
2469 	     *  ipacket[3]:  1   1  Yc  Xc   0  W0   D   U
2470 	     *  ipacket[4]: X7  X6  X5  X4  X3  X2  X1  X0
2471 	     *  ipacket[5]: Y7  Y6  Y5  Y4  Y3  Y2  Y1  Y0
2472 	     *
2473 	     * Legend:
2474 	     *  L: left physical mouse button
2475 	     *  R: right physical mouse button
2476 	     *  D: down button
2477 	     *  U: up button
2478 	     *  W: "wrist" value
2479 	     *  X: x position
2480 	     *  Y: x position
2481 	     *  Z: pressure
2482 	     *
2483 	     * Absolute reportable limits:    0 - 6143.
2484 	     * Typical bezel limits:       1472 - 5472.
2485 	     * Typical edge marings:       1632 - 5312.
2486 	     *
2487 	     * w = 3 Passthrough Packet
2488 	     *
2489 	     * Byte 2,5,6 == Byte 1,2,3 of "Guest"
2490 	     */
2491 
2492 	    /* Sanity check for out of sync packets. */
2493 	    if ((pb->ipacket[0] & 0xc8) != 0x80 ||
2494 		(pb->ipacket[3] & 0xc8) != 0xc0)
2495 		continue;
2496 
2497 	    x = y = x0 = y0 = 0;
2498 
2499 	    /* Pressure value. */
2500 	    z = pb->ipacket[2];
2501 	    w = ((pb->ipacket[0] & 0x30) >> 2) |
2502 		((pb->ipacket[0] & 0x04) >> 1) |
2503 		((pb->ipacket[3] & 0x04) >> 2);
2504 
2505 	    ms.button = 0;
2506 	    if (pb->ipacket[0] & 0x01)
2507 		ms.button |= MOUSE_BUTTON1DOWN;
2508 	    if (pb->ipacket[0] & 0x02)
2509 		ms.button |= MOUSE_BUTTON3DOWN;
2510 
2511 	    if ((pb->ipacket[3] & 0x01) && (pb->ipacket[0] & 0x01) == 0)
2512 		ms.button |= MOUSE_BUTTON2DOWN;
2513 	    if ((pb->ipacket[3] & 0x02) && (pb->ipacket[0] & 0x02) == 0)
2514 		ms.button |= MOUSE_BUTTON4DOWN;
2515 
2516 	    /* There is a finger on the pad. */
2517 	    if ((w >= 4 && w <= 7) && (z >= 16 && z < 200)) {
2518 		x0 = ((pb->ipacket[3] & 0x10) << 8) |
2519 		    ((pb->ipacket[1] & 0x0f) << 8) |
2520 		    pb->ipacket[4];
2521 		y0 = ((pb->ipacket[3] & 0x20) << 7) |
2522 		    ((pb->ipacket[1] & 0xf0) << 4) |
2523 		    pb->ipacket[5];
2524 
2525 		if (sc->flags & PSM_FLAGS_FINGERDOWN) {
2526 		    x0 = (x0 + sc->xold * 3) / 4;
2527 		    y0 = (y0 + sc->yold * 3) / 4;
2528 
2529 		    x = (x0 - sc->xold) / 4;
2530 		    y = (y0 - sc->yold) / 4;
2531 		} else {
2532 		    sc->flags |= PSM_FLAGS_FINGERDOWN;
2533 		}
2534 
2535 		sc->xold = x0;
2536 		sc->yold = y0;
2537 	    } else {
2538 		sc->flags &= ~PSM_FLAGS_FINGERDOWN;
2539 	    }
2540 	    z = 0;
2541 	    break;
2542 
2543 	case MOUSE_MODEL_GENERIC:
2544 	default:
2545 	    break;
2546 	}
2547 
2548         /* scale values */
2549         if (sc->mode.accelfactor >= 1) {
2550             if (x != 0) {
2551                 x = x * x / sc->mode.accelfactor;
2552                 if (x == 0)
2553                     x = 1;
2554                 if (c & MOUSE_PS2_XNEG)
2555                     x = -x;
2556             }
2557             if (y != 0) {
2558                 y = y * y / sc->mode.accelfactor;
2559                 if (y == 0)
2560                     y = 1;
2561                 if (c & MOUSE_PS2_YNEG)
2562                     y = -y;
2563             }
2564         }
2565 
2566         ms.dx = x;
2567         ms.dy = y;
2568         ms.dz = z;
2569         ms.flags = ((x || y || z) ? MOUSE_POSCHANGED : 0)
2570 	    | (ms.obutton ^ ms.button);
2571 
2572 	if (sc->mode.level < PSM_LEVEL_NATIVE)
2573 	    pb->inputbytes = tame_mouse(sc, pb, &ms, pb->ipacket);
2574 
2575         sc->status.flags |= ms.flags;
2576         sc->status.dx += ms.dx;
2577         sc->status.dy += ms.dy;
2578         sc->status.dz += ms.dz;
2579         sc->status.button = ms.button;
2580         sc->button = ms.button;
2581 
2582 	sc->watchdog = FALSE;
2583 
2584         /* queue data */
2585         if (sc->queue.count + pb->inputbytes < sizeof(sc->queue.buf)) {
2586 	    l = imin(pb->inputbytes, sizeof(sc->queue.buf) - sc->queue.tail);
2587 	    bcopy(&pb->ipacket[0], &sc->queue.buf[sc->queue.tail], l);
2588 	    if (pb->inputbytes > l)
2589 	        bcopy(&pb->ipacket[l], &sc->queue.buf[0], pb->inputbytes - l);
2590             sc->queue.tail =
2591 		(sc->queue.tail + pb->inputbytes) % sizeof(sc->queue.buf);
2592             sc->queue.count += pb->inputbytes;
2593 	}
2594         pb->inputbytes = 0;
2595 
2596 	if (++sc->pqueue_start >= PSM_PACKETQUEUE)
2597 		sc->pqueue_start = 0;
2598     } while (sc->pqueue_start != sc->pqueue_end);
2599     if (sc->state & PSM_ASLP) {
2600         sc->state &= ~PSM_ASLP;
2601         wakeup( sc);
2602     }
2603     selwakeuppri(&sc->rsel, PZERO);
2604     sc->state &= ~PSM_SOFTARMED;
2605     splx(s);
2606 }
2607 
2608 static int
2609 psmpoll(struct cdev *dev, int events, struct thread *td)
2610 {
2611     struct psm_softc *sc = PSM_SOFTC(PSM_UNIT(dev));
2612     int s;
2613     int revents = 0;
2614 
2615     /* Return true if a mouse event available */
2616     s = spltty();
2617     if (events & (POLLIN | POLLRDNORM)) {
2618 	if (sc->queue.count > 0)
2619 	    revents |= events & (POLLIN | POLLRDNORM);
2620 	else
2621 	    selrecord(td, &sc->rsel);
2622     }
2623     splx(s);
2624 
2625     return (revents);
2626 }
2627 
2628 /* vendor/model specific routines */
2629 
2630 static int mouse_id_proc1(KBDC kbdc, int res, int scale, int *status)
2631 {
2632     if (set_mouse_resolution(kbdc, res) != res)
2633         return FALSE;
2634     if (set_mouse_scaling(kbdc, scale)
2635 	&& set_mouse_scaling(kbdc, scale)
2636 	&& set_mouse_scaling(kbdc, scale)
2637 	&& (get_mouse_status(kbdc, status, 0, 3) >= 3))
2638 	return TRUE;
2639     return FALSE;
2640 }
2641 
2642 static int
2643 mouse_ext_command(KBDC kbdc, int command)
2644 {
2645     int c;
2646 
2647     c = (command >> 6) & 0x03;
2648     if (set_mouse_resolution(kbdc, c) != c)
2649 	return FALSE;
2650     c = (command >> 4) & 0x03;
2651     if (set_mouse_resolution(kbdc, c) != c)
2652 	return FALSE;
2653     c = (command >> 2) & 0x03;
2654     if (set_mouse_resolution(kbdc, c) != c)
2655 	return FALSE;
2656     c = (command >> 0) & 0x03;
2657     if (set_mouse_resolution(kbdc, c) != c)
2658 	return FALSE;
2659     return TRUE;
2660 }
2661 
2662 #if notyet
2663 /* Logitech MouseMan Cordless II */
2664 static int
2665 enable_lcordless(struct psm_softc *sc)
2666 {
2667     int status[3];
2668     int ch;
2669 
2670     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
2671         return FALSE;
2672     if (status[1] == PSMD_RES_HIGH)
2673 	return FALSE;
2674     ch = (status[0] & 0x07) - 1;	/* channel # */
2675     if ((ch <= 0) || (ch > 4))
2676 	return FALSE;
2677     /*
2678      * status[1]: always one?
2679      * status[2]: battery status? (0-100)
2680      */
2681     return TRUE;
2682 }
2683 #endif /* notyet */
2684 
2685 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
2686 static int
2687 enable_groller(struct psm_softc *sc)
2688 {
2689     int status[3];
2690 
2691     /*
2692      * The special sequence to enable the fourth button and the
2693      * roller. Immediately after this sequence check status bytes.
2694      * if the mouse is NetScroll, the second and the third bytes are
2695      * '3' and 'D'.
2696      */
2697 
2698     /*
2699      * If the mouse is an ordinary PS/2 mouse, the status bytes should
2700      * look like the following.
2701      *
2702      * byte 1 bit 7 always 0
2703      *        bit 6 stream mode (0)
2704      *        bit 5 disabled (0)
2705      *        bit 4 1:1 scaling (0)
2706      *        bit 3 always 0
2707      *        bit 0-2 button status
2708      * byte 2 resolution (PSMD_RES_HIGH)
2709      * byte 3 report rate (?)
2710      */
2711 
2712     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2713         return FALSE;
2714     if ((status[1] != '3') || (status[2] != 'D'))
2715         return FALSE;
2716     /* FIXME: SmartScroll Mouse has 5 buttons! XXX */
2717     sc->hw.buttons = 4;
2718     return TRUE;
2719 }
2720 
2721 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
2722 static int
2723 enable_gmouse(struct psm_softc *sc)
2724 {
2725     int status[3];
2726 
2727     /*
2728      * The special sequence to enable the middle, "rubber" button.
2729      * Immediately after this sequence check status bytes.
2730      * if the mouse is NetMouse, NetMouse Pro, or ASCII MIE Mouse,
2731      * the second and the third bytes are '3' and 'U'.
2732      * NOTE: NetMouse reports that it has three buttons although it has
2733      * two buttons and a rubber button. NetMouse Pro and MIE Mouse
2734      * say they have three buttons too and they do have a button on the
2735      * side...
2736      */
2737     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
2738         return FALSE;
2739     if ((status[1] != '3') || (status[2] != 'U'))
2740         return FALSE;
2741     return TRUE;
2742 }
2743 
2744 /* ALPS GlidePoint */
2745 static int
2746 enable_aglide(struct psm_softc *sc)
2747 {
2748     int status[3];
2749 
2750     /*
2751      * The special sequence to obtain ALPS GlidePoint specific
2752      * information. Immediately after this sequence, status bytes will
2753      * contain something interesting.
2754      * NOTE: ALPS produces several models of GlidePoint. Some of those
2755      * do not respond to this sequence, thus, cannot be detected this way.
2756      */
2757     if (set_mouse_sampling_rate(sc->kbdc, 100) != 100)
2758 	return FALSE;
2759     if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
2760         return FALSE;
2761     if ((status[1] == PSMD_RES_LOW) || (status[2] == 100))
2762         return FALSE;
2763     return TRUE;
2764 }
2765 
2766 /* Kensington ThinkingMouse/Trackball */
2767 static int
2768 enable_kmouse(struct psm_softc *sc)
2769 {
2770     static unsigned char rate[] = { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
2771     KBDC kbdc = sc->kbdc;
2772     int status[3];
2773     int id1;
2774     int id2;
2775     int i;
2776 
2777     id1 = get_aux_id(kbdc);
2778     if (set_mouse_sampling_rate(kbdc, 10) != 10)
2779 	return FALSE;
2780     /*
2781      * The device is now in the native mode? It returns a different
2782      * ID value...
2783      */
2784     id2 = get_aux_id(kbdc);
2785     if ((id1 == id2) || (id2 != 2))
2786 	return FALSE;
2787 
2788     if (set_mouse_resolution(kbdc, PSMD_RES_LOW) != PSMD_RES_LOW)
2789         return FALSE;
2790 #if PSM_DEBUG >= 2
2791     /* at this point, resolution is LOW, sampling rate is 10/sec */
2792     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2793         return FALSE;
2794 #endif
2795 
2796     /*
2797      * The special sequence to enable the third and fourth buttons.
2798      * Otherwise they behave like the first and second buttons.
2799      */
2800     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2801         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2802 	    return FALSE;
2803     }
2804 
2805     /*
2806      * At this point, the device is using default resolution and
2807      * sampling rate for the native mode.
2808      */
2809     if (get_mouse_status(kbdc, status, 0, 3) < 3)
2810         return FALSE;
2811     if ((status[1] == PSMD_RES_LOW) || (status[2] == rate[i - 1]))
2812         return FALSE;
2813 
2814     /* the device appears be enabled by this sequence, diable it for now */
2815     disable_aux_dev(kbdc);
2816     empty_aux_buffer(kbdc, 5);
2817 
2818     return TRUE;
2819 }
2820 
2821 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
2822 static int
2823 enable_mmanplus(struct psm_softc *sc)
2824 {
2825     KBDC kbdc = sc->kbdc;
2826     int data[3];
2827 
2828     /* the special sequence to enable the fourth button and the roller. */
2829     /*
2830      * NOTE: for ScrollPoint to respond correctly, the SET_RESOLUTION
2831      * must be called exactly three times since the last RESET command
2832      * before this sequence. XXX
2833      */
2834     if (!set_mouse_scaling(kbdc, 1))
2835 	return FALSE;
2836     if (!mouse_ext_command(kbdc, 0x39) || !mouse_ext_command(kbdc, 0xdb))
2837 	return FALSE;
2838     if (get_mouse_status(kbdc, data, 1, 3) < 3)
2839         return FALSE;
2840 
2841     /*
2842      * PS2++ protocl, packet type 0
2843      *
2844      *          b7 b6 b5 b4 b3 b2 b1 b0
2845      * byte 1:  *  1  p3 p2 1  *  *  *
2846      * byte 2:  1  1  p1 p0 m1 m0 1  0
2847      * byte 3:  m7 m6 m5 m4 m3 m2 m1 m0
2848      *
2849      * p3-p0: packet type: 0
2850      * m7-m0: model ID: MouseMan+:0x50, FirstMouse+:0x51, ScrollPoint:0x58...
2851      */
2852     /* check constant bits */
2853     if ((data[0] & MOUSE_PS2PLUS_SYNCMASK) != MOUSE_PS2PLUS_SYNC)
2854         return FALSE;
2855     if ((data[1] & 0xc3) != 0xc2)
2856         return FALSE;
2857     /* check d3-d0 in byte 2 */
2858     if (!MOUSE_PS2PLUS_CHECKBITS(data))
2859         return FALSE;
2860     /* check p3-p0 */
2861     if (MOUSE_PS2PLUS_PACKET_TYPE(data) != 0)
2862         return FALSE;
2863 
2864     sc->hw.hwid &= 0x00ff;
2865     sc->hw.hwid |= data[2] << 8;	/* save model ID */
2866 
2867     /*
2868      * MouseMan+ (or FirstMouse+) is now in its native mode, in which
2869      * the wheel and the fourth button events are encoded in the
2870      * special data packet. The mouse may be put in the IntelliMouse mode
2871      * if it is initialized by the IntelliMouse's method.
2872      */
2873     return TRUE;
2874 }
2875 
2876 /* MS IntelliMouse Explorer */
2877 static int
2878 enable_msexplorer(struct psm_softc *sc)
2879 {
2880     static unsigned char rate0[] = { 200, 100, 80, };
2881     static unsigned char rate1[] = { 200, 200, 80, };
2882     KBDC kbdc = sc->kbdc;
2883     int id;
2884     int i;
2885 
2886     /* the special sequence to enable the extra buttons and the roller. */
2887     for (i = 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i) {
2888         if (set_mouse_sampling_rate(kbdc, rate1[i]) != rate1[i])
2889 	    return FALSE;
2890     }
2891     /* the device will give the genuine ID only after the above sequence */
2892     id = get_aux_id(kbdc);
2893     if (id != PSM_EXPLORER_ID)
2894 	return FALSE;
2895 
2896     sc->hw.hwid = id;
2897     sc->hw.buttons = 5;		/* IntelliMouse Explorer XXX */
2898 
2899     /*
2900      * XXX: this is a kludge to fool some KVM switch products
2901      * which think they are clever enough to know the 4-byte IntelliMouse
2902      * protocol, and assume any other protocols use 3-byte packets.
2903      * They don't convey 4-byte data packets from the IntelliMouse Explorer
2904      * correctly to the host computer because of this!
2905      * The following sequence is actually IntelliMouse's "wake up"
2906      * sequence; it will make the KVM think the mouse is IntelliMouse
2907      * when it is in fact IntelliMouse Explorer.
2908      */
2909     for (i = 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i) {
2910         if (set_mouse_sampling_rate(kbdc, rate0[i]) != rate0[i])
2911 	    break;
2912     }
2913     id = get_aux_id(kbdc);
2914 
2915     return TRUE;
2916 }
2917 
2918 /* MS IntelliMouse */
2919 static int
2920 enable_msintelli(struct psm_softc *sc)
2921 {
2922     /*
2923      * Logitech MouseMan+ and FirstMouse+ will also respond to this
2924      * probe routine and act like IntelliMouse.
2925      */
2926 
2927     static unsigned char rate[] = { 200, 100, 80, };
2928     KBDC kbdc = sc->kbdc;
2929     int id;
2930     int i;
2931 
2932     /* the special sequence to enable the third button and the roller. */
2933     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2934         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2935 	    return FALSE;
2936     }
2937     /* the device will give the genuine ID only after the above sequence */
2938     id = get_aux_id(kbdc);
2939     if (id != PSM_INTELLI_ID)
2940 	return FALSE;
2941 
2942     sc->hw.hwid = id;
2943     sc->hw.buttons = 3;
2944 
2945     return TRUE;
2946 }
2947 
2948 /* A4 Tech 4D Mouse */
2949 static int
2950 enable_4dmouse(struct psm_softc *sc)
2951 {
2952     /*
2953      * Newer wheel mice from A4 Tech may use the 4D+ protocol.
2954      */
2955 
2956     static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
2957     KBDC kbdc = sc->kbdc;
2958     int id;
2959     int i;
2960 
2961     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2962         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2963 	    return FALSE;
2964     }
2965     id = get_aux_id(kbdc);
2966     /*
2967      * WinEasy 4D, 4 Way Scroll 4D: 6
2968      * Cable-Free 4D: 8 (4DPLUS)
2969      * WinBest 4D+, 4 Way Scroll 4D+: 8 (4DPLUS)
2970      */
2971     if (id != PSM_4DMOUSE_ID)
2972 	return FALSE;
2973 
2974     sc->hw.hwid = id;
2975     sc->hw.buttons = 3;		/* XXX some 4D mice have 4? */
2976 
2977     return TRUE;
2978 }
2979 
2980 /* A4 Tech 4D+ Mouse */
2981 static int
2982 enable_4dplus(struct psm_softc *sc)
2983 {
2984     /*
2985      * Newer wheel mice from A4 Tech seem to use this protocol.
2986      * Older models are recognized as either 4D Mouse or IntelliMouse.
2987      */
2988     KBDC kbdc = sc->kbdc;
2989     int id;
2990 
2991     /*
2992      * enable_4dmouse() already issued the following ID sequence...
2993     static unsigned char rate[] = { 200, 100, 80, 60, 40, 20 };
2994     int i;
2995 
2996     for (i = 0; i < sizeof(rate)/sizeof(rate[0]); ++i) {
2997         if (set_mouse_sampling_rate(kbdc, rate[i]) != rate[i])
2998 	    return FALSE;
2999     }
3000     */
3001 
3002     id = get_aux_id(kbdc);
3003     switch (id) {
3004     case PSM_4DPLUS_ID:
3005 	    sc->hw.buttons = 4;
3006 	    break;
3007     case PSM_4DPLUS_RFSW35_ID:
3008 	    sc->hw.buttons = 3;
3009 	    break;
3010     default:
3011 	    return FALSE;
3012     }
3013 
3014     sc->hw.hwid = id;
3015 
3016     return TRUE;
3017 }
3018 
3019 /* Synaptics Touchpad */
3020 static int
3021 enable_synaptics(struct psm_softc *sc)
3022 {
3023     int status[3];
3024     KBDC kbdc;
3025 
3026     kbdc = sc->kbdc;
3027     disable_aux_dev(kbdc);
3028 
3029     /* Just to be on the safe side */
3030     set_mouse_scaling(kbdc, 1);
3031 
3032     if (mouse_ext_command(kbdc, 0) == 0)
3033 	return (FALSE);
3034     if (get_mouse_status(kbdc, status, 0, 3) != 3)
3035 	return (FALSE);
3036 
3037     /* If it is a Synaptics, byte 2 is 0x47. */
3038     if (status[1] != 0x47)
3039 	return (FALSE);
3040 
3041     /*
3042      * Identify the Touchpad version.  The first byte contains the minor
3043      * version number, the lower 4 bits of the third byte contain infoMajor,
3044      * and the upper 4 bits contain the (obsolete) infoModelCode.
3045      */
3046     sc->synhw.infoMinor = status[0];
3047     sc->synhw.infoMajor = status[2] & 0x0f;
3048     if (verbose >= 2) {
3049 	printf("Synaptics Touchpad:\n");
3050 	printf("  Version: %d.%d\n", sc->synhw.infoMajor, sc->synhw.infoMinor);
3051     }
3052     if (sc->synhw.infoMajor < 4) {
3053 	printf("Synaptics Version less than 4 detected, not yet supported\n");
3054 	return (FALSE);
3055     }
3056 
3057     if (mouse_ext_command(kbdc, 3) == 0)
3058 	return (FALSE);
3059     if (get_mouse_status(kbdc, status, 0, 3) != 3)
3060 	return (FALSE);
3061     if ((status[1] & 0x01) != 0) {
3062 	printf("  Could not read model id bytes from the Touchpad\n");
3063 	return (FALSE);
3064     }
3065 
3066     sc->synhw.infoRot180   = (status[0] & 0x80) >> 7;
3067     sc->synhw.infoPortrait = (status[0] & 0x40) >> 6;
3068     sc->synhw.infoSensor   =  status[0] & 0x3f;
3069     sc->synhw.infoHardware = (status[1] & 0xfe) >> 1;
3070     sc->synhw.infoNewAbs   = (status[2] & 0x80) >> 7;
3071     sc->synhw.capPen       = (status[2] & 0x40) >> 6;
3072     sc->synhw.infoSimplC   = (status[2] & 0x20) >> 5;
3073     sc->synhw.infoGeometry =  status[2] & 0x0f;
3074     if (verbose >= 2) {
3075 	printf("  Model id: %02x %02x %02x\n", status[0] , status[1] ,
3076 	    status[2]);
3077 	printf(" infoRot180: %d\n",sc->synhw.infoRot180);
3078 	printf(" infoPortrait: %d\n",sc->synhw.infoPortrait);
3079 	printf(" infoSensor: %d\n",sc->synhw.infoSensor);
3080 	printf(" infoHardware: %d\n",sc->synhw.infoHardware);
3081 	printf(" infoNewAbs: %d\n",sc->synhw.infoNewAbs);
3082 	printf(" capPen: %d\n",sc->synhw.capPen);
3083 	printf(" infoSimplC: %d\n",sc->synhw.infoSimplC);
3084 	printf(" infoGeometry: %d\n",sc->synhw.infoGeometry);
3085     }
3086 
3087     if (mouse_ext_command(kbdc, 2) == 0)
3088 	return (FALSE);
3089     if (get_mouse_status(kbdc, status, 0, 3) != 3)
3090 	return (FALSE);
3091     if (status[1] != 0x47) {
3092 	printf("  Could not read capabilities from the Touchpad\n");
3093 	return (FALSE);
3094     }
3095     sc->synhw.capExtended    = (status[0] & 0x80) >> 7;
3096     sc->synhw.capPassthrough = (status[2] & 0x80) >> 7;
3097     sc->synhw.capSleep       = (status[2] & 0x10) >> 4;
3098     sc->synhw.capFourButtons = (status[2] & 0x08) >> 3;
3099     sc->synhw.capMultiFinger = (status[2] & 0x02) >> 1;
3100     sc->synhw.capPalmDetect  = (status[2] & 0x01);
3101     if (verbose >= 2)
3102 	printf("  Capability Bytes: %02x %02x %02x\n", status[0], status[1],
3103 	    status[2]);
3104 
3105     if (mouse_ext_command(kbdc, 1) == 0)
3106 	return (FALSE);
3107     if (get_mouse_status(kbdc, status, 0, 3) != 3)
3108 	return (FALSE);
3109     if (status[0] != 0x3b || status[1] != 0x47) {
3110 	printf("  Could not read mode byte from the Touchpad\n");
3111 	return (FALSE);
3112     }
3113     if (verbose >= 2)
3114 	printf("  Mode byte set by BIOS: %02x\n", status[2]);
3115 
3116     /*
3117      * Mode byte values:
3118      * 1 (absolute)
3119      * 1 rate (0 = 40/1 = 80)
3120      * 0
3121      * 0 (reserved)
3122      * 0 (Sleep (Only buttons))
3123      * 0 DisGest (not for absolute Mode)
3124      * 0 pktsize (0 for ps2)
3125      * 1 wmode
3126      */
3127     sc->hw.buttons = 3;
3128 
3129     /* Set encode mode byte and sampling rate. */
3130     mouse_ext_command(kbdc, 0xc1);
3131     set_mouse_sampling_rate(kbdc, 20);
3132 
3133     return (TRUE);
3134 }
3135 /* Interlink electronics VersaPad */
3136 static int
3137 enable_versapad(struct psm_softc *sc)
3138 {
3139     KBDC kbdc = sc->kbdc;
3140     int data[3];
3141 
3142     set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
3143     set_mouse_sampling_rate(kbdc, 100);		/* set rate 100 */
3144     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3145     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3146     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3147     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3148     if (get_mouse_status(kbdc, data, 0, 3) < 3)	/* get status */
3149 	return FALSE;
3150     if (data[2] != 0xa || data[1] != 0 )	/* rate == 0xa && res. == 0 */
3151 	return FALSE;
3152     set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
3153 
3154     sc->config |= PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
3155 
3156     return TRUE;				/* PS/2 absolute mode */
3157 }
3158 
3159 static int
3160 psmresume(device_t dev)
3161 {
3162     struct psm_softc *sc = device_get_softc(dev);
3163     int unit = device_get_unit(dev);
3164     int err;
3165 
3166     if (verbose >= 2)
3167         log(LOG_NOTICE, "psm%d: system resume hook called.\n", unit);
3168 
3169     if (!(sc->config & PSM_CONFIG_HOOKRESUME))
3170 	return (0);
3171 
3172     err = reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
3173 
3174     if ((sc->state & PSM_ASLP) && !(sc->state & PSM_VALID)) {
3175 	/*
3176 	 * Release the blocked process; it must be notified that the device
3177 	 * cannot be accessed anymore.
3178 	 */
3179         sc->state &= ~PSM_ASLP;
3180         wakeup(sc);
3181     }
3182 
3183     if (verbose >= 2)
3184         log(LOG_DEBUG, "psm%d: system resume hook exiting.\n", unit);
3185 
3186     return (err);
3187 }
3188 
3189 DRIVER_MODULE(psm, atkbdc, psm_driver, psm_devclass, 0, 0);
3190 
3191 /*
3192  * This sucks up assignments from PNPBIOS and ACPI.
3193  */
3194 
3195 /*
3196  * When the PS/2 mouse device is reported by ACPI or PnP BIOS, it may
3197  * appear BEFORE the AT keyboard controller.  As the PS/2 mouse device
3198  * can be probed and attached only after the AT keyboard controller is
3199  * attached, we shall quietly reserve the IRQ resource for later use.
3200  * If the PS/2 mouse device is reported to us AFTER the keyboard controller,
3201  * copy the IRQ resource to the PS/2 mouse device instance hanging
3202  * under the keyboard controller, then probe and attach it.
3203  */
3204 
3205 static	devclass_t			psmcpnp_devclass;
3206 
3207 static	device_probe_t			psmcpnp_probe;
3208 static	device_attach_t			psmcpnp_attach;
3209 
3210 static device_method_t psmcpnp_methods[] = {
3211 	DEVMETHOD(device_probe,		psmcpnp_probe),
3212 	DEVMETHOD(device_attach,	psmcpnp_attach),
3213 
3214 	{ 0, 0 }
3215 };
3216 
3217 static driver_t psmcpnp_driver = {
3218 	PSMCPNP_DRIVER_NAME,
3219 	psmcpnp_methods,
3220 	1,			/* no softc */
3221 };
3222 
3223 static struct isa_pnp_id psmcpnp_ids[] = {
3224 	{ 0x030fd041, "PS/2 mouse port" },		/* PNP0F03 */
3225 	{ 0x130fd041, "PS/2 mouse port" },		/* PNP0F13 */
3226 	{ 0x1303d041, "PS/2 port" },			/* PNP0313, XXX */
3227 	{ 0x02002e4f, "Dell PS/2 mouse port" },		/* Lat. X200, Dell */
3228 	{ 0x80374d24, "IBM PS/2 mouse port" },		/* IBM3780, ThinkPad */
3229 	{ 0x81374d24, "IBM PS/2 mouse port" },		/* IBM3781, ThinkPad */
3230 	{ 0x0190d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9001, Vaio */
3231 	{ 0x0290d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9002, Vaio */
3232 	{ 0x0390d94d, "SONY VAIO PS/2 mouse port"},	/* SNY9003, Vaio */
3233 	{ 0x0490d94d, "SONY VAIO PS/2 mouse port"},     /* SNY9004, Vaio */
3234 	{ 0 }
3235 };
3236 
3237 static int
3238 create_a_copy(device_t atkbdc, device_t me)
3239 {
3240 	device_t psm;
3241 	u_long irq;
3242 
3243 	/* find the PS/2 mouse device instance under the keyboard controller */
3244 	psm = device_find_child(atkbdc, PSM_DRIVER_NAME,
3245 				device_get_unit(atkbdc));
3246 	if (psm == NULL)
3247 		return ENXIO;
3248 	if (device_get_state(psm) != DS_NOTPRESENT)
3249 		return 0;
3250 
3251 	/* move our resource to the found device */
3252 	irq = bus_get_resource_start(me, SYS_RES_IRQ, 0);
3253 	bus_set_resource(psm, SYS_RES_IRQ, KBDC_RID_AUX, irq, 1);
3254 
3255 	/* ...then probe and attach it */
3256 	return device_probe_and_attach(psm);
3257 }
3258 
3259 static int
3260 psmcpnp_probe(device_t dev)
3261 {
3262 	struct resource *res;
3263 	u_long irq;
3264 	int rid;
3265 
3266 	if (ISA_PNP_PROBE(device_get_parent(dev), dev, psmcpnp_ids))
3267 		return ENXIO;
3268 
3269 	/*
3270 	 * The PnP BIOS and ACPI are supposed to assign an IRQ (12)
3271 	 * to the PS/2 mouse device node. But, some buggy PnP BIOS
3272 	 * declares the PS/2 mouse device node without an IRQ resource!
3273 	 * If this happens, we shall refer to device hints.
3274 	 * If we still don't find it there, use a hardcoded value... XXX
3275 	 */
3276 	rid = 0;
3277 	irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
3278 	if (irq <= 0) {
3279 		if (resource_long_value(PSM_DRIVER_NAME,
3280 					device_get_unit(dev), "irq", &irq) != 0)
3281 			irq = 12;	/* XXX */
3282 		device_printf(dev, "irq resource info is missing; "
3283 			      "assuming irq %ld\n", irq);
3284 		bus_set_resource(dev, SYS_RES_IRQ, rid, irq, 1);
3285 	}
3286 	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
3287 				     RF_SHAREABLE);
3288 	bus_release_resource(dev, SYS_RES_IRQ, rid, res);
3289 
3290 	/* keep quiet */
3291 	if (!bootverbose)
3292 		device_quiet(dev);
3293 
3294 	return ((res == NULL) ? ENXIO : 0);
3295 }
3296 
3297 static int
3298 psmcpnp_attach(device_t dev)
3299 {
3300 	device_t atkbdc;
3301 	int rid;
3302 
3303 	/* find the keyboard controller, which may be on acpi* or isa* bus */
3304 	atkbdc = devclass_get_device(devclass_find(ATKBDC_DRIVER_NAME),
3305 				     device_get_unit(dev));
3306 	if ((atkbdc != NULL) && (device_get_state(atkbdc) == DS_ATTACHED)) {
3307 		create_a_copy(atkbdc, dev);
3308 	} else {
3309 		/*
3310 		 * If we don't have the AT keyboard controller yet,
3311 		 * just reserve the IRQ for later use...
3312 		 * (See psmidentify() above.)
3313 		 */
3314 		rid = 0;
3315 		bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_SHAREABLE);
3316 	}
3317 
3318 	return 0;
3319 }
3320 
3321 /*
3322  * Return true if 'now' is earlier than (start + (secs.usecs)).
3323  * Now may be NULL and the function will fetch the current time from
3324  * getmicrouptime(), or a cached 'now' can be passed in.
3325  * All values should be numbers derived from getmicrouptime().
3326  */
3327 static int
3328 timeelapsed(start, secs, usecs, now)
3329 	const struct timeval *start, *now;
3330 	int secs, usecs;
3331 {
3332 	struct timeval snow, tv;
3333 
3334 	/* if there is no 'now' passed in, the get it as a convience. */
3335 	if (now == NULL) {
3336 		getmicrouptime(&snow);
3337 		now = &snow;
3338 	}
3339 
3340 	tv.tv_sec = secs;
3341 	tv.tv_usec = usecs;
3342 	timevaladd(&tv, start);
3343 	return (timevalcmp(&tv, now, <));
3344 }
3345 
3346 DRIVER_MODULE(psmcpnp, isa, psmcpnp_driver, psmcpnp_devclass, 0, 0);
3347 DRIVER_MODULE(psmcpnp, acpi, psmcpnp_driver, psmcpnp_devclass, 0, 0);
3348