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